From 9c33714591a2147f7e5879e77212ca9886d0c967 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 25 Sep 2026 21:47:58 -0300 Subject: Put the game first: lib/sketchbook, sketches/vecanim The root is the game. The platform library moves to lib/sketchbook (with serve_web.py, which serves any sketch's web build, as a tool of it), and vecanim to sketches/vecanim, still its own package on the same library. --- .gitignore | 3 + README.md | 160 +++++++++ build.zig | 513 +++++++++++++++++++++++++++ build.zig.zon | 17 + src/abi.zig | 524 +++++++++++++++++++++++++++ src/glsl.zig | 158 +++++++++ src/host/Console.zig | 260 ++++++++++++++ src/host/Host.zig | 545 ++++++++++++++++++++++++++++ src/host/audio.zig | 284 +++++++++++++++ src/host/fields.zig | 116 ++++++ src/host/gfx.zig | 177 +++++++++ src/host/gpu.zig | 346 ++++++++++++++++++ src/host/library.zig | 83 +++++ src/host/memory.zig | 406 +++++++++++++++++++++ src/host/overlay.zig | 76 ++++ src/host/probe.zig | 64 ++++ src/host/root.zig | 138 ++++++++ src/host/script.zig | 139 ++++++++ src/host/timeline.zig | 208 +++++++++++ src/keys.zig | 107 ++++++ src/layout.zig | 148 ++++++++ src/main.zig | 6 + src/sketch/camera.zig | 60 ++++ src/sketch/root.zig | 215 +++++++++++ src/sketch/shape.zig | 209 +++++++++++ src/sketch/tween.zig | 133 +++++++ src/sketch/web.zig | 201 +++++++++++ src/vector/Cpu.zig | 185 ++++++++++ src/vector/Drawing.zig | 195 ++++++++++ src/vector/Gpu.zig | 174 +++++++++ src/vector/Paint.zig | 110 ++++++ src/vector/Polygons.zig | 395 +++++++++++++++++++++ src/vector/geom.zig | 239 +++++++++++++ src/vector/layouts.zig | 40 +++ src/vector/morph.zig | 178 ++++++++++ src/vector/root.zig | 144 ++++++++ src/vector/shaders/cover.frag | 65 ++++ src/vector/shaders/path.vert | 9 + src/vector/shaders/stencil.frag | 7 + src/vector/svg.zig | 768 ++++++++++++++++++++++++++++++++++++++++ test/counter_v1.zig | 24 ++ test/counter_v2.zig | 23 ++ test/readme.zig | 16 + test/reload.script | 18 + tools/serve_web.py | 32 ++ web/host.js | 167 +++++++++ web/index.html | 18 + 47 files changed, 8103 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 build.zig create mode 100644 build.zig.zon create mode 100644 src/abi.zig create mode 100644 src/glsl.zig create mode 100644 src/host/Console.zig create mode 100644 src/host/Host.zig create mode 100644 src/host/audio.zig create mode 100644 src/host/fields.zig create mode 100644 src/host/gfx.zig create mode 100644 src/host/gpu.zig create mode 100644 src/host/library.zig create mode 100644 src/host/memory.zig create mode 100644 src/host/overlay.zig create mode 100644 src/host/probe.zig create mode 100644 src/host/root.zig create mode 100644 src/host/script.zig create mode 100644 src/host/timeline.zig create mode 100644 src/keys.zig create mode 100644 src/layout.zig create mode 100644 src/main.zig create mode 100644 src/sketch/camera.zig create mode 100644 src/sketch/root.zig create mode 100644 src/sketch/shape.zig create mode 100644 src/sketch/tween.zig create mode 100644 src/sketch/web.zig create mode 100644 src/vector/Cpu.zig create mode 100644 src/vector/Drawing.zig create mode 100644 src/vector/Gpu.zig create mode 100644 src/vector/Paint.zig create mode 100644 src/vector/Polygons.zig create mode 100644 src/vector/geom.zig create mode 100644 src/vector/layouts.zig create mode 100644 src/vector/morph.zig create mode 100644 src/vector/root.zig create mode 100644 src/vector/shaders/cover.frag create mode 100644 src/vector/shaders/path.vert create mode 100644 src/vector/shaders/stencil.frag create mode 100644 src/vector/svg.zig create mode 100644 test/counter_v1.zig create mode 100644 test/counter_v2.zig create mode 100644 test/readme.zig create mode 100644 test/reload.script create mode 100644 tools/serve_web.py create mode 100644 web/host.js create mode 100644 web/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..895f4e6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +zig-out/ +zig-pkg/ +.zig-cache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..6531fcd --- /dev/null +++ b/README.md @@ -0,0 +1,160 @@ +# sketchbook + +A small Zig 0.16 platform for sketching games and toys, in the spirit of +Processing and pygame: write plain data and two functions, save, and the +running program picks up the new code with its state intact. + +```zig +const sk = @import("sketch"); + +pub const State = struct { x: f32 = 480, y: f32 = 300, hue: f32 = 0 }; + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.pressed(sk.Key.space)) s.hue += 30; + s.x += (in.mouse_x - s.x) * 0.1; + s.y += (in.mouse_y - s.y) * 0.1; +} + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(0x202020); + f.fill(.{ .x = s.x - 10, .y = s.y - 10, .w = 20, .h = 20 }, 0xff8040); + f.print(8, 8, 2, 0xffffff, "hue {d}", .{s.hue}); +} +``` + +## An app + +An app is an ordinary module. Every declaration is optional: + +| Declaration | Meaning | +| --- | --- | +| `name`, `width`, `height` | Window title and initial canvas | +| `State` | Persistent state: saved to a file, snapshotted, replayed. No pointers (compile error). | +| `Session` | Survives reloads, never saved: caches, loaded handles, audio buffers. May point into host memory. | +| `init(state, host)` | Setup for brand-new state, after the declared defaults | +| `update(state, input)` | **Deterministic**: the host replays recorded input through it | +| `draw(state, session, frame)` | Pictures and sound, as commands; may change only `Session` | +| `command(state, session, console, line) !bool` | Console lines the host does not know | +| `commands` | Console completions | + +`update` sees `input.events`: pointer, wheel, key, text, `cancel` (focus loss, +console) and one `tick` per frame carrying `dt`. Recorded ticks make +time-driven sketches replay exactly. + +`draw` gets a `Frame`: `clear`, `fill`, `image`, `text`, `print`, `clip`, +`canvas`, `cursor`, `voice`, `audio`, `pixels`, `quit`, plus `f.arena` (frame +lifetime), `f.gpa` (session lifetime) and `f.host` (`loadImage`, +`decodeImage`, `newImage`, `loadSound`, `decodeSound`, `readFile`, `env`, +`log`). + +Geometry and colors are duck-typed. Anything with `x`/`y` is a point, anything +that also has `w`/`h` (or `width`/`height`) is a rect, in any number type, and +`@Vector`s or arrays work too. Colors are `r`/`g`/`b`[/`a`] or `0xRRGGBB`. The +helpers return the caller's own type: + +- `sk.shape`: `isPoint`/`isRect`/`isColor`, `contains`, `inset`, `offset` +- `sk.Camera`: `toScreen`, `toWorld`, `pan`, `zoomAt` +- `sk.tween`: `lerp` over any plain data, `lerpFields(a, b, t, .{ .x, .zoom })`, `toward(a, .{ .x = 100 }, t)`, and `ease` + +**Vector graphics**, in the `vector` module (import `sb.modules.vector`): +SVG parsing (the static subset Typst emits, and more) into cubic Bézier +data; flattening, stroking, dashing, trimming, clipping and morphing as +geometry; and `vector.Renderer(.gpu)` or `vector.Renderer(.cpu)`. The CPU +backend computes exact coverage and runs anywhere, wasm included. The GPU +backend describes stencil-then-cover passes (8× MSAA, gradients in a +shader). Both are tested against resvg (see `sketches/vecanim` in the game repository). + +**GPU work is data.** A sketch describes pipelines (SPIR-V, vertex layout, +blend, stencil) and passes (`f.gpu(.{ .image, .pipelines, .draws, ... })`); +the host runs them with SDL_GPU. It caches shaders and pipelines by content +hash, so an edited shader is just a new pipeline after a reload. No sketch +touches a graphics API, and another host (Vulkan, WebGPU) would be another +translation of the same data. `abi.gpu.pipeline(Vertex, ...)` derives the +vertex layout from a struct, and `abi.gpu.uniform` checks std140 at +compile time. + +Sound is declarative. `f.voice(.{ .key, .audio, .serial, .loop, .volume })` +declares a voice that should be sounding. A new key or serial starts it, and +an undeclared key stops it. A finished one-shot stays finished while it is +still declared, so replays and seeks never re-fire sounds. `f.audio(key, +samples, .{})` streams PCM, and `input.stream(key)` reports what the host has +queued and played. + +## The host + +- **Hot reload.** It watches the library file and loads each new build through + a private copy. +- **State file.** `.state` holds the live state plus 7 snapshot slots, + shared via `MAP_SHARED`. Its header carries the reflected layout, so a + layout change migrates every slot field by field, with enums matched by tag + name, and `sketchbook-probe` can print any sketch's state. +- **Time travel.** Recordings, replay, seek and step work on any sketch, + because they only need state bytes and events. +- **Console and overlays.** `get`/`set `, snapshots, recordings and + the memory and scope overlays come from the host; unknown lines go to the + sketch. +- **Scripts** (`--headless --fresh --script file`) drive the same routing and + frames as a player: `click`, `key`, `type`, `console`, `expect field value`, + `expect-audio`, `screenshot`, `load`, `await-reload`. +- **GPU.** The host's 2D renderer runs on an SDL GPU device, which also + runs sketches' GPU passes. Without a GPU it falls back to any renderer. +- **Memory.** SDL allocations go through a leak-checking allocator; a leak + fails the exit. + +## Build API + +```zig +const sketchbook = @import("sketchbook"); + +pub fn build(b: *std.Build) void { + const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); + const app = sb.app(.{ .name = "demo", .root_source_file = b.path("src/main.zig") }); + _ = app.addSteps(.{ .scripts = &.{b.path("test/play.script")} }); +} +``` + +`addSteps` installs the executable and adds `run`, `lib`, `web`, `probe`, +`e2e` and `test`. Every piece is also available on its own and returns plain +`std.Build` objects: + +| Call | Returns | +| --- | --- | +| `app.addLibrary()` | the hot-reloadable shared library | +| `app.addExecutable()` | host and sketch linked into one binary | +| `app.addWeb(.{ .assets = ... })` | the wasm module and a ready-to-serve directory | +| `app.addRun(lib, .{})` | the generic host running the installed library | +| `app.addScript(exe, file, .{})` | a headless, fresh-state scripted run | +| `app.addProbe(state)` | the probe on a state file | +| `app.addTest(.{})` | tests with the app importable as `app` | + +Shaders, in the same style: + +```zig +const layouts = sb.addGlslLayouts(.{ .module = my_layouts, .types = &.{ "Vertex", "Paint" } }); +const shaders = sb.addSpirvModule(&.{ + .{ .name = "fill_vert", .spirv = sb.addGlslc(.{ .source = b.path("fill.vert"), .include_dirs = &.{layouts.dir} }).spirv }, +}); +``` + +`addGlslLayouts` writes `.glsl` declarations generated from Zig +structs (tagged with `pub const glsl = .vertex` or +`.{ .uniform = .{ .set, .instance } }`), so the Zig struct is the one +definition. `addGlslc` compiles one file. `addSpirvModule` embeds the +results, aligned for Vulkan. + +`sb.modules`, `sb.host_exe` and `sb.probe_exe` are exposed for anything else. +Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`. + +## The boundary + +Host and sketch are built by the same `zig build`, so ordinary Zig types cross +it (slices, tagged unions, `std.mem.Allocator`). `abi.hash`, a comptime hash +of every shared type's layout, guards against the one real hazard: a host +refuses a library built against different definitions. Everything that outlives +a call lives in host memory, since host code is never unloaded. Only the +recorded `Event` and the reflected `Layout` are `extern`, because they are +written to disk. + +`zig build test` in this directory runs the unit tests and a headless reload +through `dlopen`, where a counter sketch changes its layout mid-run and keeps +its values. diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..9fc9049 --- /dev/null +++ b/build.zig @@ -0,0 +1,513 @@ +//! sketchbook: a host that hot-reloads sketches, and the library they use. +//! +//! Apps use it from their own build.zig: +//! +//! const sketchbook = @import("sketchbook"); +//! +//! const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); +//! const app = sb.app(.{ .name = "demo", .root_source_file = b.path("src/main.zig") }); +//! _ = app.addSteps(.{}); // run, lib, web, probe, e2e, test, install +//! +//! or pick the pieces: `app.addLibrary()`, `app.addExecutable()`, +//! `app.addWeb(...)`, `app.addRun(...)`, `app.addScript(...)`, +//! `app.addProbe(...)`, `app.addTest(...)`. For GPU shaders: +//! `sb.addGlslLayouts(...)`, `sb.addGlslc(...)`, `sb.addSpirvModule(...)`. +//! Each returns the ordinary `std.Build` objects, so anything can be +//! extended or rewired. +const std = @import("std"); +const Build = std.Build; +const translate_c = @import("translate_c"); + +pub fn build(b: *Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + + // Target-free: they compile for whatever imports them, native or wasm. + const abi = b.addModule("abi", .{ .root_source_file = b.path("src/abi.zig") }); + const sketch = b.addModule("sketch", .{ + .root_source_file = b.path("src/sketch/root.zig"), + .imports = &.{.{ .name = "abi", .module = abi }}, + }); + + const c = cModule(b, target, optimize); + const host = b.addModule("host", .{ + .root_source_file = b.path("src/host/root.zig"), + .target = target, + .optimize = optimize, + .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c } }, + }); + + const host_exe = b.addExecutable(.{ + .name = "sketchbook", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "host", .module = host }}, + }), + }); + b.installArtifact(host_exe); + + const probe = b.addExecutable(.{ + .name = "sketchbook-probe", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/host/probe.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "abi", .module = abi }}, + }), + }); + b.installArtifact(probe); + + var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig") }; + + // Vector graphics: built with the same shader step apps use. + const vector_layouts = b.createModule(.{ .root_source_file = b.path("src/vector/layouts.zig") }); + const glsl = sb.addGlslLayouts(.{ .module = vector_layouts, .types = &.{ "Vertex", "Viewport", "Paint" } }); + const vector_shaders = sb.addSpirvModule(&.{ + .{ .name = "path_vert", .spirv = sb.addGlslc(.{ .source = b.path("src/vector/shaders/path.vert"), .include_dirs = &.{glsl.dir} }).spirv }, + .{ .name = "stencil_frag", .spirv = sb.addGlslc(.{ .source = b.path("src/vector/shaders/stencil.frag") }).spirv }, + .{ .name = "cover_frag", .spirv = sb.addGlslc(.{ .source = b.path("src/vector/shaders/cover.frag"), .include_dirs = &.{glsl.dir} }).spirv }, + }); + const vector_imports: []const Build.Module.Import = &.{ + .{ .name = "abi", .module = abi }, + .{ .name = "vector_layouts", .module = vector_layouts }, + .{ .name = "vector_shaders", .module = vector_shaders }, + }; + sb.modules.vector = b.addModule("vector", .{ .root_source_file = b.path("src/vector/root.zig"), .imports = vector_imports }); + + const test_step = b.step("test", "Run unit tests and the reload end-to-end test"); + for ([_]*Build.Module{ + b.createModule(.{ .root_source_file = b.path("src/vector/root.zig"), .target = target, .optimize = optimize, .imports = vector_imports }), + b.createModule(.{ .root_source_file = b.path("src/glsl.zig"), .target = target, .optimize = optimize }), + b.createModule(.{ .root_source_file = b.path("src/abi.zig"), .target = target, .optimize = optimize }), + b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "abi", .module = abi }} }), + b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c } } }), + }) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); + + // A sketch reloaded mid-run with a changed layout: state carried over by + // field name, through the real dlopen path and the headless host. + const v1 = sb.app(.{ .name = "counter", .root_source_file = b.path("test/counter_v1.zig") }).addLibrary(); + const v2 = sb.app(.{ .name = "counter", .root_source_file = b.path("test/counter_v2.zig") }).addLibrary(); + // The README's example, so the documentation always compiles. + test_step.dependOn(&sb.app(.{ .name = "readme", .root_source_file = b.path("test/readme.zig") }).addLibrary().step); + + const reload = b.addRunArtifact(host_exe); + reload.addArgs(&.{ "--headless", "--fresh", "--script" }); + reload.addFileArg(b.path("test/reload.script")); + reload.addArg("--state"); + _ = reload.addOutputFileArg("counter.state"); + reload.addArg("--define"); + reload.addPrefixedArtifactArg("v2=", v2); + reload.addArtifactArg(v1); + reload.expectExitCode(0); + test_step.dependOn(&reload.step); +} + +fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *Build.Module { + const sdl_dep = b.dependency("sdl", .{ .target = target, .optimize = optimize }); + const sdl = sdl_dep.artifact("SDL3"); + if (target.result.os.tag == .linux) fixSdlThreadCleanup(b, sdl.root_module, sdl_dep.path("src")); + const translator: translate_c.Translator = .init(b.dependency("translate_c", .{}), .{ + .c_source_file = b.addWriteFiles().add("c.h", + \\#define SDL_DISABLE_OLD_NAMES + \\#include + \\#include + ), + .target = target, + .optimize = optimize, + }); + translator.linkLibrary(sdl); + translator.linkSystemLibrary("sndfile", .{}); + return translator.mod; +} + +/// SDL 3.4.14 gives its pthread TLS key no destructor, so threads SDL did not +/// create (PipeWire's) leave error storage behind when they exit. Compile the +/// original backend with an exit destructor; the pinned package is untouched. +fn fixSdlThreadCleanup(b: *Build, sdl: *Build.Module, source: Build.LazyPath) void { + var flags: ?[]const []const u8 = null; + for (sdl.link_objects.items) |object| { + if (object != .c_source_files) continue; + const group = object.c_source_files; + for (group.files, 0..) |file, i| { + if (!std.mem.eql(u8, file, "src/thread/pthread/SDL_systls.c")) continue; + const files = b.allocator.alloc([]const u8, group.files.len - 1) catch @panic("OOM"); + @memcpy(files[0..i], group.files[0..i]); + @memcpy(files[i..], group.files[i + 1 ..]); + group.files = files; + flags = group.flags; + break; + } + } + std.debug.assert(flags != null); + const patched = b.addWriteFiles().add("SDL_systls_cleanup.c", + \\#include + \\#include "SDL_internal.h" + \\#include "thread/SDL_systhread.h" + \\static void sketchbook_cleanup_tls(void *data) { + \\ /* pthread clears the key before calling us; SDL_CleanupTLS reads it. */ + \\ if (SDL_SYS_SetTLSData(data)) SDL_CleanupTLS(); + \\} + \\#define pthread_key_create(key, destructor) pthread_key_create(key, sketchbook_cleanup_tls) + \\#include "thread/pthread/SDL_systls.c" + ); + sdl.addIncludePath(source); + sdl.addCSourceFile(.{ .file = patched, .flags = flags.? }); +} + +// --------------------------------------------------------------------------- +// Build API for apps + +pub const Options = struct { + target: Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + /// This package's name in the app's build.zig.zon. + dependency: []const u8 = "sketchbook", +}; + +pub fn init(b: *Build, options: Options) Sketchbook { + const dep = b.dependency(options.dependency, .{ .target = options.target, .optimize = options.optimize }); + return .{ + .b = b, + .target = options.target, + .optimize = options.optimize, + .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .vector = dep.module("vector") }, + .host_exe = dep.artifact("sketchbook"), + .probe_exe = dep.artifact("sketchbook-probe"), + .web = dep.path("web"), + .glsl = dep.path("src/glsl.zig"), + }; +} + +pub const Sketchbook = struct { + b: *Build, + target: Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + /// `vector`: SVG, cubic geometry, and CPU and GPU renderers. + modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, vector: *Build.Module }, + /// The generic host: loads and hot-reloads a sketch library. + host_exe: *Build.Step.Compile, + /// Prints any sketch's state file. + probe_exe: *Build.Step.Compile, + /// `host.js` and the `index.html` template. + web: Build.LazyPath, + /// The GLSL declaration generator (see `addGlslLayouts`). + glsl: Build.LazyPath, + + pub const GlslLayouts = struct { + run: *Build.Step.Run, + /// `.glsl` for each type: pass it to `addGlslc` as an include. + dir: Build.LazyPath, + }; + + /// GLSL declarations generated from Zig types, so shaders and Zig share + /// one definition (see `glsl.zig`; std140 is checked as it runs). + /// `module` holds the types and must not depend on the shaders; + /// `types` are paths inside it, like "Vertex" or "gpu.Paint". + pub fn addGlslLayouts(sb: Sketchbook, options: struct { module: *Build.Module, types: []const []const u8 }) GlslLayouts { + const b = sb.b; + var paths: std.ArrayList(u8) = .empty; + for (options.types) |t| paths.print(b.allocator, "\"{s}\", ", .{t}) catch @panic("OOM"); + const tool = b.addExecutable(.{ + .name = "glsl-layouts", + .root_module = b.createModule(.{ + .root_source_file = b.addWriteFiles().add("glsl_layouts.zig", b.fmt( + \\const std = @import("std"); + \\pub fn main(init: std.process.Init) !void {{ + \\ var args = init.minimal.args.iterate(); + \\ _ = args.skip(); + \\ var dir = try std.Io.Dir.cwd().createDirPathOpen(init.io, args.next().?, .{{}}); + \\ defer dir.close(init.io); + \\ try @import("glsl").generate(@import("layouts"), &.{{ {s}}}, init.io, dir); + \\}} + , .{paths.items})), + .target = b.graph.host, + .imports = &.{ + .{ .name = "glsl", .module = b.createModule(.{ .root_source_file = sb.glsl }) }, + .{ .name = "layouts", .module = options.module }, + }, + }), + }); + const run = b.addRunArtifact(tool); + return .{ .run = run, .dir = run.addOutputDirectoryArg("glsl") }; + } + + pub const Glslc = struct { + run: *Build.Step.Run, + spirv: Build.LazyPath, + }; + + /// One GLSL file compiled to SPIR-V by `glslc` (from the Vulkan SDK or + /// shaderc, on PATH). + pub fn addGlslc(sb: Sketchbook, options: struct { + source: Build.LazyPath, + include_dirs: []const Build.LazyPath = &.{}, + target_env: []const u8 = "vulkan1.1", + optimize: bool = true, + }) Glslc { + const b = sb.b; + const run = b.addSystemCommand(&.{ "glslc", b.fmt("--target-env={s}", .{options.target_env}) }); + if (options.optimize) run.addArg("-O"); + for (options.include_dirs) |dir| run.addPrefixedDirectoryArg("-I", dir); + run.addArg("-o"); + const spirv = run.addOutputFileArg(b.fmt("{s}.spv", .{std.fs.path.basename(options.source.getDisplayName())})); + run.addFileArg(options.source); + return .{ .run = run, .spirv = spirv }; + } + + /// A module declaring each SPIR-V file as `pub const : []const u8`, + /// 4-byte aligned as Vulkan reads it. + pub fn addSpirvModule(sb: Sketchbook, shaders: []const struct { name: []const u8, spirv: Build.LazyPath }) *Build.Module { + const b = sb.b; + const files = b.addWriteFiles(); + var source: std.ArrayList(u8) = .empty; + for (shaders) |shader| { + const file = b.fmt("{s}.spv", .{shader.name}); + _ = files.addCopyFile(shader.spirv, file); + source.print(b.allocator, "const {s}_words align(4) = @embedFile(\"{s}\").*;\npub const {s}: []const u8 = &{s}_words;\n", .{ shader.name, file, shader.name, shader.name }) catch @panic("OOM"); + } + return b.createModule(.{ .root_source_file = files.add("spirv.zig", source.items) }); + } + + pub fn app(sb: Sketchbook, options: App.Options) App { + const imports = sb.b.allocator.alloc(Build.Module.Import, options.imports.len + 1) catch @panic("OOM"); + imports[0] = .{ .name = "sketch", .module = sb.modules.sketch }; + @memcpy(imports[1..], options.imports); + return .{ + .sb = sb, + .name = options.name, + .root_source_file = options.root_source_file, + .imports = imports, + // No target: every artifact compiles it for its own. + .module = sb.b.createModule(.{ .root_source_file = options.root_source_file, .imports = imports }), + }; + } +}; + +pub const App = struct { + sb: Sketchbook, + name: []const u8, + root_source_file: Build.LazyPath, + imports: []const Build.Module.Import, + /// The app's root, importing `sketch` and the app's own imports. + module: *Build.Module, + + pub const Options = struct { + name: []const u8, + root_source_file: Build.LazyPath, + /// Imports for the app's root module, besides `sketch`: for example + /// `sb.modules.vector`, or shaders from `addSpirvModule`. + imports: []const Build.Module.Import = &.{}, + }; + + /// A root module around the app: `source` sees `app`, `sketch` and `host`. + fn wrap(app: App, source: []const u8, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *Build.Module { + const b = app.sb.b; + const root = b.createModule(.{ + .root_source_file = b.addWriteFiles().add("root.zig", source), + .target = target, + .optimize = optimize, + .imports = &.{ .{ .name = "app", .module = app.module }, .{ .name = "sketch", .module = app.sb.modules.sketch } }, + }); + if (std.mem.indexOf(u8, source, "\"host\"") != null) root.addImport("host", app.sb.modules.host); + return root; + } + + /// The hot-reloadable sketch: a shared library the host watches. + pub fn addLibrary(app: App) *Build.Step.Compile { + return app.sb.b.addLibrary(.{ + .name = app.name, + .linkage = .dynamic, + .root_module = app.wrap("comptime { @import(\"sketch\").exportSketch(@import(\"app\")); }", app.sb.target, app.sb.optimize), + }); + } + + /// Host and sketch in one executable, nothing loaded at runtime: for + /// shipping, and for scripts that must not depend on a library path. + pub fn addExecutable(app: App) *Build.Step.Compile { + return app.sb.b.addExecutable(.{ + .name = app.name, + .root_module = app.wrap( + \\const std = @import("std"); + \\pub fn main(init: std.process.Init) !void { + \\ return @import("host").main(init, @import("sketch").sketch(@import("app"))); + \\} + , app.sb.target, app.sb.optimize), + }); + } + + pub const WebOptions = struct { + /// Directories copied next to the page, under their own `dest`. + assets: []const Asset = &.{}, + /// Replaces the generic page; `{title}` is substituted either way. + index_html: ?Build.LazyPath = null, + optimize: std.builtin.OptimizeMode = .ReleaseSafe, + + pub const Asset = struct { source: Build.LazyPath, dest: []const u8 }; + }; + + pub const Web = struct { + wasm: *Build.Step.Compile, + /// The page: `index.html`, `host.js`, `sketch.wasm` and assets. + dir: Build.LazyPath, + }; + + /// The browser build, as one directory ready to serve. + pub fn addWeb(app: App, options: WebOptions) Web { + const b = app.sb.b; + const wasm = b.addExecutable(.{ + .name = "sketch", + .root_module = app.wrap("comptime { @import(\"sketch\").web.exportWeb(@import(\"app\")); }", b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }), options.optimize), + }); + wasm.entry = .disabled; + wasm.rdynamic = true; + wasm.export_memory = true; + + const files = b.addWriteFiles(); + _ = files.addCopyFile(wasm.getEmittedBin(), "sketch.wasm"); + _ = files.addCopyFile(app.sb.web.path(b, "host.js"), "host.js"); + const page = b.addRunArtifact(b.addExecutable(.{ + .name = "sketchbook-page", + .root_module = b.createModule(.{ .root_source_file = b.addWriteFiles().add("page.zig", page_tool), .target = b.graph.host }), + })); + page.addFileArg(options.index_html orelse app.sb.web.path(b, "index.html")); + page.addArg(app.name); + _ = files.addCopyFile(page.addOutputFileArg("index.html"), "index.html"); + for (options.assets) |asset| _ = files.addCopyDirectory(asset.source, asset.dest, .{}); + return .{ .wasm = wasm, .dir = files.getDirectory() }; + } + + pub const RunOptions = struct { + /// State file, relative to the working directory. + state: ?[]const u8 = null, + /// Where relative asset paths resolve; the project root by default. + cwd: ?Build.LazyPath = null, + }; + + /// Runs the generic host on the installed library. Rebuilding the library + /// (`zig build lib --watch` in another terminal) reloads it in place. + pub fn addRun(app: App, library: *Build.Step.Compile, options: RunOptions) *Build.Step.Run { + const b = app.sb.b; + const install = b.addInstallArtifact(library, .{}); + const run = b.addRunArtifact(app.sb.host_exe); + run.step.dependOn(&install.step); + run.addArgs(&.{ "--state", options.state orelse b.fmt("{s}.state", .{app.name}) }); + run.addArg(b.getInstallPath(.lib, library.out_filename)); + run.setCwd(options.cwd orelse b.path(".")); + run.stdio = .inherit; + if (b.args) |args| run.addArgs(args); + return run; + } + + pub const ScriptOptions = struct { + /// `{name}` substitutions for the script. + defines: []const [2][]const u8 = &.{}, + cwd: ?Build.LazyPath = null, + }; + + /// Plays a script headless against `exe` (from `addExecutable`), with a + /// throwaway state file. Fails when an expectation does. + pub fn addScript(app: App, exe: *Build.Step.Compile, script: Build.LazyPath, options: ScriptOptions) *Build.Step.Run { + const b = app.sb.b; + const run = b.addRunArtifact(exe); + run.addArgs(&.{ "--headless", "--fresh", "--script" }); + run.addFileArg(script); + run.addArg("--state"); + _ = run.addOutputFileArg(b.fmt("{s}.state", .{app.name})); + for (options.defines) |pair| run.addArgs(&.{ "--define", b.fmt("{s}={s}", .{ pair[0], pair[1] }) }); + run.setCwd(options.cwd orelse b.path(".")); + run.expectExitCode(0); + run.has_side_effects = true; + return run; + } + + /// Prints the app's live state; `zig build probe -- --watch` follows it. + pub fn addProbe(app: App, state: ?[]const u8) *Build.Step.Run { + const b = app.sb.b; + const run = b.addRunArtifact(app.sb.probe_exe); + run.addArg(state orelse b.fmt("{s}.state", .{app.name})); + run.setCwd(b.path(".")); + run.stdio = .inherit; + if (b.args) |args| run.addArgs(args); + return run; + } + + /// Tests in `root_source_file` (the app's root by default), with the + /// app's imports and the app itself importable as `app`. + pub fn addTest(app: App, options: struct { root_source_file: ?Build.LazyPath = null }) *Build.Step.Compile { + const b = app.sb.b; + const module = b.createModule(.{ + .root_source_file = options.root_source_file orelse app.root_source_file, + .target = app.sb.target, + .optimize = app.sb.optimize, + .imports = app.imports, + }); + if (options.root_source_file != null) module.addImport("app", app.module); + return b.addTest(.{ .root_module = module }); + } + + pub const StepsOptions = struct { + web: ?WebOptions = null, + /// Scripts run by the `e2e` step. + scripts: []const Build.LazyPath = &.{}, + /// Extra test roots for the `test` step, besides the app's root. + tests: []const Build.LazyPath = &.{}, + }; + + pub const Steps = struct { + library: *Build.Step.Compile, + exe: *Build.Step.Compile, + run: *Build.Step.Run, + web: ?Web, + test_step: *Build.Step, + e2e: *Build.Step, + }; + + /// The conventional wiring. Installs the executable, and adds: + /// `run` (host + hot reload), `lib` (rebuild the library; use `--watch`), + /// `web`, `probe`, `e2e` (scripts) and `test`. + pub fn addSteps(app: App, options: StepsOptions) Steps { + const b = app.sb.b; + const library = app.addLibrary(); + const exe = app.addExecutable(); + b.installArtifact(exe); + + const run = app.addRun(library, .{}); + b.step("run", "Run with hot reload (rebuild with `zig build lib --watch`)").dependOn(&run.step); + b.step("lib", "Build and install the hot-reloadable library").dependOn(&b.addInstallArtifact(library, .{}).step); + b.step("probe", "Print the live state (-- --watch to follow)").dependOn(&app.addProbe(null).step); + + const web = if (options.web) |web_options| blk: { + const web = app.addWeb(web_options); + b.step("web", "Build the browser version into zig-out/web").dependOn(&b.addInstallDirectory(.{ .source_dir = web.dir, .install_dir = .prefix, .install_subdir = "web" }).step); + break :blk web; + } else null; + + const e2e = b.step("e2e", "Play the end-to-end scripts headless"); + for (options.scripts) |script| e2e.dependOn(&app.addScript(exe, script, .{}).step); + + const test_step = b.step("test", "Run unit tests and end-to-end scripts"); + test_step.dependOn(&b.addRunArtifact(app.addTest(.{})).step); + for (options.tests) |root| test_step.dependOn(&b.addRunArtifact(app.addTest(.{ .root_source_file = root })).step); + test_step.dependOn(e2e); + return .{ .library = library, .exe = exe, .run = run, .web = web, .test_step = test_step, .e2e = e2e }; + } +}; + +/// Fills `{title}` in the page template. +const page_tool = + \\const std = @import("std"); + \\pub fn main(init: std.process.Init) !void { + \\ var args = init.minimal.args.iterate(); + \\ _ = args.skip(); + \\ const template = args.next().?; + \\ const title = args.next().?; + \\ const out = args.next().?; + \\ const cwd = std.Io.Dir.cwd(); + \\ const arena = init.arena.allocator(); + \\ const source = try cwd.readFileAlloc(init.io, template, arena, .limited(1 << 20)); + \\ const page = try std.mem.replaceOwned(u8, arena, source, "{title}", title); + \\ try cwd.writeFile(init.io, .{ .sub_path = out, .data = page }); + \\} +; diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..7922d7f --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,17 @@ +.{ + .name = .sketchbook, + .version = "0.1.0", + .dependencies = .{ + .sdl = .{ + .url = "git+https://github.com/castholm/SDL.git#fb2d799c4778832a34ccb3739e40dded700684bd", + .hash = "sdl-0.5.3+3.4.14-SDL--v4eqAGuIKFsspMVxBxZf1OIEmmH-yHDdEl9ZRdX", + }, + .translate_c = .{ + .url = "git+https://codeberg.org/ziglang/translate-c?ref=zig-0.16.x#6fe0ffc4549f15c5f2d9432c2b4460ba90ff85ac", + .hash = "translate_c-1.0.0-Q_BUWo_5BgD4flHdUhA31zOz0XvZk9k7lQv1ouzyNXj2", + }, + }, + .minimum_zig_version = "0.16.0", + .paths = .{ "build.zig", "build.zig.zon", "src", "web" }, + .fingerprint = 0x6d6d2e26aa60b45e, +} diff --git a/src/abi.zig b/src/abi.zig new file mode 100644 index 0000000..3e23c47 --- /dev/null +++ b/src/abi.zig @@ -0,0 +1,524 @@ +//! Types shared by a host and the sketches it loads. +//! +//! Host and sketch are built by the same `zig build`, with the same compiler +//! and standard library, so ordinary Zig types cross the boundary: slices, +//! tagged unions, `std.mem.Allocator`. Two rules keep reloads safe: +//! - whatever outlives a call lives in host memory (host code is never +//! unloaded, so host allocators and function pointers stay valid); +//! - `hash` covers the layout of every type here, and a host refuses a sketch +//! built against different definitions instead of misreading its memory. +//! +//! Only `Event` and the reflected `Layout` are `extern`: they are written to disk. +const std = @import("std"); +pub const layout = @import("layout.zig"); +pub const Key = @import("keys.zig").Key; + +pub const Rect = extern struct { + x: f32 = 0, + y: f32 = 0, + w: f32 = 0, + h: f32 = 0, + + pub fn contains(r: Rect, x: f32, y: f32) bool { + return x >= r.x and y >= r.y and x < r.x + r.w and y < r.y + r.h; + } + pub fn inset(r: Rect, d: f32) Rect { + return .{ .x = r.x + d, .y = r.y + d, .w = r.w - 2 * d, .h = r.h - 2 * d }; + } +}; + +pub const Color = extern struct { + r: u8, + g: u8, + b: u8, + a: u8 = 0xff, + + pub const white: Color = .{ .r = 255, .g = 255, .b = 255 }; + pub const black: Color = .{ .r = 0, .g = 0, .b = 0 }; + + pub fn hex(rgb: u24) Color { + return .{ .r = @truncate(rgb >> 16), .g = @truncate(rgb >> 8), .b = @truncate(rgb) }; + } + pub fn alpha(c: Color, a: u8) Color { + return .{ .r = c.r, .g = c.g, .b = c.b, .a = a }; + } +}; + +/// One input event. Recordings are arrays of these on disk, so the layout is +/// frozen: 24 bytes, no padding, no pointers. +pub const Event = extern struct { + /// Nanoseconds. Live: host clock. Replay: time since the recording began. + time: u64 = 0, + /// Canvas coordinates for pointer events; `tick` stores dt seconds in `x`. + x: f32 = 0, + y: f32 = 0, + kind: Kind, + flags: u8 = 0, + /// Mouse button (1 left, 2 middle, 3 right) or USB HID scancode. + code: u16 = 0, + /// Unicode codepoint for `text`, key modifiers, or `@bitCast` wheel delta. + value: u32 = 0, + + pub const Kind = enum(u8) { + /// Once per frame, after that frame's other events. + tick, + mouse_move, + mouse_down, + mouse_up, + wheel, + key_down, + key_up, + text, + /// Focus loss, or the console took the pointer: drop armed gestures. + cancel, + _, + }; + /// `flags` bit for a held key's auto-repeat. + pub const repeat: u8 = 1; + + pub fn wheel(e: Event) f32 { + return @bitCast(e.value); + } + + comptime { + std.debug.assert(@sizeOf(Event) == 24); + } +}; + +pub const Mode = enum { live, recording, playing, paused }; + +/// A host audio stream, as last observed by the host. +pub const Stream = struct { + key: u32, + /// Samples waiting to be played. + queued: u32 = 0, + /// Samples pushed since the stream was last cleared. + pushed: u64 = 0, +}; + +/// Everything a sketch learns about the world for one call. +pub const Input = struct { + now: u64 = 0, + /// Nanoseconds since the previous frame. + dt: u64 = 0, + frame: u64 = 0, + events: []const Event = &.{}, + mode: Mode = .live, + /// First frame after new code, or a new layout, was loaded. + reloaded: bool = false, + /// The console is open and owns the keyboard. + console: bool = false, + width: f32 = 0, + height: f32 = 0, + mouse_x: f32 = 0, + mouse_y: f32 = 0, + /// Held mouse buttons, bit `button - 1`. + buttons: u32 = 0, + /// Held keys by USB HID scancode, maintained from the events fed so far. + keys: std.StaticBitSet(256) = .initEmpty(), + streams: []const Stream = &.{}, + sample_rate: u32 = 48_000, + + /// `key` is any enum whose values are HID scancodes, like `sketch.Key`. + pub fn held(in: *const Input, key: anytype) bool { + return in.keys.isSet(@intFromEnum(key)); + } + /// Went down this frame; auto-repeats excluded. + pub fn pressed(in: *const Input, key: anytype) bool { + for (in.events) |e| { + if (e.kind == .key_down and e.code == @intFromEnum(key) and e.flags & Event.repeat == 0) return true; + } + return false; + } + pub fn stream(in: *const Input, key: u32) Stream { + for (in.streams) |s| if (s.key == key) return s; + return .{ .key = key }; + } + /// Follows mouse, button and key state through one fed event. + pub fn track(in: *Input, e: Event) void { + switch (e.kind) { + .mouse_move, .wheel => { + in.mouse_x = e.x; + in.mouse_y = e.y; + }, + .mouse_down, .mouse_up => { + in.mouse_x = e.x; + in.mouse_y = e.y; + const bit = @as(u32, 1) << @intCast(@min(e.code -| 1, 31)); + if (e.kind == .mouse_down) in.buttons |= bit else in.buttons &= ~bit; + }, + .key_down => in.keys.set(@min(e.code, 255)), + .key_up => in.keys.unset(@min(e.code, 255)), + .cancel => { + in.buttons = 0; + in.keys = .initEmpty(); + }, + else => {}, + } + } + pub fn seconds(in: *const Input) f64 { + return @as(f64, @floatFromInt(in.now)) / std.time.ns_per_s; + } +}; + +pub const Image = enum(u32) { none = 0, _ }; +pub const Audio = enum(u32) { none = 0, _ }; +pub const Cursor = enum { hidden, arrow, pointer }; + +/// Voices are reconciled, not triggered: `draw` declares every voice that +/// should sound this frame, keyed by a number of its choosing. A new key, or +/// a new serial for a key, starts the sound from its beginning; an undeclared +/// key stops. A finished one-shot stays silent while its key and serial are +/// still declared, so replaying or scrubbing state never re-fires sounds. +pub const Voice = struct { + key: u32, + audio: Audio, + serial: u32 = 0, + loop: bool = false, + volume: f32 = 1, + /// Linear fade at both ends, in samples. + fade: u32 = 0, +}; + +/// Slices must stay alive until the host consumes the frame, right after +/// `draw` returns: literals, the frame arena and session memory all qualify. +pub const Command = union(enum) { + clear: Color, + rect: struct { dst: Rect, color: Color }, + /// `src` empty: the whole image. `tint` multiplies it. + image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white }, + /// Fixed 8px cells, `scale` times larger. + text: struct { x: f32, y: f32, scale: f32, color: Color, bytes: []const u8 }, + clip: ?Rect, + /// Logical canvas size; the host scales the window to fit. + canvas: struct { w: u32, h: u32 }, + cursor: Cursor, + voice: Voice, + /// Mono samples at `Input.sample_rate` for stream `key`. + audio: struct { key: u32, samples: []const f32, clear: bool = false }, + /// RGBA8 rows of `w * 4` bytes into an image made by `Host.newImage`. + pixels: struct { image: Image, w: u32, h: u32, rgba: []const u8, premultiplied: bool = false }, + /// Renders a GPU pass into an image made by `Host.newImage`, when + /// `Host.gpu` says the host can. + gpu: gpu.Pass, + quit, +}; + +/// GPU work described as data. A sketch declares its pipelines and draws; +/// the host builds the real objects, caches them by the hash of their +/// description (so an edited shader simply becomes a new pipeline after a +/// reload), and runs the pass. Sketches never touch a graphics API. +/// +/// Shaders are SPIR-V. Resources follow SDL_GPU's SPIR-V convention: +/// vertex uniforms in set 1, fragment uniforms in set 3, binding = slot. +/// Uniform bytes must follow std140. +pub const gpu = struct { + pub const Shader = struct { + spirv: []const u8, + uniform_buffers: u32 = 0, + }; + + pub const Format = enum { float, float2, float3, float4, ubyte4_norm }; + pub const Attribute = struct { location: u32, format: Format, offset: u32 }; + + pub const Blend = enum { + /// Overwrite. + none, + /// Source over, premultiplied colors. + premultiplied, + additive, + }; + + pub const Compare = enum { never, less, equal, less_or_equal, greater, not_equal, greater_or_equal, always }; + pub const StencilOp = enum { keep, zero, replace, increment_and_clamp, decrement_and_clamp, invert, increment_and_wrap, decrement_and_wrap }; + pub const StencilFace = struct { + compare: Compare = .always, + pass: StencilOp = .keep, + fail: StencilOp = .keep, + }; + + pub const Pipeline = struct { + vertex: Shader, + fragment: Shader, + /// Bytes per vertex. + stride: u32, + attributes: []const Attribute, + primitive: enum { triangle_list, triangle_strip, line_list, line_strip } = .triangle_list, + blend: Blend = .premultiplied, + write_color: bool = true, + /// Stencil test and update, per triangle facing. Needs a pass with + /// a stencil buffer. + stencil: ?struct { front: StencilFace, back: StencilFace } = null, + }; + + pub const Draw = struct { + /// Index into `Pass.pipelines`. + pipeline: u32, + vertices: []const u8, + vertex_count: u32, + stencil_reference: u8 = 0, + /// Uniform slot 0 of each stage. + vertex_uniforms: []const u8 = &.{}, + fragment_uniforms: []const u8 = &.{}, + scissor: ?Rect = null, + }; + + // Layouts from types: Zig knows every offset at comptime, so vertex + // formats and uniform layouts come from plain structs, never by hand. + + /// Vertex attributes for `V`: one per field, locations in field order, + /// formats from the field types (`f32`, `[2..4]f32` or vectors, `[4]u8` + /// normalized). + pub fn attributes(comptime V: type) []const Attribute { + return comptime blk: { + if (@typeInfo(V).@"struct".layout != .@"extern") @compileError(@typeName(V) ++ " must be extern to be a vertex"); + const fields = @typeInfo(V).@"struct".fields; + var out: [fields.len]Attribute = undefined; + for (fields, 0..) |f, i| out[i] = .{ .location = i, .offset = @offsetOf(V, f.name), .format = formatOf(f.type) }; + const frozen = out; + break :blk &frozen; + }; + } + + fn formatOf(comptime T: type) Format { + if (T == f32) return .float; + if (T == [4]u8 or T == @Vector(4, u8)) return .ubyte4_norm; + const len, const child = switch (@typeInfo(T)) { + .array => |a| .{ a.len, a.child }, + .vector => |v| .{ v.len, v.child }, + else => @compileError("no vertex format for " ++ @typeName(T)), + }; + if (child != f32) @compileError("no vertex format for " ++ @typeName(T)); + return switch (len) { + 2 => .float2, + 3 => .float3, + 4 => .float4, + else => @compileError("no vertex format for " ++ @typeName(T)), + }; + } + + /// A pipeline drawing vertices of type `V`: stride and attributes filled in. + pub fn pipeline(comptime V: type, p: struct { + vertex: Shader, + fragment: Shader, + primitive: @FieldType(Pipeline, "primitive") = .triangle_list, + blend: Blend = .premultiplied, + write_color: bool = true, + stencil: @FieldType(Pipeline, "stencil") = null, + }) Pipeline { + return .{ + .vertex = p.vertex, + .fragment = p.fragment, + .stride = @sizeOf(V), + .attributes = attributes(V), + .primitive = p.primitive, + .blend = p.blend, + .write_color = p.write_color, + .stencil = p.stencil, + }; + } + + /// Fails to compile unless `U` lays out as the std140 uniform block + /// GLSL would declare for it (see `glsl.zig`). + pub const assertStd140 = @import("glsl.zig").assertStd140; + + /// `value`'s bytes, checked against std140, copied into `arena` so they + /// outlive the caller until the frame is consumed. + pub fn uniform(arena: std.mem.Allocator, value: anytype) []const u8 { + comptime assertStd140(@TypeOf(value)); + const copy = arena.create(@TypeOf(value)) catch return &.{}; + copy.* = value; + return std.mem.asBytes(copy); + } + + pub const Pass = struct { + /// The target; its size is the image's. + image: Image, + width: u32, + height: u32, + /// 1, 2, 4 or 8. More than one renders multisampled and resolves. + samples: u8 = 1, + stencil: bool = false, + /// Premultiplied; null keeps the image's previous contents. + clear: ?[4]f32 = .{ 0, 0, 0, 0 }, + pipelines: []const Pipeline, + draws: []const Draw, + }; +}; + +/// Host services. Handles and loaded data outlive reloads. +pub const Host = struct { + ctx: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + log: *const fn (*anyopaque, []const u8) void, + /// Cached by path. A missing file still gets a handle: it draws as a + /// placeholder, and starts working when the file appears. + loadImage: *const fn (*anyopaque, []const u8) Image, + /// PNG bytes in memory. Not cached. + decodeImage: *const fn (*anyopaque, []const u8) Image, + /// A blank image for `Command.pixels`. + newImage: *const fn (*anyopaque, u32, u32) Image, + /// Releases an image; its handle draws nothing afterwards. + freeImage: *const fn (*anyopaque, Image) void, + /// Whether `Command.gpu` runs here: the host has a GPU device. + gpu: *const fn (*anyopaque) bool, + /// Zero while unknown. + imageSize: *const fn (*anyopaque, Image) [2]u32, + loadSound: *const fn (*anyopaque, []const u8) Audio, + /// WAV bytes in memory. Not cached. + decodeSound: *const fn (*anyopaque, []const u8) Audio, + /// The whole file, mapped for the life of the host; empty if missing. + readFile: *const fn (*anyopaque, []const u8) []const u8, + env: *const fn (*anyopaque, []const u8) ?[]const u8, + /// A monotonic clock in nanoseconds, for measuring, not for state: + /// `update` must use `Input` time to stay replayable. + clock: *const fn (*anyopaque) u64, + }; + + pub fn log(h: Host, message: []const u8) void { + h.vtable.log(h.ctx, message); + } + pub fn print(h: Host, comptime fmt: []const u8, args: anytype) void { + var buf: [512]u8 = undefined; + h.log(std.fmt.bufPrint(&buf, fmt, args) catch "(message too long)"); + } + pub fn loadImage(h: Host, path: []const u8) Image { + return h.vtable.loadImage(h.ctx, path); + } + pub fn decodeImage(h: Host, png: []const u8) Image { + return h.vtable.decodeImage(h.ctx, png); + } + pub fn newImage(h: Host, w: u32, height: u32) Image { + return h.vtable.newImage(h.ctx, w, height); + } + pub fn freeImage(h: Host, image: Image) void { + h.vtable.freeImage(h.ctx, image); + } + pub fn gpu(h: Host) bool { + return h.vtable.gpu(h.ctx); + } + pub fn imageSize(h: Host, image: Image) [2]u32 { + return h.vtable.imageSize(h.ctx, image); + } + pub fn loadSound(h: Host, path: []const u8) Audio { + return h.vtable.loadSound(h.ctx, path); + } + pub fn decodeSound(h: Host, wav: []const u8) Audio { + return h.vtable.decodeSound(h.ctx, wav); + } + pub fn readFile(h: Host, path: []const u8) []const u8 { + return h.vtable.readFile(h.ctx, path); + } + pub fn env(h: Host, name: []const u8) ?[]const u8 { + return h.vtable.env(h.ctx, name); + } + pub fn clock(h: Host) u64 { + return h.vtable.clock(h.ctx); + } +}; + +/// What the host passes to every call. +pub const Context = struct { + host: Host, + input: *const Input, + /// Frame lifetime: reset after the host consumes the frame. + arena: std.mem.Allocator, + /// Session lifetime: survives reloads, released when the session resets. + gpa: std.mem.Allocator, + /// Filled by `draw`, using `arena`. + commands: *std.ArrayList(Command), +}; + +/// One leaf of a reflected layout. Nested structs are flattened into dotted +/// paths; arrays stay whole. Hosts migrate state across layout changes, and +/// inspect or edit it by name, from these. Stored in the state file header. +pub const Field = extern struct { + path: [*:0]const u8, + offset: u32, + size: u32, + kind: Kind, + reserved: [3]u8 = @splat(0), + /// Structural hash of the field's type: equal hashes copy byte for byte. + hash: u64, + /// Enums: "name=value" pairs separated by commas. Empty otherwise. + tags: [*:0]const u8 = "", + + pub const Kind = enum(u8) { int, uint, float, bool, @"enum", array, bytes, _ }; +}; + +pub const Layout = struct { + size: usize = 0, + alignment: usize = 1, + hash: u64 = 0, + fields: []const Field = &.{}, +}; + +/// Returned by `sketch_info`. The host copies what it keeps, since a +/// sketch's read-only data disappears with the library. +pub const Info = struct { + /// The sketch's `abi.hash`: a host refuses one that differs from its own. + abi: u64, + name: []const u8, + width: u32, + height: u32, + state: Layout, + session: Layout, + /// Console completions offered by the sketch. + commands: []const []const u8 = &.{}, +}; + +/// Which memory `sketch_defaults` fills. +pub const Memory = enum(u8) { state, session }; + +/// The entry points of a sketch, exported from libraries under these names. +pub const Sketch = struct { + info: *const fn () callconv(.c) *const Info, + /// Declared default values, and nothing else. + defaults: *const fn (Memory, [*]u8) callconv(.c) void, + /// Setup for brand new state, after its defaults. + init: *const fn (*const Context, [*]u8) callconv(.c) void, + /// Deterministic: new state from state and input, nothing else. + update: *const fn (*const Context, [*]u8) callconv(.c) void, + /// Presentation: reads state, may change session, appends commands. + draw: *const fn (*const Context, [*]const u8, [*]u8) callconv(.c) void, + /// A console line the host did not understand; true when handled. + command: *const fn (*const Context, [*]u8, [*]u8, *const []const u8) callconv(.c) bool, + + pub const symbols = .{ + .info = "sketch_info", + .defaults = "sketch_defaults", + .init = "sketch_init", + .update = "sketch_update", + .draw = "sketch_draw", + .command = "sketch_command", + }; +}; + +/// Layout hash of everything above. Changes whenever a shared type does. +pub const hash: u64 = blk: { + @setEvalBranchQuota(1_000_000); + var h: u64 = 0; + for (.{ Rect, Color, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { + h = std.hash.Wyhash.hash(h, @typeName(T) ++ layout.signature(T)); + } + break :blk h; +}; + +test "vertex attributes and std140 checks come from the types" { + const Vertex = extern struct { position: [2]f32, color: [4]u8, uv: [2]f32 }; + const attrs = gpu.attributes(Vertex); + try std.testing.expectEqual(@as(usize, 3), attrs.len); + try std.testing.expectEqual(gpu.Format.ubyte4_norm, attrs[1].format); + try std.testing.expectEqual(@as(u32, 12), attrs[2].offset); + const Block = extern struct { color: [4]f32, size: [2]f32, pad: [2]f32, stops: [4][4]f32 }; + comptime gpu.assertStd140(Block); + const p = gpu.pipeline(Vertex, .{ .vertex = .{ .spirv = "" }, .fragment = .{ .spirv = "" } }); + try std.testing.expectEqual(@as(u32, 20), p.stride); +} + +test { + _ = layout; + _ = @import("keys.zig"); +} diff --git a/src/glsl.zig b/src/glsl.zig new file mode 100644 index 0000000..995985b --- /dev/null +++ b/src/glsl.zig @@ -0,0 +1,158 @@ +//! GLSL declarations from Zig structs, so shaders and the code that feeds +//! them share one definition: the Zig one. `Sketchbook.addGlslLayouts` builds a +//! small generator around this file for the types it is given; each type +//! says how it appears in GLSL with a `glsl` tag: +//! +//! pub const Viewport = extern struct { +//! size: [2]f32, +//! pad: [2]f32 = .{ 0, 0 }, +//! pub const glsl = .{ .uniform = .{ .set = 1, .instance = "viewport" } }; +//! }; +//! +//! becomes `Viewport.glsl`: +//! +//! layout(set = 1, binding = 0, std140) uniform Viewport { +//! vec2 size; +//! vec2 pad; +//! } viewport; +//! +//! Tags: `.vertex` (one `layout(location = N) in` per field, in the order +//! `abi.gpu.attributes` uses), `.{ .uniform = .{ .set, .binding = 0, +//! .instance } }` (SDL_GPU's SPIR-V sets: 1 vertex, 3 fragment), `.plain` +//! (a `struct`, for nesting). +const std = @import("std"); + +/// `T`'s declaration, as GLSL source. +pub fn source(comptime T: type, comptime name: []const u8) []const u8 { + comptime { + @setEvalBranchQuota(100_000); + const tag = T.glsl; + const fields = @typeInfo(T).@"struct".fields; + var out: []const u8 = "// Generated from the Zig struct " ++ @typeName(T) ++ "; do not edit.\n"; + if (@TypeOf(tag) == @TypeOf(.enum_literal) and tag == .vertex) { + for (fields, 0..) |f, i| out = out ++ std.fmt.comptimePrint("layout(location = {d}) in {s} {s};\n", .{ i, typeName(f.type, .vertex), f.name }); + } else if (@TypeOf(tag) == @TypeOf(.enum_literal) and tag == .plain) { + out = out ++ "struct " ++ name ++ " {\n" ++ members(T) ++ "};\n"; + } else if (@hasField(@TypeOf(tag), "uniform")) { + const u = tag.uniform; + assertStd140(T); + const binding = if (@hasField(@TypeOf(u), "binding")) u.binding else 0; + out = out ++ std.fmt.comptimePrint("layout(set = {d}, binding = {d}, std140) uniform {s} {{\n", .{ u.set, binding, name }) ++ members(T) ++ "} " ++ u.instance ++ ";\n"; + } else @compileError(@typeName(T) ++ ".glsl must be .vertex, .plain or .{ .uniform = ... }"); + return out; + } +} + +fn members(comptime T: type) []const u8 { + comptime { + var out: []const u8 = ""; + for (@typeInfo(T).@"struct".fields) |f| { + const array_of_composites = switch (@typeInfo(f.type)) { + .array => |a| @typeInfo(a.child) == .array or @typeInfo(a.child) == .@"struct", + else => false, + }; + out = out ++ if (array_of_composites) + std.fmt.comptimePrint(" {s} {s}[{d}];\n", .{ typeName(@typeInfo(f.type).array.child, .uniform), f.name, @typeInfo(f.type).array.len }) + else + std.fmt.comptimePrint(" {s} {s};\n", .{ typeName(f.type, .uniform), f.name }); + } + return out; + } +} + +fn typeName(comptime T: type, comptime use: enum { vertex, uniform }) []const u8 { + if (T == f32) return "float"; + if (T == u32) return "uint"; + if (T == i32) return "int"; + if (use == .vertex and (T == [4]u8 or T == @Vector(4, u8))) return "vec4"; + return switch (@typeInfo(T)) { + .array => |a| vector(a.len, a.child), + .vector => |v| vector(v.len, v.child), + .@"struct" => @typeName(T)[if (std.mem.lastIndexOfScalar(u8, @typeName(T), '.')) |dot| dot + 1 else 0..], + else => @compileError("no GLSL type for " ++ @typeName(T)), + }; +} + +fn vector(comptime len: usize, comptime child: type) []const u8 { + const prefix = if (child == f32) "" else if (child == u32) "u" else if (child == i32) "i" else @compileError("no GLSL vector of " ++ @typeName(child)); + return std.fmt.comptimePrint("{s}vec{d}", .{ prefix, len }); +} + +/// The type at `path` (dot-separated declarations) inside `root`. +pub fn resolve(comptime root: type, comptime path: []const u8) type { + comptime { + var t = root; + var it = std.mem.tokenizeScalar(u8, path, '.'); + while (it.next()) |name| t = @field(t, name); + return t; + } +} + +/// Writes `.glsl` for each type path into `dir`. +pub fn generate(comptime root: type, comptime paths: []const []const u8, io: std.Io, dir: std.Io.Dir) !void { + inline for (paths) |path| { + const T = resolve(root, path); + const name = comptime path[if (std.mem.lastIndexOfScalar(u8, path, '.')) |dot| dot + 1 else 0..]; + try dir.writeFile(io, .{ .sub_path = name ++ ".glsl", .data = comptime source(T, name) }); + } +} + +/// Fails to compile unless `U` lays out exactly as a std140 uniform block +/// with the same members in GLSL: scalars at 4 bytes, `vec2` at 8, +/// `vec3`/`vec4` at 16, arrays and nested structs at 16 with 16-byte strides. +pub fn assertStd140(comptime U: type) void { + comptime { + if (@typeInfo(U).@"struct".layout != .@"extern") @compileError(@typeName(U) ++ " must be extern to be a uniform block"); + for (@typeInfo(U).@"struct".fields) |f| { + const want = std140Align(f.type); + if (@offsetOf(U, f.name) % want != 0) @compileError(std.fmt.comptimePrint("{s}.{s} sits at {d}; std140 wants a multiple of {d}", .{ @typeName(U), f.name, @offsetOf(U, f.name), want })); + } + if (@sizeOf(U) % 16 != 0) @compileError(@typeName(U) ++ " must be a multiple of 16 bytes"); + } +} + +fn std140Align(comptime T: type) usize { + return switch (@typeInfo(T)) { + .float, .int => 4, + .bool => @compileError("GLSL bools are 4 bytes: use u32"), + .vector => |v| if (v.len == 2) 8 else 16, + .array => |a| blk: { + if (@typeInfo(a.child) == .float or @typeInfo(a.child) == .int) { + // `[2]f32` stands for a vec2, `[3]`/`[4]f32` for vec3/vec4. + if (a.len == 2) break :blk 8; + if (a.len == 3 or a.len == 4) break :blk 16; + @compileError("std140 arrays of scalars have a 16-byte stride: use [N][4]f32"); + } + if (@sizeOf(a.child) % 16 != 0) @compileError("std140 array elements are 16-byte strided"); + break :blk 16; + }, + .@"struct" => blk: { + assertStd140(T); + break :blk 16; + }, + else => @compileError("no std140 layout for " ++ @typeName(T)), + }; +} + +test "uniform blocks and vertex inputs from structs" { + const Root = struct { + pub const Paint = extern struct { + color: [4]f32, + size: [2]f32, + pad: [2]f32, + stops: [4][4]f32, + pub const glsl = .{ .uniform = .{ .set = 3, .instance = "paint" } }; + }; + pub const Vertex = extern struct { + position: [2]f32, + tint: [4]u8, + pub const glsl = .vertex; + }; + }; + const paint = comptime source(resolve(Root, "Paint"), "Paint"); + try std.testing.expect(std.mem.indexOf(u8, paint, "layout(set = 3, binding = 0, std140) uniform Paint {") != null); + try std.testing.expect(std.mem.indexOf(u8, paint, " vec4 stops[4];") != null); + try std.testing.expect(std.mem.indexOf(u8, paint, "} paint;") != null); + const vertex = comptime source(Root.Vertex, "Vertex"); + try std.testing.expect(std.mem.indexOf(u8, vertex, "layout(location = 1) in vec4 tint;") != null); +} diff --git a/src/host/Console.zig b/src/host/Console.zig new file mode 100644 index 0000000..d9aa469 --- /dev/null +++ b/src/host/Console.zig @@ -0,0 +1,260 @@ +//! The developer console: a line editor, a short log, and the host commands +//! (snapshots, recordings, replay, field inspection). Lines the host does not +//! know go to the sketch's `command`. +const Console = @This(); +const std = @import("std"); +const abi = @import("abi"); +const Host = @import("Host.zig"); +const fields = @import("fields.zig"); +const memory = @import("memory.zig"); +const timeline = @import("timeline.zig"); + +pub const panel_height = 144; +pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, submit }; +const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 }; + +const host_commands = [_][]const u8{ + "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", + "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit", +}; + +visible: bool = false, +buffer: [96]u8 = @splat(0), +len: usize = 0, +cursor: usize = 0, +lines: [5]Line = @splat(.{}), +snapshot: usize = 1, +recording: usize = 0, +overlay_memory: bool = false, +overlay_sound: bool = false, + +pub fn text(self: *const Console) []const u8 { + return self.buffer[0..self.len]; +} + +pub fn insert(self: *Console, typed: []const u8) void { + for (typed) |byte| { + // Commands and the built-in font only need printable ASCII. + if (byte < 32 or byte > 126 or byte == '`' or self.len == self.buffer.len) continue; + std.mem.copyBackwards(u8, self.buffer[self.cursor + 1 .. self.len + 1], self.buffer[self.cursor..self.len]); + self.buffer[self.cursor] = byte; + self.cursor += 1; + self.len += 1; + } +} + +/// Edits the line; `submit` returns it (valid until the next edit). +pub fn edit(self: *Console, key: Key, extra: []const []const u8) ?[]const u8 { + switch (key) { + .left => self.cursor -|= 1, + .right => self.cursor = @min(self.len, self.cursor + 1), + .home => self.cursor = 0, + .end => self.cursor = self.len, + .clear => { + self.len = 0; + self.cursor = 0; + }, + .backspace => if (self.cursor > 0) { + self.cursor -= 1; + self.erase(); + }, + .delete => self.erase(), + .tab => self.complete(extra), + .submit => { + const line = self.text(); + // The bytes stay put until the next edit; only the length resets. + self.len = 0; + self.cursor = 0; + if (std.mem.trim(u8, line, " ").len == 0) return null; + self.print("> {s}", .{line}); + return line; + }, + } + return null; +} + +fn erase(self: *Console) void { + if (self.cursor == self.len) return; + std.mem.copyForwards(u8, self.buffer[self.cursor .. self.len - 1], self.buffer[self.cursor + 1 .. self.len]); + self.len -= 1; +} + +fn complete(self: *Console, extra: []const []const u8) void { + var first: ?[]const u8 = null; + var common: usize = 0; + var matches: [256]u8 = undefined; + var used: usize = 0; + var count: usize = 0; + for ([_][]const []const u8{ &host_commands, extra }) |list| for (list) |candidate| { + if (!std.mem.startsWith(u8, candidate, self.text())) continue; + if (first) |previous| { + var i: usize = 0; + while (i < common and i < candidate.len and previous[i] == candidate[i]) : (i += 1) {} + common = i; + } else { + first = candidate; + common = candidate.len; + } + const match = std.fmt.bufPrint(matches[used..], "{s} ", .{candidate}) catch continue; + used += match.len; + count += 1; + }; + if (first) |candidate| { + self.cursor = self.len; + self.insert(candidate[self.len..common]); + if (count > 1) self.log(matches[0..used]); + } else self.log("No completion. Type help for commands."); +} + +pub fn log(self: *Console, message: []const u8) void { + var rest = message; + while (true) { + std.mem.copyForwards(Line, self.lines[0..4], self.lines[1..5]); + const line = &self.lines[4]; + line.len = @min(rest.len, line.bytes.len); + @memcpy(line.bytes[0..line.len], rest[0..line.len]); + rest = rest[line.len..]; + if (rest.len == 0) break; + } +} + +pub fn print(self: *Console, comptime fmt: []const u8, args: anytype) void { + var buf: [512]u8 = undefined; + self.log(std.fmt.bufPrint(&buf, fmt, args) catch "(message too long)"); +} + +/// Runs one line. Host commands first; anything else goes to the sketch. +/// Returns events to replay after a seek, already restored to the snapshot. +pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const abi.Event { + const h = &host.timeline; + var words = std.mem.tokenizeAny(u8, line, " \t"); + const command = words.next() orelse return &.{}; + const arg = words.next(); + 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("diff [N] | reset | get | set | overlay memory|sound | quit"); + if (!host.forward(self, line, now)) self.log("Backtick hides the console. Tab completes."); + return &.{}; + } + if (eq(command, "overlay")) { + const name = arg orelse return error.ExpectedOverlay; + const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else return error.UnknownOverlay; + flag.* = !flag.*; + 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 {}; + self.print("{s} = {s}", .{ path, w.buffered() }); + } else if (eq(command, "set")) { + const path = arg orelse return error.ExpectedField; + const leaf = host.state.layout.find(path) orelse return error.UnknownField; + if (rest.len == 0) return error.ExpectedValue; + h.stop(now); + try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " ")); + self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") }); + } else if (eq(command, "quit") or eq(command, "exit")) { + h.stop(now); + host.quit = true; + } else if (eq(command, "reset")) { + h.stop(now); + host.resetState(); + self.log("Live state reset. Snapshots are kept."); + } else if (eq(command, "snapshot")) { + self.snapshot = try slot(arg orelse return error.ExpectedSlot, 1, memory.slot_count - 1); + } else if (eq(command, "recording")) { + self.recording = try slot(arg orelse return error.ExpectedSlot, 0, timeline.recording_count - 1); + } else if (eq(command, "save") or eq(command, "load")) { + const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; + if (eq(command, "load") and !h.bank.hasSnapshot(index)) return error.EmptySnapshot; + h.stop(now); + if (eq(command, "save")) { + h.bank.save(index); + self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index}); + } else { + try h.bank.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); + self.recording = index; + self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot }); + } else if (eq(command, "stop")) { + h.stop(now); + } else if (eq(command, "pause")) { + if (h.mode != .playing and h.mode != .paused) return error.NotReplaying; + h.pause(now); + } else if (eq(command, "step") or eq(command, "seek")) { + const value = arg orelse return error.ExpectedPosition; + _ = try h.bank.get(if (h.mode == .live or h.mode == .recording) self.recording else h.selected); + 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 (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); + const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition; + return h.seekTime(ms *| std.time.ns_per_ms); + } else if (eq(command, "diff")) { + 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 }); + } else { + // Sketch commands edit state outside the recorded input. + h.stop(now); + if (!host.forward(self, line, now)) return error.UnknownCommand; + } + return &.{}; +} + +pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), arena: std.mem.Allocator) !void { + const ink: abi.Color = .{ .r = 230, .g = 255, .b = 230 }; + const hint: abi.Color = .{ .r = 145, .g = 220, .b = 150 }; + const top = @as(f32, @floatFromInt(host.canvas[1])) - panel_height; + const width: f32 = @floatFromInt(host.canvas[0]); + const h = &host.timeline; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } }); + const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {d} | recording {d} (active {d}) | event {d} | {d}ms", .{ + host.name, h.mode, self.snapshot, self.recording, h.selected, h.cursor, h.position / std.time.ns_per_ms, + }); + try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } }); + for (&self.lines, 0..) |*line, i| { + try out.append(arena, .{ .text = .{ .x = 12, .y = top + 28 + @as(f32, @floatFromInt(i)) * 18, .scale = 1, .color = ink, .bytes = line.bytes[0..line.len] } }); + } + try out.append(arena, .{ .text = .{ .x = 12, .y = top + 122, .scale = 1, .color = ink, .bytes = try std.fmt.allocPrint(arena, "> {s}", .{self.text()}) } }); + try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } }); +} + +fn eq(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +fn slot(value: []const u8, min: usize, max: usize) !usize { + const index = std.fmt.parseInt(usize, value, 10) catch return error.InvalidSlot; + if (index < min or index > max) return error.InvalidSlot; + return index; +} + +test "line editing, completion and submission" { + var c: Console = .{}; + c.insert("scen"); + _ = c.edit(.tab, &.{ "scene room", "scene gallery" }); + try std.testing.expectEqualStrings("scene ", c.text()); + c.insert("`room"); + try std.testing.expectEqualStrings("scene room", c.text()); + _ = c.edit(.home, &.{}); + _ = c.edit(.delete, &.{}); + try std.testing.expectEqualStrings("cene room", c.text()); + const line = c.edit(.submit, &.{}).?; + try std.testing.expectEqualStrings("cene room", line); + try std.testing.expectEqualStrings("", c.text()); + try std.testing.expect(c.edit(.submit, &.{}) == null); +} diff --git a/src/host/Host.zig b/src/host/Host.zig new file mode 100644 index 0000000..41597a6 --- /dev/null +++ b/src/host/Host.zig @@ -0,0 +1,545 @@ +//! The runtime around a sketch: window, memory, audio, timeline and console. +//! One `frame` serves both the interactive loop and test scripts, so scripts +//! exercise exactly what a player does. +const Host = @This(); +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 gfx = @import("gfx.zig"); +const sound = @import("audio.zig"); +const Gpu = @import("gpu.zig"); +const overlay = @import("overlay.zig"); +const Console = @import("Console.zig"); +const Library = @import("library.zig").Library; +const Watch = @import("library.zig").Watch; + +pub const Options = struct { + /// A hot-reloaded sketch library. Unused when a sketch is linked in. + library: ?[]const u8 = null, + /// State file; recordings go next to it with an `.inputs` suffix. + state: []const u8 = "sketch.state", + /// Offscreen video, silent audio, no vsync: for scripts and CI. + headless: bool = false, + /// Forget the state file's contents: scripts start from a known place. + fresh: bool = false, +}; + +gpa: std.mem.Allocator, +io: std.Io, +environ: *const std.process.Environ.Map, +options: Options, +window: *c.SDL_Window, +renderer: *c.SDL_Renderer, +/// Runs sketches' GPU passes, and the 2D renderer draws through it too. +/// Null when the machine has no usable GPU driver. +gpu: ?*c.SDL_GPUDevice, +passes: ?Gpu = null, +pointer_cursor: ?*c.SDL_Cursor = null, +images: gfx.Images, +audio: sound.Audio, +state: memory.StateFile, +session: memory.Session, +recordings: []align(memory.page) u8, +timeline: Timeline, +console: Console = .{}, +sketch: abi.Sketch, +library: ?Library = null, +watch: ?Watch = null, +reloads: usize = 0, +/// Copies of the sketch's info strings, replaced on every load. +info_arena: std.heap.ArenaAllocator, +name: []const u8 = "", +completions: []const []const u8 = &.{}, +/// Frame lifetime: sketch scratch and this frame's commands. +frame_arena: std.heap.ArenaAllocator, +commands: std.ArrayList(abi.Command) = .empty, +/// Events routed since the last frame, fed to `update` by the next one. +pending: std.ArrayList(abi.Event) = .empty, +input: abi.Input = .{}, +files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty, +canvas: [2]u32 = .{ 0, 0 }, +cursor: abi.Cursor = .arrow, +quit: bool = false, +reloaded: bool = true, +last_now: u64 = 0, +/// Saved after the next frame is drawn (scripts). +screenshot: ?[:0]const u8 = null, + +pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void { + if (options.headless) { + _ = c.SDL_SetHint(c.SDL_HINT_VIDEO_DRIVER, "offscreen"); + _ = c.SDL_SetHint(c.SDL_HINT_AUDIO_DRIVER, "dummy"); + _ = c.SDL_SetHint(c.SDL_HINT_RENDER_DRIVER, "software"); + } + if (!c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_EVENTS | c.SDL_INIT_AUDIO)) return sdlError("SDL_Init"); + errdefer c.SDL_Quit(); + + var library: ?Library = null; + const sketch = linked orelse blk: { + const path = options.library orelse return error.NoSketch; + library = try Library.openCopy(io, path, scratchDir(environ), 0); + break :blk library.?.sketch; + }; + errdefer if (library) |*l| l.close(); + const info = sketch.info(); + + var title_buf: [256]u8 = undefined; + const title = std.fmt.bufPrintZ(&title_buf, "{s}", .{info.name}) catch "sketch"; + const window = c.SDL_CreateWindow(title.ptr, @intCast(info.width), @intCast(info.height), c.SDL_WINDOW_RESIZABLE) orelse return sdlError("SDL_CreateWindow"); + errdefer c.SDL_DestroyWindow(window); + // The 2D renderer runs on the GPU device that also runs sketches' GPU + // passes; without one, SDL picks whatever renderer works. + var gpu = c.SDL_CreateGPUDevice(c.SDL_GPU_SHADERFORMAT_SPIRV, false, null); + var renderer: ?*c.SDL_Renderer = if (gpu) |device| c.SDL_CreateGPURenderer(device, window) else null; + if (renderer == null) { + if (gpu) |device| c.SDL_DestroyGPUDevice(device); + gpu = null; + 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); + errdefer if (gpu) |device| c.SDL_DestroyGPUDevice(device); + if (!options.headless) _ = c.SDL_SetRenderVSync(renderer, 1); + + var state = try memory.StateFile.open(gpa, options.state); + errdefer state.close(); + var inputs_buf: [std.fs.max_path_bytes]u8 = undefined; + const recordings = try mapRecordings(try std.fmt.bufPrint(&inputs_buf, "{s}.inputs", .{options.state})); + errdefer std.posix.munmap(recordings); + + self.* = .{ + .gpa = gpa, + .io = io, + .environ = environ, + .options = options, + .window = window, + .renderer = renderer.?, + .gpu = gpu, + .images = .{ .gpa = gpa, .renderer = renderer.? }, + .audio = .{ .gpa = gpa }, + .state = state, + .session = .init(gpa), + .recordings = recordings, + .timeline = undefined, + .sketch = sketch, + .library = library, + .info_arena = .init(gpa), + .frame_arena = .init(gpa), + }; + self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } }; + if (gpu) |device| self.passes = .init(gpa, device); + self.audio.open() catch |err| std.log.warn("audio unavailable: {t}", .{err}); + if (options.library) |path| if (linked == null) { + self.watch = Watch.init(path) catch null; + }; + self.setCanvas(info.width, info.height); + _ = c.SDL_StartTextInput(self.window); + try self.adopt(sketch); + if (options.fresh) { + self.state.header().used = 0; + @memset(self.recordings, 0); + self.resetState(); + } +} + +pub fn deinit(self: *Host) void { + if (self.watch) |w| w.deinit(); + self.audio.deinit(); + if (self.passes) |*g| g.deinit(&self.images); + self.images.deinit(); + if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); + c.SDL_DestroyRenderer(self.renderer); + if (self.gpu) |device| c.SDL_DestroyGPUDevice(device); + c.SDL_DestroyWindow(self.window); + var files = self.files.iterator(); + while (files.next()) |entry| { + self.gpa.free(entry.key_ptr.*); + std.posix.munmap(entry.value_ptr.*); + } + self.files.deinit(self.gpa); + std.posix.munmap(self.recordings); + self.session.deinit(self.gpa); + self.state.close(); + self.pending.deinit(self.gpa); + self.frame_arena.deinit(); + self.info_arena.deinit(); + if (self.library) |*l| l.close(); + c.SDL_Quit(); +} + +/// The interactive loop. +pub fn run(self: *Host) !void { + while (!self.quit) { + try self.poll(); + try self.frame(c.SDL_GetTicksNS()); + } + self.timeline.stop(c.SDL_GetTicksNS()); +} + +pub fn live(self: *Host) []u8 { + return self.state.slot(0); +} + +/// One frame: reload if a build replaced the library, feed input through +/// `update`, then `draw` and present. +pub fn frame(self: *Host, now: u64) !void { + _ = self.frame_arena.reset(.retain_capacity); + self.commands = .empty; + if (self.watch) |w| if (w.changed()) self.reload() catch |err| self.print("reload failed: {t}", .{err}); + + const dt = if (self.last_now == 0) 0 else now -| self.last_now; + self.last_now = now; + const h = &self.timeline; + switch (h.mode) { + .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; + self.update(self.pending.items); + }, + } + self.pending.clearRetainingCapacity(); + try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position); +} + +/// Feeds events to the sketch's deterministic `update`. +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; + const ctx = self.context(); + self.sketch.update(&ctx, self.live().ptr); + self.input.events = &.{}; +} + +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.reloaded = false; + self.input.console = self.console.visible; + self.input.width = @floatFromInt(self.canvas[0]); + self.input.height = @floatFromInt(self.canvas[1]); + self.input.streams = self.audio.streamStatus(); + self.input.sample_rate = sound.sample_rate; + self.input.frame += 1; + const ctx = self.context(); + self.sketch.draw(&ctx, self.live().ptr, self.session.bytes.ptr); + + _ = c.SDL_SetRenderClipRect(self.renderer, null); + _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 255); + _ = c.SDL_RenderClear(self.renderer); + self.audio.beginFrame(); + for (self.commands.items) |command| switch (command) { + .canvas => |size| self.setCanvas(size.w, size.h), + .cursor => |kind| self.cursor = kind, + .voice => |voice| self.audio.declare(voice), + .audio => |a| self.audio.push(a.key, a.samples, a.clear), + .quit => self.quit = true, + .gpu => |pass| if (self.passes) |*g| g.run(&self.images, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), + else => gfx.draw(self.renderer, &self.images, command), + }; + self.audio.endFrame(); + _ = 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); + if (self.console.overlay_sound) { + const samples = self.audio.scope.snapshot(); + 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); + self.applyCursor(); + + if (self.screenshot) |path| { + self.screenshot = null; + const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels"); + defer c.SDL_DestroySurface(surface); + if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG"); + } + _ = c.SDL_RenderPresent(self.renderer); + if (self.passes) |*g| g.endFrame(); +} + +fn context(self: *Host) abi.Context { + return .{ + .host = .{ .ctx = self, .vtable = &api }, + .input = &self.input, + .arena = self.frame_arena.allocator(), + .gpa = self.session.heap.allocator(), + .commands = &self.commands, + }; +} + +/// Sends one event to the console or towards the sketch. Backtick toggles the +/// console; while it is open it owns the keyboard, and pointer events over it +/// become a cancel, so a half-made click never lands behind it. +pub fn route(self: *Host, e: abi.Event) !void { + if (e.kind == .key_down and e.code == @intFromEnum(abi.Key.grave)) { + if (e.flags & abi.Event.repeat != 0) return; + self.console.visible = !self.console.visible; + return self.pending.append(self.gpa, .{ .kind = .cancel, .time = e.time }); + } + if (self.console.visible) switch (e.kind) { + .text => { + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(@intCast(@min(e.value, 0x10ffff)), &buf) catch return; + self.console.insert(buf[0..len]); + return; + }, + .key_down => { + const key = consoleKey(e) orelse return; + if (self.console.edit(key, self.completions)) |line| self.runLine(line, e.time); + return; + }, + .key_up => return, + .mouse_move, .mouse_down, .mouse_up, .wheel => if (e.y >= @as(f32, @floatFromInt(self.canvas[1])) - Console.panel_height) { + return self.pending.append(self.gpa, .{ .kind = .cancel, .time = e.time }); + }, + else => {}, + }; + try self.pending.append(self.gpa, e); +} + +/// Runs a console line now, replaying whatever a seek asks for. +pub fn runLine(self: *Host, line: []const u8, now: u64) void { + const replay = self.console.execute(self, line, now) catch |err| { + self.console.print("{t}. Type help for usage.", .{err}); + return; + }; + if (self.timeline.mode == .paused) self.update(replay); +} + +/// Offers a line to the sketch; false if it did not take it. +pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) bool { + self.input.now = now; + const ctx = self.context(); + return self.sketch.command(&ctx, self.live().ptr, self.session.bytes.ptr, &line); +} + +/// Fresh state: declared defaults, then the sketch's `init`. +pub fn resetState(self: *Host) void { + const bytes = self.live(); + @memset(bytes, 0); + self.sketch.defaults(.state, bytes.ptr); + const ctx = self.context(); + self.sketch.init(&ctx, bytes.ptr); + self.state.markUsed(0, true); +} + +/// Loads the watched library again. +pub fn reload(self: *Host) !void { + try self.load(self.options.library orelse return error.NoLibrary); +} + +/// Replaces the running sketch with the library at `path`, keeping state. +pub fn load(self: *Host, path: []const u8) !void { + var library = try Library.openCopy(self.io, path, scratchDir(self.environ), self.reloads + 1); + errdefer library.close(); + try self.adopt(library.sketch); + if (self.library) |*old| old.close(); + self.library = library; + self.reloads += 1; + self.print("reload {d}: {s}", .{ self.reloads, path }); +} + +fn adopt(self: *Host, sketch: abi.Sketch) !void { + const info = sketch.info(); + if (info.abi != abi.hash) return error.AbiMismatch; + const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults); + const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults); + _ = self.info_arena.reset(.retain_capacity); + const arena = self.info_arena.allocator(); + self.name = try arena.dupe(u8, info.name); + const completions = try arena.alloc([]const u8, info.commands.len); + for (completions, info.commands) |*to, from| to.* = try arena.dupe(u8, from); + self.completions = completions; + self.sketch = sketch; + self.reloaded = true; + switch (adoption) { + .unchanged => {}, + .created => {}, + .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }), + } + if (!self.state.used(0)) self.resetState(); + if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{}); +} + +fn setCanvas(self: *Host, w: u32, h: u32) void { + if (w == 0 or h == 0 or (self.canvas[0] == w and self.canvas[1] == h)) return; + self.canvas = .{ w, h }; + _ = c.SDL_SetRenderLogicalPresentation(self.renderer, @intCast(w), @intCast(h), c.SDL_LOGICAL_PRESENTATION_LETTERBOX); + _ = c.SDL_SetWindowSize(self.window, @intCast(w), @intCast(h)); +} + +fn applyCursor(self: *Host) void { + const kind: abi.Cursor = if (self.console.visible) .arrow else self.cursor; + switch (kind) { + .hidden => _ = c.SDL_HideCursor(), + .arrow => { + _ = c.SDL_SetCursor(c.SDL_GetDefaultCursor()); + _ = c.SDL_ShowCursor(); + }, + .pointer => { + if (self.pointer_cursor == null) self.pointer_cursor = c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_POINTER); + _ = c.SDL_SetCursor(self.pointer_cursor orelse c.SDL_GetDefaultCursor()); + _ = c.SDL_ShowCursor(); + }, + } +} + +pub fn print(self: *Host, comptime fmt: []const u8, args: anytype) void { + var buf: [512]u8 = undefined; + const message = std.fmt.bufPrint(&buf, fmt, args) catch "(message too long)"; + self.console.log(message); + // Headless runs are tests: they report through their own results. + if (!self.options.headless) std.debug.print("{s}\n", .{message}); +} + +/// Translates SDL events into sketch events and routes them. +pub fn poll(self: *Host) !void { + var event: c.SDL_Event = undefined; + while (c.SDL_PollEvent(&event)) { + _ = c.SDL_ConvertEventToRenderCoordinates(self.renderer, &event); + const time = event.common.timestamp; + switch (event.type) { + c.SDL_EVENT_QUIT => self.quit = true, + c.SDL_EVENT_WINDOW_FOCUS_LOST => try self.route(.{ .kind = .cancel, .time = time }), + c.SDL_EVENT_MOUSE_MOTION => try self.route(.{ .kind = .mouse_move, .time = time, .x = event.motion.x, .y = event.motion.y }), + c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP => try self.route(.{ + .kind = if (event.type == c.SDL_EVENT_MOUSE_BUTTON_DOWN) .mouse_down else .mouse_up, + .time = time, + .x = event.button.x, + .y = event.button.y, + .code = event.button.button, + }), + c.SDL_EVENT_MOUSE_WHEEL => { + const delta = event.wheel.y * @as(f32, if (event.wheel.direction == c.SDL_MOUSEWHEEL_FLIPPED) -1 else 1); + if (!std.math.isFinite(delta) or delta == 0) continue; + try self.route(.{ .kind = .wheel, .time = time, .x = event.wheel.mouse_x, .y = event.wheel.mouse_y, .value = @bitCast(delta) }); + }, + c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_KEY_UP => try self.route(.{ + .kind = if (event.type == c.SDL_EVENT_KEY_DOWN) .key_down else .key_up, + .time = time, + .code = @intCast(event.key.scancode), + .flags = if (event.key.repeat) abi.Event.repeat else 0, + .value = modifiers(event.key.mod), + }), + c.SDL_EVENT_TEXT_INPUT => { + var it = (std.unicode.Utf8View.init(std.mem.span(event.text.text)) catch continue).iterator(); + while (it.nextCodepoint()) |cp| try self.route(.{ .kind = .text, .time = time, .value = cp }); + }, + else => {}, + } + } +} + +fn modifiers(mod: c.SDL_Keymod) u32 { + var m: u32 = 0; + if (mod & c.SDL_KMOD_SHIFT != 0) m |= abi.Key.Mod.shift; + if (mod & c.SDL_KMOD_CTRL != 0) m |= abi.Key.Mod.ctrl; + if (mod & c.SDL_KMOD_ALT != 0) m |= abi.Key.Mod.alt; + if (mod & c.SDL_KMOD_GUI != 0) m |= abi.Key.Mod.gui; + return m; +} + +fn consoleKey(e: abi.Event) ?Console.Key { + const key: abi.Key = @enumFromInt(@as(u8, @truncate(e.code))); + if (key == .u and e.value & abi.Key.Mod.ctrl != 0) return .clear; + if (e.flags & abi.Event.repeat != 0 and key.isEnter()) return null; + if (key.isEnter()) return .submit; + return switch (key) { + .left => .left, + .right => .right, + .home => .home, + .end => .end, + .backspace => .backspace, + .delete => .delete, + .escape => .clear, + .tab => .tab, + else => null, + }; +} + +fn scratchDir(environ: *const std.process.Environ.Map) []const u8 { + return environ.get("XDG_RUNTIME_DIR") orelse "/tmp"; +} + +fn sdlError(what: []const u8) error{Sdl} { + std.log.err("{s}: {s}", .{ what, c.SDL_GetError() }); + return error.Sdl; +} + +// Host services, as seen by sketches. +const api: abi.Host.VTable = .{ + .log = apiLog, + .loadImage = apiLoadImage, + .decodeImage = apiDecodeImage, + .newImage = apiNewImage, + .freeImage = apiFreeImage, + .gpu = apiGpu, + .imageSize = apiImageSize, + .loadSound = apiLoadSound, + .decodeSound = apiDecodeSound, + .readFile = apiReadFile, + .env = apiEnv, + .clock = apiClock, +}; + +fn hostOf(ctx: *anyopaque) *Host { + return @ptrCast(@alignCast(ctx)); +} +fn apiLog(ctx: *anyopaque, message: []const u8) void { + hostOf(ctx).print("{s}", .{message}); +} +fn apiLoadImage(ctx: *anyopaque, path: []const u8) abi.Image { + return hostOf(ctx).images.load(path); +} +fn apiDecodeImage(ctx: *anyopaque, png: []const u8) abi.Image { + return hostOf(ctx).images.decode(png); +} +fn apiNewImage(ctx: *anyopaque, w: u32, h: u32) abi.Image { + return hostOf(ctx).images.new(w, h); +} +fn apiFreeImage(ctx: *anyopaque, image: abi.Image) void { + const self = hostOf(ctx); + if (self.passes) |*g| g.forget(&self.images, image); + self.images.free(image); +} +fn apiGpu(ctx: *anyopaque) bool { + return hostOf(ctx).gpu != null; +} +fn apiImageSize(ctx: *anyopaque, image: abi.Image) [2]u32 { + return hostOf(ctx).images.size(image); +} +fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio { + return hostOf(ctx).audio.load(path); +} +fn apiDecodeSound(ctx: *anyopaque, wav: []const u8) abi.Audio { + return hostOf(ctx).audio.decode(wav); +} +fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 { + const self = hostOf(ctx); + if (self.files.get(path)) |bytes| return bytes; + const bytes = memory.mapReadOnly(path); + if (bytes.len == 0) return &.{}; + const key = self.gpa.dupe(u8, path) catch return bytes; + self.files.put(self.gpa, key, bytes) catch self.gpa.free(key); + return bytes; +} +fn apiClock(_: *anyopaque) u64 { + return c.SDL_GetTicksNS(); +} +fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 { + return hostOf(ctx).environ.get(name); +} diff --git a/src/host/audio.zig b/src/host/audio.zig new file mode 100644 index 0000000..fc8dcfb --- /dev/null +++ b/src/host/audio.zig @@ -0,0 +1,284 @@ +//! Sound output: decoded clips played by reconciled voices, plus raw streams +//! the sketch fills itself. The audio thread only ever sees SDL's own copies +//! of the samples; sketch code and memory never run on it. +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); + +pub const sample_rate = 48_000; +const spec: c.SDL_AudioSpec = .{ .format = c.SDL_AUDIO_F32, .channels = 1, .freq = sample_rate }; +/// A device block plus the next frame; 512 samples can underrun at 60 Hz. +const queue_samples = 2048; + +pub const Audio = struct { + gpa: std.mem.Allocator, + device: c.SDL_AudioDeviceID = 0, + /// Mixed voices. + voices_out: ?*c.SDL_AudioStream = null, + clips: std.ArrayList([]f32) = .empty, + paths: std.StringHashMapUnmanaged(abi.Audio) = .empty, + voices: std.ArrayList(Playing) = .empty, + streams: std.ArrayList(Stream) = .empty, + status: std.ArrayList(abi.Stream) = .empty, + scope: Scope = .{}, + + const Playing = struct { voice: abi.Voice, cursor: usize = 0, done: bool = false, seen: bool = true }; + const Stream = struct { key: u32, out: *c.SDL_AudioStream, pushed: u64 = 0 }; + + pub fn open(self: *Audio) !void { + const device = c.SDL_OpenAudioDevice(c.SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec); + if (device == 0) return error.OpenAudio; + self.device = device; + self.voices_out = try self.bind(); + self.scope.attach(device) catch {}; + } + + pub fn deinit(self: *Audio) void { + self.scope.deinit(); + for (self.streams.items) |s| c.SDL_DestroyAudioStream(s.out); + if (self.voices_out) |s| c.SDL_DestroyAudioStream(s); + if (self.device != 0) c.SDL_CloseAudioDevice(self.device); + for (self.clips.items) |samples| self.gpa.free(samples); + var keys = self.paths.keyIterator(); + while (keys.next()) |key| self.gpa.free(key.*); + self.paths.deinit(self.gpa); + self.clips.deinit(self.gpa); + self.voices.deinit(self.gpa); + self.streams.deinit(self.gpa); + self.status.deinit(self.gpa); + } + + fn bind(self: *Audio) !*c.SDL_AudioStream { + const out = c.SDL_CreateAudioStream(&spec, &spec) orelse return error.OpenAudio; + errdefer c.SDL_DestroyAudioStream(out); + if (!c.SDL_BindAudioStream(self.device, out)) return error.OpenAudio; + return out; + } + + pub fn load(self: *Audio, path: []const u8) abi.Audio { + if (self.paths.get(path)) |audio| return audio; + const audio = self.add(decodeFile(self.gpa, path) catch |err| blk: { + std.log.warn("sound {s}: {t}", .{ path, err }); + break :blk &.{}; + }); + const key = self.gpa.dupe(u8, path) catch return audio; + self.paths.put(self.gpa, key, audio) catch self.gpa.free(key); + return audio; + } + + pub fn decode(self: *Audio, wav: []const u8) abi.Audio { + return self.add(decodeWav(self.gpa, wav) catch &.{}); + } + + fn add(self: *Audio, samples: []f32) abi.Audio { + self.clips.append(self.gpa, samples) catch { + self.gpa.free(samples); + return .none; + }; + return @enumFromInt(self.clips.items.len); + } + + fn samplesOf(self: *Audio, audio: abi.Audio) []const f32 { + const index = @intFromEnum(audio); + if (index == 0 or index > self.clips.items.len) return &.{}; + return self.clips.items[index - 1]; + } + + pub fn beginFrame(self: *Audio) void { + for (self.voices.items) |*v| v.seen = false; + } + + /// Reconciles one declared voice with what is playing. + pub fn declare(self: *Audio, voice: abi.Voice) void { + for (self.voices.items) |*playing| { + if (playing.voice.key != voice.key) continue; + const restart = playing.voice.serial != voice.serial or playing.voice.audio != voice.audio; + playing.voice = voice; + playing.seen = true; + if (restart) { + playing.cursor = 0; + playing.done = false; + } + return; + } + self.voices.append(self.gpa, .{ .voice = voice }) catch {}; + } + + pub fn push(self: *Audio, key: u32, samples: []const f32, clear: bool) void { + const s = self.streamFor(key) orelse return; + if (clear) { + _ = c.SDL_ClearAudioStream(s.out); + s.pushed = 0; + } + if (samples.len == 0) return; + if (c.SDL_PutAudioStreamData(s.out, samples.ptr, @intCast(samples.len * @sizeOf(f32)))) s.pushed += samples.len; + } + + fn streamFor(self: *Audio, key: u32) ?*Stream { + for (self.streams.items) |*s| if (s.key == key) return s; + if (self.device == 0) return null; + const out = self.bind() catch return null; + self.streams.append(self.gpa, .{ .key = key, .out = out }) catch { + c.SDL_DestroyAudioStream(out); + return null; + }; + return &self.streams.items[self.streams.items.len - 1]; + } + + /// Drops undeclared voices and keeps the voice mix queued ahead. + pub fn endFrame(self: *Audio) void { + var i: usize = 0; + while (i < self.voices.items.len) { + if (self.voices.items[i].seen) i += 1 else _ = self.voices.swapRemove(i); + } + const out = self.voices_out orelse return; + const queued = c.SDL_GetAudioStreamQueued(out); + if (queued < 0) return; + const needed = queue_samples -| @as(usize, @intCast(queued)) / @sizeOf(f32); + var buffer: [queue_samples]f32 = undefined; + const count = self.mix(buffer[0..needed]); + if (count != 0) _ = c.SDL_PutAudioStreamData(out, &buffer, @intCast(count * @sizeOf(f32))); + } + + /// Mixes live voices into `output`; returns how many samples were written, + /// stopping early once every voice has finished. + pub fn mix(self: *Audio, output: []f32) usize { + var count: usize = 0; + for (output) |*sample| { + var sum: f32 = 0; + var alive = false; + for (self.voices.items) |*playing| { + if (playing.done) continue; + const samples = self.samplesOf(playing.voice.audio); + if (playing.cursor >= samples.len) { + playing.done = true; + continue; + } + alive = true; + const v = playing.voice; + const edge = @min(playing.cursor + 1, samples.len - playing.cursor); + const fade: f32 = if (v.fade == 0) 1 else @as(f32, @floatFromInt(@min(edge, v.fade))) / @as(f32, @floatFromInt(v.fade)); + sum += samples[playing.cursor] * v.volume * fade; + playing.cursor += 1; + if (playing.cursor == samples.len and v.loop) playing.cursor = 0; + } + if (!alive) break; + // Bounded however many voices sound at once. + sample.* = sum / (1 + @abs(sum)); + count += 1; + } + return count; + } + + pub fn streamStatus(self: *Audio) []const abi.Stream { + self.status.clearRetainingCapacity(); + for (self.streams.items) |s| { + const queued = c.SDL_GetAudioStreamQueued(s.out); + self.status.append(self.gpa, .{ .key = s.key, .queued = @intCast(@divFloor(@max(queued, 0), @sizeOf(f32))), .pushed = s.pushed }) catch {}; + } + return self.status.items; + } +}; + +fn decodeWav(gpa: std.mem.Allocator, wav: []const u8) ![]f32 { + const io = c.SDL_IOFromConstMem(wav.ptr, wav.len) orelse return error.OpenWav; + var from: c.SDL_AudioSpec = undefined; + var data: [*c]u8 = null; + var len: u32 = 0; + if (!c.SDL_LoadWAV_IO(io, true, &from, &data, &len)) return error.DecodeWav; + defer c.SDL_free(data); + return convert(gpa, &from, data[0..len]); +} + +fn decodeFile(gpa: std.mem.Allocator, path: []const u8) ![]f32 { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const z = try std.fmt.bufPrintZ(&buf, "{s}", .{path}); + var info: c.SF_INFO = std.mem.zeroes(c.SF_INFO); + const file = c.sf_open(z.ptr, c.SFM_READ, &info) orelse return error.OpenSoundFile; + defer _ = c.sf_close(file); + if (info.samplerate <= 0 or info.samplerate > 192000 or info.channels <= 0 or info.channels > 8 or info.frames <= 0 or info.frames > @as(i64, info.samplerate) * 600) return error.UnsupportedSoundFormat; + const raw = try gpa.alloc(f32, @intCast(info.frames * info.channels)); + defer gpa.free(raw); + if (c.sf_readf_float(file, raw.ptr, info.frames) != info.frames) return error.TruncatedAudio; + const from: c.SDL_AudioSpec = .{ .format = c.SDL_AUDIO_F32, .channels = info.channels, .freq = info.samplerate }; + return convert(gpa, &from, std.mem.sliceAsBytes(raw)); +} + +/// To host format: f32 mono at `sample_rate`, all finite. +fn convert(gpa: std.mem.Allocator, from: *const c.SDL_AudioSpec, data: []const u8) ![]f32 { + if (data.len == 0 or data.len > std.math.maxInt(c_int)) return error.InvalidAudioLength; + var out: [*c]u8 = null; + var out_len: c_int = 0; + if (!c.SDL_ConvertAudioSamples(from, data.ptr, @intCast(data.len), &spec, &out, &out_len)) return error.ConvertAudio; + defer c.SDL_free(out); + if (out_len <= 0 or @mod(out_len, 4) != 0) return error.InvalidAudioLength; + const samples = @as([*]const f32, @ptrCast(@alignCast(out)))[0..@intCast(@divExact(out_len, 4))]; + for (samples) |v| if (!std.math.isFinite(v)) return error.InvalidAudioSample; + return gpa.dupe(f32, samples); +} + +/// A read-only tap of the device's final mix, for the sound overlay. +pub const Scope = struct { + mutex: ?*c.SDL_Mutex = null, + device: c.SDL_AudioDeviceID = 0, + ring: [512]f32 = @splat(0), + cursor: usize = 0, + rate: u32 = sample_rate, + + pub fn attach(self: *Scope, device: c.SDL_AudioDeviceID) !void { + self.mutex = c.SDL_CreateMutex() orelse return error.ScopeMutex; + if (!c.SDL_SetAudioPostmixCallback(device, callback, self)) return error.ScopeCallback; + self.device = device; + } + pub fn deinit(self: *Scope) void { + // SDL waits for a callback in flight before removing it. + if (self.device != 0) _ = c.SDL_SetAudioPostmixCallback(self.device, null, null); + if (self.mutex) |m| c.SDL_DestroyMutex(m); + self.* = .{}; + } + /// Oldest first. + pub fn snapshot(self: *Scope) [512]f32 { + var result: [512]f32 = @splat(0); + const m = self.mutex orelse return result; + c.SDL_LockMutex(m); + defer c.SDL_UnlockMutex(m); + for (&result, 0..) |*s, i| s.* = self.ring[(self.cursor + i) % self.ring.len]; + return result; + } + fn callback(userdata: ?*anyopaque, s: [*c]const c.SDL_AudioSpec, buffer: [*c]f32, bytes: c_int) callconv(.c) void { + const self: *Scope = @ptrCast(@alignCast(userdata orelse return)); + if (s == null or s.*.channels <= 0 or bytes <= 0) return; + const m = self.mutex orelse return; + // Dropping one picture beats blocking the audio thread. + if (!c.SDL_TryLockMutex(m)) return; + defer c.SDL_UnlockMutex(m); + const channels: usize = @intCast(s.*.channels); + const frames = @as(usize, @intCast(bytes)) / @sizeOf(f32) / channels; + self.rate = @intCast(s.*.freq); + for (0..frames) |i| { + self.ring[self.cursor] = buffer[i * channels]; + self.cursor = (self.cursor + 1) % self.ring.len; + } + } +}; + +test "voices reconcile: one-shots finish and stay silent, new serials restart, undeclared keys stop" { + var audio: Audio = .{ .gpa = std.testing.allocator }; + defer audio.deinit(); + const clip = audio.add(try std.testing.allocator.dupe(f32, &.{ 0.5, 0.5, 0.5 })); + var out: [8]f32 = undefined; + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = clip }); + try std.testing.expectEqual(@as(usize, 3), audio.mix(&out)); + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = clip }); + try std.testing.expectEqual(@as(usize, 0), audio.mix(&out)); + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = clip, .serial = 1 }); + try std.testing.expectEqual(@as(usize, 3), audio.mix(&out)); + audio.beginFrame(); + audio.declare(.{ .key = 2, .audio = clip, .loop = true }); + audio.endFrame(); + try std.testing.expectEqual(@as(usize, 1), audio.voices.items.len); + try std.testing.expectEqual(@as(usize, 8), audio.mix(&out)); +} diff --git a/src/host/fields.zig b/src/host/fields.zig new file mode 100644 index 0000000..215f176 --- /dev/null +++ b/src/host/fields.zig @@ -0,0 +1,116 @@ +//! Reading and writing state by field path, from the reflected layout alone. +//! 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; + +pub fn format(leaf: Leaf, memory: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void { + const bytes = leaf.bytes(memory); + switch (leaf.kind) { + .int => try w.print("{d}", .{readInt(i64, bytes)}), + .uint => try w.print("{d}", .{readInt(u64, bytes)}), + .bool => try w.writeAll(if (bytes[0] != 0) "true" else "false"), + .float => switch (leaf.size) { + 4 => try w.print("{d}", .{@as(f32, @bitCast(bytes[0..4].*))}), + 8 => try w.print("{d}", .{@as(f64, @bitCast(bytes[0..8].*))}), + else => try w.writeAll("?"), + }, + .@"enum" => { + const value = readInt(i64, bytes); + if (tagName(leaf.tags, value)) |name| try w.print(".{s}", .{name}) else try w.print("{d}", .{value}); + }, + else => try w.print("<{d} bytes>", .{leaf.size}), + } +} + +/// Parses `text` as the field's kind (enums by name or number) and stores it. +pub fn set(leaf: Leaf, memory: []u8, text: []const u8) !void { + const bytes = memory[leaf.offset..][0..leaf.size]; + switch (leaf.kind) { + .int, .uint, .@"enum" => { + const name = std.mem.trimStart(u8, text, "."); + const value: i64 = if (leaf.kind == .@"enum" and tagValue(leaf.tags, name) != null) + tagValue(leaf.tags, name).? + else + std.fmt.parseInt(i64, text, 0) catch return error.InvalidValue; + writeInt(bytes, value); + }, + .bool => bytes[0] = if (std.mem.eql(u8, text, "true") or std.mem.eql(u8, text, "1")) 1 else if (std.mem.eql(u8, text, "false") or std.mem.eql(u8, text, "0")) 0 else return error.InvalidValue, + .float => { + const value = std.fmt.parseFloat(f64, text) catch return error.InvalidValue; + switch (leaf.size) { + 4 => bytes[0..4].* = @bitCast(@as(f32, @floatCast(value))), + 8 => bytes[0..8].* = @bitCast(value), + else => return error.UnsupportedField, + } + }, + else => return error.UnsupportedField, + } +} + +/// True when the field's formatted value equals `text` (enum names compare +/// with or without the leading dot). +pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool { + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + format(leaf, memory, &w) catch return false; + const shown = w.buffered(); + if (std.mem.eql(u8, shown, text)) return true; + if (leaf.kind == .@"enum") { + if (std.mem.eql(u8, std.mem.trimStart(u8, shown, "."), std.mem.trimStart(u8, text, "."))) return true; + const value = std.fmt.parseInt(i64, text, 0) catch return false; + return value == readInt(i64, leaf.bytes(memory)); + } + return false; +} + +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); + if (T == u64) return value; + // Sign-extend from the field's own width. + const shift: u6 = @intCast(64 - n * 8); + return @as(i64, @bitCast(value << shift)) >> shift; +} + +pub fn writeInt(bytes: []u8, value: i64) void { + const raw: u64 = @bitCast(value); + for (bytes, 0..) |*b, i| b.* = if (i < 8) @truncate(raw >> @intCast(i * 8)) else 0; +} + +pub fn tagName(tags: []const u8, value: i64) ?[]const u8 { + var it = std.mem.tokenizeScalar(u8, tags, ','); + while (it.next()) |pair| { + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; + if ((std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch continue) == value) return pair[0..eq]; + } + return null; +} + +pub fn tagValue(tags: []const u8, name: []const u8) ?i64 { + var it = std.mem.tokenizeScalar(u8, tags, ','); + while (it.next()) |pair| { + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; + if (std.mem.eql(u8, pair[0..eq], name)) return std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch null; + } + return null; +} + +test "fields format, parse and compare by kind" { + const S = extern struct { mood: enum(u32) { calm, angry = 5 } = .calm, x: i16 = -3, speed: f32 = 1.5, on: bool = false }; + 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, .forbidden)); + var s: S = .{}; + const bytes = std.mem.asBytes(&s); + try std.testing.expect(matches(layout.find("x").?, bytes, "-3")); + try set(layout.find("mood").?, bytes, "angry"); + try std.testing.expectEqual(.angry, s.mood); + try std.testing.expect(matches(layout.find("mood").?, bytes, ".angry")); + try std.testing.expect(matches(layout.find("mood").?, bytes, "5")); + try set(layout.find("speed").?, bytes, "0.25"); + try std.testing.expectEqual(@as(f32, 0.25), s.speed); + try set(layout.find("on").?, bytes, "true"); + try std.testing.expect(s.on); + try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana")); +} diff --git a/src/host/gfx.zig b/src/host/gfx.zig new file mode 100644 index 0000000..e00d325 --- /dev/null +++ b/src/host/gfx.zig @@ -0,0 +1,177 @@ +//! Images and drawing. Textures have host lifetime; sketches hold handles. +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); + +pub const Images = struct { + gpa: std.mem.Allocator, + renderer: *c.SDL_Renderer, + /// Handle `n` is `entries[n - 1]`. + entries: std.ArrayList(Entry) = .empty, + paths: std.StringHashMapUnmanaged(abi.Image) = .empty, + + const Entry = struct { + texture: ?*c.SDL_Texture = null, + w: u32 = 0, + h: u32 = 0, + }; + + pub fn deinit(self: *Images) void { + for (self.entries.items) |entry| if (entry.texture) |t| c.SDL_DestroyTexture(t); + self.entries.deinit(self.gpa); + var keys = self.paths.keyIterator(); + while (keys.next()) |key| self.gpa.free(key.*); + self.paths.deinit(self.gpa); + } + + pub fn load(self: *Images, path: []const u8) abi.Image { + if (self.paths.get(path)) |image| return image; + var buf: [std.fs.max_path_bytes]u8 = undefined; + const z = std.fmt.bufPrintZ(&buf, "{s}", .{path}) catch return .none; + const surface = c.SDL_LoadPNG(z.ptr); + if (surface == null) std.log.warn("image {s}: {s}", .{ path, c.SDL_GetError() }); + const image = self.add(surface); + const key = self.gpa.dupe(u8, path) catch return image; + self.paths.put(self.gpa, key, image) catch self.gpa.free(key); + return image; + } + + pub fn decode(self: *Images, png: []const u8) abi.Image { + const io = c.SDL_IOFromConstMem(png.ptr, png.len) orelse return .none; + return self.add(c.SDL_LoadPNG_IO(io, true)); + } + + 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 }); + } + + /// Makes `image` show a GPU render target (GPU renderer only). + pub fn wrap(self: *Images, image: abi.Image, gpu_texture: *anyopaque, w: u32, h: u32) !void { + const entry = self.get(image) orelse return error.UnknownImage; + const props = c.SDL_CreateProperties(); + defer c.SDL_DestroyProperties(props); + _ = c.SDL_SetPointerProperty(props, c.SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER, gpu_texture); + _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, c.SDL_PIXELFORMAT_ABGR8888); + _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, w); + _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, h); + 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 }; + } + + /// Stops showing a wrapped render target, before the target goes away. + pub fn unwrap(self: *Images, image: abi.Image) void { + const entry = self.get(image) orelse return; + if (entry.texture) |t| c.SDL_DestroyTexture(t); + entry.texture = null; + } + + 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.* = .{}; + } + + pub fn size(self: *Images, image: abi.Image) [2]u32 { + const entry = self.get(image) orelse return .{ 0, 0 }; + return .{ entry.w, entry.h }; + } + + pub fn get(self: *Images, image: abi.Image) ?*Entry { + const index = @intFromEnum(image); + if (index == 0 or index > self.entries.items.len) return null; + return &self.entries.items[index - 1]; + } + + /// Takes ownership of `surface`, which may be null (a missing image). + fn add(self: *Images, surface: ?*c.SDL_Surface) abi.Image { + const s = surface orelse return self.append(.{}); + defer c.SDL_DestroySurface(s); + const texture = c.SDL_CreateTextureFromSurface(self.renderer, s); + if (texture) |t| setup(t); + return self.append(.{ .texture = texture, .w = @intCast(s.*.w), .h = @intCast(s.*.h) }); + } + + fn append(self: *Images, entry: Entry) abi.Image { + self.entries.append(self.gpa, entry) catch return .none; + return @enumFromInt(self.entries.items.len); + } + + 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| { + 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 => {}, + } +} + +/// SDL's built-in 8x8 font, `scale` times larger. Stops at the first NUL. +pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color) void { + var buf: [1024]u8 = undefined; + const len = @min(std.mem.indexOfScalar(u8, bytes, 0) orelse bytes.len, buf.len - 1); + @memcpy(buf[0..len], bytes[0..len]); + buf[len] = 0; + setColor(renderer, color); + var sx: f32 = 1; + var sy: f32 = 1; + _ = c.SDL_GetRenderScale(renderer, &sx, &sy); + const s = @max(scale, 1); + _ = c.SDL_SetRenderScale(renderer, sx * s, sy * s); + _ = c.SDL_RenderDebugText(renderer, x / s, y / s, &buf); + _ = c.SDL_SetRenderScale(renderer, sx, sy); +} + +fn missing(renderer: *c.SDL_Renderer, dst: abi.Rect) void { + 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 }); +} + +fn setColor(renderer: *c.SDL_Renderer, color: abi.Color) void { + _ = c.SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); +} + +fn frect(r: abi.Rect) c.SDL_FRect { + return .{ .x = r.x, .y = r.y, .w = r.w, .h = r.h }; +} diff --git a/src/host/gpu.zig b/src/host/gpu.zig new file mode 100644 index 0000000..34c817f --- /dev/null +++ b/src/host/gpu.zig @@ -0,0 +1,346 @@ +//! Runs `abi.gpu` passes 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, +/// 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, + +fn Cached(comptime T: type) type { + return struct { object: *T, used: u64 }; +} + +const Target = struct { + width: u32, + height: u32, + texture: *c.SDL_GPUTexture, + samples: u8 = 1, + msaa: ?*c.SDL_GPUTexture = null, + 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 { + 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 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.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 }) |map| { + var it = map.iterator(); + while (it.next()) |entry| { + if (g.frame - entry.value_ptr.used < keep_frames) continue; + if (@TypeOf(map) == @TypeOf(&g.pipelines)) c.SDL_ReleaseGPUGraphicsPipeline(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); + + // 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] }; + // 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; + if (samples > 1) { + color.texture = t.msaa; + color.store_op = c.SDL_GPU_STOREOP_RESOLVE; + color.resolve_texture = t.texture; + } else { + color.texture = t.texture; + color.store_op = c.SDL_GPU_STOREOP_STORE; + } + 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 built = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| { + std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() }); + continue; + }; + if (bound != built) { + c.SDL_BindGPUGraphicsPipeline(rp, built); + bound = built; + } + c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = offset }, 1); + 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); + if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit; +} + +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; + } + 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.spirv); + h.update(std.mem.asBytes(&s.uniform_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.spirv.len, + .code = s.spirv.ptr, + .entrypoint = "main", + .format = c.SDL_GPU_SHADERFORMAT_SPIRV, + .stage = stage, + .num_samplers = 0, + .num_storage_textures = 0, + .num_storage_buffers = 0, + .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, @intFromEnum(p.primitive), @intFromEnum(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, @intFromEnum(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 (.{ @intFromEnum(face.compare), @intFromEnum(face.pass), @intFromEnum(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 }, + .num_vertex_buffers = 1, + .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, @intFromEnum(face.compare)) + 1, + .pass_op = @as(u32, @intFromEnum(face.pass)) + 1, + .fail_op = @as(u32, @intFromEnum(face.fail)) + 1, + .depth_fail_op = c.SDL_GPU_STENCILOP_KEEP, + }; +} diff --git a/src/host/library.zig b/src/host/library.zig new file mode 100644 index 0000000..6c9338f --- /dev/null +++ b/src/host/library.zig @@ -0,0 +1,83 @@ +//! Loading sketch libraries, and noticing when a build replaces one. +//! +//! `dlopen` returns the handle it already has for a path it loaded before, so +//! every load goes through a private copy with a fresh name. The copy is +//! deleted right after loading: the mapping keeps the code alive, and nothing +//! is left behind if the host dies. +const std = @import("std"); +const linux = std.os.linux; +const c = @import("c"); +const abi = @import("abi"); + +pub const Library = struct { + object: *c.SDL_SharedObject, + sketch: abi.Sketch, + + pub fn open(path: [:0]const u8) !Library { + const object = c.SDL_LoadObject(path.ptr) orelse return error.LoadLibrary; + errdefer c.SDL_UnloadObject(object); + var sketch: abi.Sketch = undefined; + inline for (@typeInfo(abi.Sketch).@"struct".fields) |field| { + const symbol = @field(abi.Sketch.symbols, field.name); + const address = c.SDL_LoadFunction(object, symbol) orelse return error.MissingEntryPoint; + @field(sketch, field.name) = @ptrCast(address); + } + if (sketch.info().abi != abi.hash) return error.AbiMismatch; + return .{ .object = object, .sketch = sketch }; + } + + /// Loads `source` through a uniquely named copy in `scratch_dir`. + pub fn openCopy(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const copy = try std.fmt.bufPrintZ(&buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }); + const cwd = std.Io.Dir.cwd(); + try cwd.copyFile(source, cwd, copy, io, .{}); + defer cwd.deleteFile(io, copy) catch {}; + return open(copy); + } + + pub fn close(self: *Library) void { + c.SDL_UnloadObject(self.object); + } +}; + +/// inotify on a library's directory, filtered to its file name. Builds +/// replace files by renaming (`MOVED_TO`) or rewrite them (`CLOSE_WRITE`). +pub const Watch = struct { + fd: i32, + name: []const u8, + + pub fn init(path: []const u8) !Watch { + const fd: i32 = @intCast(@as(isize, @bitCast(linux.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC)))); + if (fd < 0) return error.WatchFailed; + errdefer _ = linux.close(fd); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = std.fs.path.dirname(path) orelse "."; + const dir_z = try std.fmt.bufPrintZ(&buf, "{s}", .{dir}); + if (@as(isize, @bitCast(linux.inotify_add_watch(fd, dir_z, linux.IN.MOVED_TO | linux.IN.CLOSE_WRITE))) < 0) return error.WatchFailed; + return .{ .fd = fd, .name = std.fs.path.basename(path) }; + } + + pub fn deinit(self: Watch) void { + _ = linux.close(self.fd); + } + + /// Drains pending events; true if any named the library. + pub fn changed(self: Watch) bool { + var found = false; + var buf: [4096]u8 align(@alignOf(linux.inotify_event)) = undefined; + while (true) { + const rc = linux.read(self.fd, &buf, buf.len); + const len: isize = @bitCast(rc); + if (len <= 0) return found; + var off: usize = 0; + while (off + @sizeOf(linux.inotify_event) <= @as(usize, @intCast(len))) { + const event: *const linux.inotify_event = @ptrCast(@alignCast(&buf[off])); + off += @sizeOf(linux.inotify_event) + event.len; + if (event.getName()) |name| { + if (std.mem.eql(u8, name, self.name)) found = true; + } + } + } + } +}; diff --git a/src/host/memory.zig b/src/host/memory.zig new file mode 100644 index 0000000..dd9f632 --- /dev/null +++ b/src/host/memory.zig @@ -0,0 +1,406 @@ +//! Sketch memory by lifetime. +//! +//! `StateFile`: one `MAP_SHARED` file holding the live state and its snapshot +//! slots, plus a header describing the layout, so the state outlives restarts, +//! a probe can read it from another process, and a reload with a changed +//! layout can carry the old values over field by field. +const std = @import("std"); +const posix = std.posix; +const linux = std.os.linux; +const abi = @import("abi"); +const field_value = @import("fields.zig"); + +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".*; + +pub const Header = extern struct { + magic: [8]u8 = file_magic, + size: u64, + alignment: u64, + hash: u64, + /// Distance between slots, page aligned. + stride: u64, + /// Bit `i`: slot `i` holds state. + used: u32, + field_count: u32, + strings_len: u32, + reserved: u32 = 0, +}; + +/// A leaf as stored in the file: strings are offsets into the string table. +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, + reserved: [3]u8 = @splat(0), +}; + +/// A layout the host owns: copied out of a sketch, or read from a file. +pub const Layout = struct { + size: usize = 0, + alignment: usize = 1, + hash: u64 = 0, + fields: []const Leaf = &.{}, + + pub const Leaf = struct { + path: []const u8, + offset: u32, + size: u32, + kind: abi.Field.Kind, + hash: u64, + tags: []const u8, + + pub fn bytes(leaf: Leaf, memory: []const u8) []const u8 { + return memory[leaf.offset..][0..leaf.size]; + } + }; + + pub fn copy(arena: std.mem.Allocator, l: abi.Layout) !Layout { + const fields = try arena.alloc(Leaf, l.fields.len); + for (fields, l.fields) |*to, from| to.* = .{ + .path = try arena.dupe(u8, std.mem.span(from.path)), + .offset = from.offset, + .size = from.size, + .kind = from.kind, + .hash = from.hash, + .tags = try arena.dupe(u8, std.mem.span(from.tags)), + }; + return .{ .size = l.size, .alignment = l.alignment, .hash = l.hash, .fields = fields }; + } + + pub fn find(self: Layout, path: []const u8) ?Leaf { + for (self.fields) |leaf| if (std.mem.eql(u8, leaf.path, path)) return leaf; + return null; + } +}; + +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. +pub fn migrate(from: Layout, old: []const u8, to: Layout, new: []u8) Migration { + var result: Migration = .{}; + for (to.fields) |leaf| { + const before = from.find(leaf.path) orelse { + 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)) { + result.kept += 1; + } else result.reset += 1; + } + return result; +} + +/// 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; + const value = field_value.tagValue(to.tags, name) orelse return false; + field_value.writeInt(new[to.offset..][0..to.size], value); + return true; +} + +pub const StateFile = struct { + fd: posix.fd_t, + map: []align(page) u8, + /// Layout of the bytes in the file, owned by `arena`. + 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. + 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) { + 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 = &.{}; + } + try self.resize(0); + self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; + return self; + } + + pub fn close(self: *StateFile) void { + if (self.map.len != 0) posix.munmap(self.map); + _ = posix.system.close(self.fd); + self.arena.deinit(); + } + + pub fn header(self: *StateFile) *Header { + return @ptrCast(self.map.ptr); + } + + pub fn slot(self: *StateFile, index: usize) []align(page) u8 { + std.debug.assert(index < slot_count); + const h = self.header(); + const start = header_len + index * h.stride; + return @alignCast(self.map[start..][0..h.size]); + } + + pub fn used(self: *StateFile, index: usize) bool { + return self.header().used & (@as(u32, 1) << @intCast(index)) != 0; + } + + pub fn markUsed(self: *StateFile, index: usize, value: bool) void { + const bit = @as(u32, 1) << @intCast(index); + if (value) self.header().used |= bit else self.header().used &= ~bit; + } + + pub const Adoption = union(enum) { + unchanged, + created, + migrated: Migration, + }; + + /// 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; + const had_state = self.header().used & 1 != 0; + + // Keep the old bytes and layout while the file is rebuilt. + var old_arena: std.heap.ArenaAllocator = .init(gpa); + defer old_arena.deinit(); + const old_layout = self.layout; + var old_slots: [slot_count]?[]u8 = @splat(null); + for (&old_slots, 0..) |*copy, i| { + if (self.used(i)) copy.* = try old_arena.allocator().dupe(u8, self.slot(i)); + } + const old_used = self.header().used; + // `old_layout` points into `self.arena`: move it aside before resetting. + var kept = self.arena; + defer kept.deinit(); + self.arena = .init(gpa); + + self.layout = try Layout.copy(self.arena.allocator(), new); + 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 }; + try self.writeLayout(); + + var total: Migration = .{}; + for (old_slots, 0..) |maybe_old, i| { + const old = maybe_old orelse continue; + const bytes = self.slot(i); + @memset(bytes, 0); + defaults(.state, bytes.ptr); + const m = migrate(old_layout, old, self.layout, bytes); + total.kept += m.kept; + if (i == 0) total.reset = m.reset; + } + if (!had_state) { + self.markUsed(0, false); + return .created; + } + return .{ .migrated = total }; + } + + fn valid(self: *StateFile) bool { + 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; + } + + fn resize(self: *StateFile, stride: usize) !void { + const len = header_len + slot_count * stride; + if (self.map.len != 0) posix.munmap(self.map); + self.map = &.{}; + switch (posix.errno(posix.system.ftruncate(self.fd, @intCast(len)))) { + .SUCCESS => {}, + else => |err| return posix.unexpectedErrno(err), + } + self.map = try mapFile(self.fd, len, .{ .READ = true, .WRITE = true }); + } + + fn writeLayout(self: *StateFile) !void { + const h = self.header(); + const fields: [*]StoredField = @ptrCast(@alignCast(self.map.ptr + @sizeOf(Header))); + const strings_start = @sizeOf(Header) + self.layout.fields.len * @sizeOf(StoredField); + var strings: usize = 0; + for (self.layout.fields, 0..) |leaf, i| { + if (strings_start + strings + leaf.path.len + leaf.tags.len > header_len) return error.LayoutTooLarge; + const base = strings_start + strings; + @memcpy(self.map[base..][0..leaf.path.len], leaf.path); + @memcpy(self.map[base + leaf.path.len ..][0..leaf.tags.len], leaf.tags); + fields[i] = .{ + .offset = leaf.offset, + .size = leaf.size, + .hash = leaf.hash, + .kind = leaf.kind, + .path = @intCast(strings), + .path_len = @intCast(leaf.path.len), + .tags = @intCast(strings + leaf.path.len), + .tags_len = @intCast(leaf.tags.len), + }; + strings += leaf.path.len + leaf.tags.len; + } + h.field_count = @intCast(self.layout.fields.len); + h.strings_len = @intCast(strings); + } +}; + +/// The layout stored in a state file's header, or null if it has none. +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 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; + // Copied: the mapping moves when the file is resized. + leaf.* = .{ + .path = try arena.dupe(u8, strings[f.path..][0..f.path_len]), + .offset = f.offset, + .size = f.size, + .kind = f.kind, + .hash = f.hash, + .tags = try arena.dupe(u8, strings[f.tags..][0..f.tags_len]), + }; + } + return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves }; +} + +pub fn mapFile(fd: posix.fd_t, len: usize, prot: posix.PROT) ![]align(page) u8 { + return posix.mmap(null, len, prot, .{ .TYPE = .SHARED }, fd, 0); +} + +pub fn fileSize(fd: posix.fd_t) !u64 { + var stat: linux.Statx = undefined; + switch (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &stat))) { + .SUCCESS => {}, + else => |err| return posix.unexpectedErrno(err), + } + return stat.size; +} + +/// Maps a whole file read-only; empty when missing or empty. +pub fn mapReadOnly(path: []const u8) []align(page) const u8 { + const fd = posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDONLY }, 0) catch return &.{}; + defer _ = posix.system.close(fd); + const len = fileSize(fd) catch return &.{}; + if (len == 0) return &.{}; + return posix.mmap(null, @intCast(len), .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0) catch &.{}; +} + +/// Session memory: survives reloads while its layout hash is unchanged. +/// `heap` is released with it. +pub const Session = struct { + bytes: []align(16) u8 = &.{}, + hash: u64 = 0, + heap: std.heap.ArenaAllocator, + + pub fn init(gpa: std.mem.Allocator) Session { + return .{ .heap = .init(gpa) }; + } + + pub fn deinit(self: *Session, gpa: std.mem.Allocator) void { + gpa.free(self.bytes); + self.heap.deinit(); + } + + /// True when the session was reset to `layout`'s defaults. + pub fn adopt(self: *Session, gpa: std.mem.Allocator, layout: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !bool { + if (self.hash == layout.hash and self.bytes.len == @max(layout.size, 1)) return false; + if (layout.alignment > 16) return error.SessionOveraligned; + gpa.free(self.bytes); + self.bytes = &.{}; + _ = self.heap.reset(.free_all); + self.bytes = try gpa.alignedAlloc(u8, .@"16", @max(layout.size, 1)); + @memset(self.bytes, 0); + defaults(.session, self.bytes.ptr); + self.hash = layout.hash; + return true; + } +}; + +test "enums migrate by tag name" { + const V1 = struct { mood: enum(u8) { calm, lost, angry } = .calm, gone: enum(u8) { a, b } = .b }; + const V2 = struct { mood: enum(u16) { angry = 7, calm, sleepy } = .sleepy, gone: enum(u8) { c } = .c }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .forbidden)); + const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .forbidden)); + for ([_]struct { @FieldType(V1, "mood"), @FieldType(V2, "mood") }{ .{ .calm, .calm }, .{ .angry, .angry }, .{ .lost, .sleepy } }) |case| { + const old: V1 = .{ .mood = case[0] }; + var new: V2 = .{}; + _ = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new)); + try std.testing.expectEqual(case[1], new.mood); + try std.testing.expectEqual(.c, new.gone); + } +} + +test "migration keeps unchanged fields and defaults the rest" { + const V1 = extern struct { a: u32 = 1, b: f32 = 2, gone: u8 = 3 }; + const V2 = extern struct { b: f32 = 20, a: u32 = 10, b2: [2]u8 = .{ 7, 7 } }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .forbidden)); + const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .forbidden)); + const old: V1 = .{ .a = 42, .b = 0.5 }; + var new: V2 = .{}; + const m = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new)); + try std.testing.expectEqual(V2{ .a = 42, .b = 0.5 }, new); + try std.testing.expectEqual(@as(usize, 2), m.kept); + try std.testing.expectEqual(@as(usize, 1), m.reset); +} + +test "state file migrates live state and snapshots, and a reopen reads the layout back" { + const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* }; + const V2 = extern struct { level: u16 = 1, score: u32 = 0 }; + const D = struct { + fn v1(_: abi.Memory, p: [*]u8) callconv(.c) void { + @as(*V1, @ptrCast(@alignCast(p))).* = .{}; + } + fn v2(_: abi.Memory, p: [*]u8) callconv(.c) void { + @as(*V2, @ptrCast(@alignCast(p))).* = .{}; + } + }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/test.state", .{&tmp.sub_path}); + const gpa = std.testing.allocator; + { + var file = try StateFile.open(gpa, path); + defer file.close(); + try std.testing.expectEqual(StateFile.Adoption.created, try file.adopt(gpa, abi.layout.of(V1, .forbidden), D.v1)); + file.markUsed(0, true); + @as(*V1, @ptrCast(file.slot(0).ptr)).score = 99; + @memcpy(file.slot(3), file.slot(0)); + file.markUsed(3, true); + } + var file = try StateFile.open(gpa, path); + defer file.close(); + try std.testing.expectEqual(abi.layout.hash(V1), file.layout.hash); + const adoption = try file.adopt(gpa, abi.layout.of(V2, .forbidden), D.v2); + try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset); + for ([_]usize{ 0, 3 }) |i| { + const s: *V2 = @ptrCast(file.slot(i).ptr); + try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, s.*); + } + try std.testing.expect(!file.used(1)); +} diff --git a/src/host/overlay.zig b/src/host/overlay.zig new file mode 100644 index 0000000..919fff6 --- /dev/null +++ b/src/host/overlay.zig @@ -0,0 +1,76 @@ +//! Debug overlays drawn by the host over any sketch: the live state's fields +//! and bytes, from the reflected layout, and the audio output waveform. +const std = @import("std"); +const abi = @import("abi"); +const memory = @import("memory.zig"); +const fields = @import("fields.zig"); + +const List = std.ArrayList(abi.Command); +const shown_bytes = 0x100; + +/// Each field hashes its path into a dark shade; bytes it owns wear the same +/// shade in the hex view below, and padding stays gray. +fn shade(path: []const u8) abi.Color { + const hash = std.hash.Wyhash.hash(0, path); + return .{ .r = @as(u8, @truncate(hash)) / 2, .g = @as(u8, @truncate(hash >> 8)) / 2, .b = @as(u8, @truncate(hash >> 16)) / 2 }; +} + +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; + const legend_top: f32 = 24; + const hex_top = legend_top + @as(f32, @floatFromInt(rows)) * 14 + 16; + const shown = @min(state.len, shown_bytes); + const height = hex_top + @as(f32, @floatFromInt((shown + 15) / 16)) * 14 + 10; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = 12, .y = 4, .w = width - 24, .h = height }, .color = .{ .r = 230, .g = 254, .b = 242 } } }); + try out.append(arena, .{ .text = .{ .x = 30, .y = 8, .scale = 1, .color = .{ .r = 24, .g = 24, .b = 24 }, .bytes = "MEMORY / overlay memory to hide" } }); + + // Legend: two fixed-width columns filled down then across. + const column = (width - 60) / 2; + for (layout.fields, 0..) |leaf, i| { + 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; + const line = try std.fmt.allocPrint(arena, "{x:0>4} {s: <26} {s}", .{ leaf.offset, name, value.written() }); + try out.append(arena, .{ .text = .{ + .x = 30 + @as(f32, @floatFromInt(i / rows)) * column, + .y = legend_top + @as(f32, @floatFromInt(i % rows)) * 14, + .scale = 1, + .color = shade(leaf.path), + .bytes = line[0..@min(line.len, @as(usize, @intFromFloat(column / 8)) - 1)], + } }); + } + + var colors: [shown_bytes]abi.Color = @splat(.{ .r = 0x9f, .g = 0x9f, .b = 0x9f }); + for (layout.fields) |leaf| { + if (leaf.offset >= shown) continue; + @memset(colors[leaf.offset..@min(shown, leaf.offset + leaf.size)], shade(leaf.path)); + } + for (state[0..shown], 0..) |byte, i| { + try out.append(arena, .{ .text = .{ + .x = 30 + @as(f32, @floatFromInt(i % 16)) * 24, + .y = hex_top + @as(f32, @floatFromInt(i / 16)) * 14, + .scale = 1, + .color = colors[i], + .bytes = try std.fmt.allocPrint(arena, "{X:0>2}", .{byte}), + } }); + } +} + +pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rate: u32, canvas: [2]u32) !void { + const green: abi.Color = .{ .r = 105, .g = 245, .b = 160 }; + const x = @as(f32, @floatFromInt(canvas[0])) - 526; + const top = @as(f32, @floatFromInt(canvas[1])) - 130; + const mid = top + 72; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = x, .y = top, .w = 514, .h = 118 }, .color = .{ .r = 24, .g = 24, .b = 24 } } }); + try out.append(arena, .{ .rect = .{ .dst = .{ .x = x + 1, .y = mid, .w = 512, .h = 1 }, .color = .{ .r = 60, .g = 85, .b = 65 } } }); + const ms = @as(f32, @floatFromInt(samples.len * 1000)) / @as(f32, @floatFromInt(@max(rate, 1))); + try out.append(arena, .{ .text = .{ .x = x + 8, .y = top + 10, .scale = 1, .color = green, .bytes = try std.fmt.allocPrint(arena, "OUTPUT ch1 / {d:.1}ms / overlay sound to hide", .{ms}) } }); + for (samples, 0..) |sample, i| { + const a = std.math.clamp(if (std.math.isFinite(sample)) sample else 0, -1, 1); + const previous = samples[i -| 1]; + const b = std.math.clamp(if (std.math.isFinite(previous)) previous else 0, -1, 1); + const y1 = mid - a * 36; + const y2 = mid - b * 36; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = x + 1 + @as(f32, @floatFromInt(i)), .y = @min(y1, y2), .w = 1, .h = @max(1, @abs(y2 - y1)) }, .color = green } }); + } +} diff --git a/src/host/probe.zig b/src/host/probe.zig new file mode 100644 index 0000000..4a693ec --- /dev/null +++ b/src/host/probe.zig @@ -0,0 +1,64 @@ +//! sketchbook-probe: prints the live state of any running sketch, from its +//! state file alone. The file header carries the layout, so the probe needs +//! no knowledge of the sketch: it maps the same pages read-only. +const std = @import("std"); +const memory = @import("memory.zig"); +const fields = @import("fields.zig"); + +const usage = + \\usage: sketchbook-probe [--watch] [--interval MS] STATE_FILE + \\Prints every field of the live state; --watch prints again on change. + \\ +; + +pub fn main(init: std.process.Init) !void { + var path: ?[]const u8 = null; + var watch = false; + var interval_ms: i64 = 100; + var args = init.minimal.args.iterate(); + _ = args.skip(); + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--watch")) { + watch = true; + } else if (std.mem.eql(u8, arg, "--interval")) { + interval_ms = std.fmt.parseInt(i64, args.next() orelse "", 10) catch fatal("--interval needs milliseconds"); + } else if (std.mem.startsWith(u8, arg, "-")) { + std.debug.print("{s}", .{usage}); + return; + } else path = arg; + } + 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"); + defer std.posix.munmap(map); + var arena: std.heap.ArenaAllocator = .init(init.gpa); + defer arena.deinit(); + const layout = (try memory.readLayout(arena.allocator(), map)) orelse fatal("state file has no layout yet"); + const header: *const memory.Header = @ptrCast(@alignCast(map.ptr)); + const live = map[memory.header_len..][0..header.size]; + + const shown = try arena.allocator().dupe(u8, live); + show(file, layout, live); + while (watch) { + try std.Io.sleep(init.io, .fromMilliseconds(interval_ms), .awake); + if (std.mem.eql(u8, shown, live)) continue; + @memcpy(shown, live); + show(file, layout, live); + } +} + +fn show(path: []const u8, layout: memory.Layout, live: []const u8) void { + var buf: [4096]u8 = undefined; + 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| { + 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() }); + } +} + +fn fatal(message: []const u8) noreturn { + std.debug.print("sketchbook-probe: {s}\n{s}", .{ message, usage }); + std.process.exit(2); +} diff --git a/src/host/root.zig b/src/host/root.zig new file mode 100644 index 0000000..637a325 --- /dev/null +++ b/src/host/root.zig @@ -0,0 +1,138 @@ +//! The sketchbook host: runs a sketch linked in, or loaded from a library +//! that it hot-reloads whenever a build replaces it. +//! +//! sketchbook [options] [LIBRARY] +//! --state FILE persistent state (default: .state) +//! --headless offscreen video, silent audio +//! --script FILE play a script instead of reading devices +//! --fresh start from default state: no snapshots or recordings +//! --define NAME=VALUE substitute {NAME} in the script +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); +pub const Host = @import("Host.zig"); +pub const memory = @import("memory.zig"); +pub const fields = @import("fields.zig"); +pub const script = @import("script.zig"); +pub const timeline = @import("timeline.zig"); + +/// Entry point for both the generic host (`linked == null`) and apps that +/// link their sketch in. +pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { + const gpa = init.gpa; + var options: Host.Options = .{}; + var script_path: ?[]const u8 = null; + var defines: std.ArrayList([2][]const u8) = .empty; + defer defines.deinit(gpa); + + var args = init.minimal.args.iterate(); + _ = args.skip(); + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--state")) { + options.state = args.next() orelse fatal("--state needs a file"); + } else if (std.mem.eql(u8, arg, "--fresh")) { + options.fresh = true; + } else if (std.mem.eql(u8, arg, "--headless")) { + options.headless = true; + } else if (std.mem.eql(u8, arg, "--script")) { + script_path = args.next() orelse fatal("--script needs a file"); + } else if (std.mem.eql(u8, arg, "--define")) { + const pair = args.next() orelse fatal("--define needs NAME=VALUE"); + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE"); + try defines.append(gpa, .{ pair[0..eq], pair[eq + 1 ..] }); + } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { + std.debug.print("{s}", .{usage}); + return; + } else if (std.mem.startsWith(u8, arg, "-")) { + fatal("unknown option (see --help)"); + } else { + options.library = arg; + } + } + if (linked == null and options.library == null) fatal("no sketch library given (see --help)"); + + sdl_heap.install(); + { + var host: Host = undefined; + try host.init(gpa, init.io, init.environ_map, options, linked); + defer host.deinit(); + if (script_path) |path| { + const source = try std.Io.Dir.cwd().readFileAlloc(init.io, path, gpa, .limited(1 << 20)); + defer gpa.free(source); + try script.run(&host, source, defines.items); + } else try host.run(); + } + if (sdl_heap.leaked()) return error.LeakedSdlMemory; +} + +const usage = + \\usage: sketchbook [options] [LIBRARY] + \\ --state FILE persistent state (default: sketch.state) + \\ --headless offscreen video, silent audio, no vsync + \\ --script FILE play a script instead of reading devices + \\ --fresh start from default state: no snapshots or recordings + \\ --define NAME=VALUE substitute {NAME} in the script + \\ +; + +fn fatal(message: []const u8) noreturn { + std.debug.print("sketchbook: {s}\n", .{message}); + std.process.exit(2); +} + +/// SDL's allocations go through a leak-checking allocator of their own, so a +/// session that leaks SDL memory fails loudly at exit. +const sdl_heap = struct { + var debug: std.heap.DebugAllocator(.{ .backing_allocator_zeroes = false }) = .{}; + const alignment: std.mem.Alignment = .of(std.c.max_align_t); + const header = alignment.forward(@sizeOf(usize)); + + fn install() void { + _ = c.SDL_SetMemoryFunctions(malloc, calloc, realloc, free); + } + fn leaked() bool { + return debug.deinit() == .leak; + } + fn block(size: usize) ?[*]u8 { + const total = std.math.add(usize, header, size) catch return null; + const base = debug.allocator().rawAlloc(total, alignment, @returnAddress()) orelse return null; + @as(*usize, @ptrCast(@alignCast(base))).* = total; + return base + header; + } + fn whole(mem: *anyopaque) []u8 { + const base: [*]u8 = @as([*]u8, @ptrCast(mem)) - header; + return base[0..@as(*const usize, @ptrCast(@alignCast(base))).*]; + } + fn malloc(size: usize) callconv(.c) ?*anyopaque { + return block(size); + } + fn calloc(n: usize, size: usize) callconv(.c) ?*anyopaque { + const bytes = std.math.mul(usize, n, size) catch return null; + const mem = block(bytes) orelse return null; + @memset(mem[0..bytes], 0); + return mem; + } + fn realloc(maybe: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { + const old = whole(maybe orelse return malloc(size)); + const total = std.math.add(usize, header, size) catch return null; + if (debug.allocator().rawRemap(old, alignment, total, @returnAddress())) |base| { + @as(*usize, @ptrCast(@alignCast(base))).* = total; + return base + header; + } + const new = block(size) orelse return null; + @memcpy(new[0..@min(size, old.len - header)], old[header..][0..@min(size, old.len - header)]); + debug.allocator().rawFree(old, alignment, @returnAddress()); + return new; + } + fn free(maybe: ?*anyopaque) callconv(.c) void { + debug.allocator().rawFree(whole(maybe orelse return), alignment, @returnAddress()); + } +}; + +test { + _ = memory; + _ = fields; + _ = timeline; + _ = @import("audio.zig"); + _ = @import("Console.zig"); +} diff --git a/src/host/script.zig b/src/host/script.zig new file mode 100644 index 0000000..4563a47 --- /dev/null +++ b/src/host/script.zig @@ -0,0 +1,139 @@ +//! End-to-end scripts: plain text that plays a sketch like a person would, +//! through the same routing and frames, on a fixed 60 Hz clock. +//! +//! # comment +//! click 710 320 move there, press and release the left button +//! move|down|up X Y one pointer event, then a frame +//! wheel X Y DELTA +//! 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 +//! frames N advance N frames without input +//! expect FIELD VALUE compare a state field (enums by name or number) +//! expect-audio KEY stream KEY has received samples +//! screenshot FILE save the next frame as PNG +//! 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. +const std = @import("std"); +const abi = @import("abi"); +const Host = @import("Host.zig"); +const fields = @import("fields.zig"); + +pub const frame_ns: u64 = std.time.ns_per_s / 60; + +pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !void { + var arena: std.heap.ArenaAllocator = .init(host.gpa); + defer arena.deinit(); + var now: u64 = std.time.ns_per_s; + var failures: usize = 0; + var lines = std.mem.splitScalar(u8, source, '\n'); + var number: usize = 0; + while (lines.next()) |raw| { + number += 1; + const line = try substitute(arena.allocator(), std.mem.trim(u8, raw, " \t\r"), defines); + if (line.len == 0 or line[0] == '#') continue; + var words = std.mem.tokenizeAny(u8, line, " \t"); + const command = words.next().?; + const rest = std.mem.trim(u8, words.rest(), " \t"); + step(host, arena.allocator(), command, rest, &words, &now) catch |err| { + failures += 1; + std.debug.print("script:{d}: {s}: {t}\n", .{ number, line, err }); + if (err != error.ExpectationFailed) break; + }; + if (host.quit) break; + } + if (failures > 0) return error.ScriptFailed; +} + +fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []const u8, words: anytype, now: *u64) !void { + const eq = std.mem.eql; + if (eq(u8, command, "click")) { + const x, const y = try point(words); + try host.route(.{ .kind = .mouse_move, .time = now.*, .x = x, .y = y }); + try host.route(.{ .kind = .mouse_down, .time = now.*, .x = x, .y = y, .code = 1 }); + try host.route(.{ .kind = .mouse_up, .time = now.*, .x = x, .y = y, .code = 1 }); + } else if (eq(u8, command, "move") or eq(u8, command, "down") or eq(u8, command, "up")) { + const x, const y = try point(words); + const kind: abi.Event.Kind = if (eq(u8, command, "move")) .mouse_move else if (eq(u8, command, "down")) .mouse_down else .mouse_up; + try host.route(.{ .kind = kind, .time = now.*, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1 }); + } else if (eq(u8, command, "wheel")) { + const x, const y = try point(words); + const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta); + try host.route(.{ .kind = .wheel, .time = now.*, .x = x, .y = y, .value = @bitCast(delta) }); + } else if (eq(u8, command, "cancel")) { + try host.route(.{ .kind = .cancel, .time = now.* }); + } else if (eq(u8, command, "key")) { + const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; + try host.route(.{ .kind = .key_down, .time = now.*, .code = @intFromEnum(key) }); + try host.route(.{ .kind = .key_up, .time = now.*, .code = @intFromEnum(key) }); + } else if (eq(u8, command, "type")) { + for (rest) |byte| try host.route(.{ .kind = .text, .time = now.*, .value = byte }); + } else if (eq(u8, command, "console")) { + host.runLine(rest, now.*); + } 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")) { + 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; + if (!fields.matches(leaf, host.live(), want)) { + 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() }); + 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; + return; + } else if (eq(u8, command, "screenshot")) { + if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir); + host.screenshot = try arena.dupeZ(u8, rest); + } else if (eq(u8, command, "load")) { + try host.load(rest); + } else if (eq(u8, command, "reload")) { + try host.reload(); + } else if (eq(u8, command, "await-reload")) { + const seconds = try std.fmt.parseInt(u64, rest, 10); + const start = host.reloads; + const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s; + while (host.reloads == start) { + if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload; + try advance(host, now); + try std.Io.sleep(host.io, .fromMilliseconds(10), .awake); + } + return; + } else if (eq(u8, command, "quit")) { + host.quit = true; + return; + } else return error.UnknownScriptCommand; + try advance(host, now); +} + +fn advance(host: *Host, now: *u64) !void { + try host.frame(now.*); + now.* += frame_ns; +} + +fn point(words: anytype) !struct { f32, f32 } { + const x = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedPoint); + const y = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedPoint); + return .{ x, y }; +} + +fn substitute(arena: std.mem.Allocator, line: []const u8, defines: []const [2][]const u8) ![]const u8 { + var out = line; + for (defines) |pair| { + const pattern = try std.fmt.allocPrint(arena, "{{{s}}}", .{pair[0]}); + out = try std.mem.replaceOwned(u8, arena, out, pattern, pair[1]); + } + return out; +} diff --git a/src/host/timeline.zig b/src/host/timeline.zig new file mode 100644 index 0000000..cd65478 --- /dev/null +++ b/src/host/timeline.zig @@ -0,0 +1,208 @@ +//! Snapshots, input recordings and replay: generic over state bytes and +//! `abi.Event`s, so any sketch gets time travel for free. +//! +//! Playback is host state, not sketch state: wall clocks, modes and cursors +//! must not contaminate byte comparisons between two runs of a sketch. +const std = @import("std"); +const posix = std.posix; +const abi = @import("abi"); +const memory = @import("memory.zig"); + +pub const recording_len = 4 * 1024 * 1024; +pub const recording_count = 16; +pub const recordings_len = recording_len * recording_count; +const recording_magic = 0x52454305; +pub const capacity = (recording_len - 32) / @sizeOf(abi.Event); + +pub const Recording = extern struct { + duration: u64, + count: u32, + snapshot: u32, + magic: u32, + reserved: [3]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]; + } +}; + +comptime { + std.debug.assert(@sizeOf(Recording) == recording_len); +} + +/// Snapshot slots of a state file, and the recordings that start from them. +pub const Bank = struct { + state: *memory.StateFile, + inputs: []align(memory.page) u8, + + pub fn slot(self: Bank, index: usize) []u8 { + return self.state.slot(index); + } + pub fn recording(self: Bank, index: usize) *Recording { + std.debug.assert(index < recording_count); + return @ptrCast(@alignCast(self.inputs[index * recording_len ..].ptr)); + } + pub fn hasSnapshot(self: Bank, index: usize) bool { + return index > 0 and index < memory.slot_count and self.state.used(index); + } + pub fn save(self: Bank, index: usize) void { + std.debug.assert(index > 0 and index < memory.slot_count); + for (0..recording_count) |i| { + const r = self.recording(i); + if (r.snapshot == index) r.magic = 0; + } + @memcpy(self.slot(index), self.slot(0)); + self.state.markUsed(index, true); + } + pub fn restore(self: Bank, index: usize) !void { + if (!self.hasSnapshot(index)) return error.EmptySnapshot; + @memcpy(self.slot(0), self.slot(index)); + } + pub fn get(self: Bank, index: usize) !*Recording { + const r = self.recording(index); + 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; + } +}; + +pub const Timeline = struct { + bank: Bank, + mode: abi.Mode = .live, + selected: usize = 0, + cursor: usize = 0, + position: u64 = 0, + clock: u64 = 0, + + pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: 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); + const r = self.bank.recording(index); + @memset(std.mem.asBytes(r)[0..32], 0); + r.magic = recording_magic; + r.snapshot = @intCast(snapshot); + self.selected = index; + self.cursor = 0; + self.position = 0; + self.clock = now; + self.mode = .recording; + } + pub fn capture(self: *Timeline, event: abi.Event) !void { + if (self.mode != .recording) return; + const r = self.bank.recording(self.selected); + if (r.count == capacity) { + 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; + self.cursor = r.count; + } + pub fn stop(self: *Timeline, now: u64) void { + if (self.mode == .recording) { + const r = self.bank.recording(self.selected); + r.duration = @max(r.duration, now -| self.clock); + self.position = r.duration; + } + self.mode = .live; + } + pub fn play(self: *Timeline, index: usize, now: u64) !void { + const r = try self.bank.get(index); + try self.bank.restore(r.snapshot); + self.selected = index; + self.cursor = 0; + self.position = 0; + self.clock = now; + self.mode = .playing; + } + pub fn pause(self: *Timeline, now: u64) void { + if (self.mode == .playing) { + self.mode = .paused; + } else if (self.mode == .paused) { + self.clock = now; + self.mode = .playing; + } + } + /// The recorded events due by `now`. 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; + 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. + 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); + self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time; + self.mode = .paused; + return r.events[0..self.cursor]; + } + 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; + const events = try self.seekCount(count); + self.position = position; + return events; + } + /// Moves by `steps` input events, passing over frame ticks. + pub fn step(self: *Timeline, steps: i64) ![]const abi.Event { + const r = try self.bank.get(self.selected); + var cursor = 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; + 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; + } else { + while (cursor > 0 and r.events[cursor - 1].kind == .tick) cursor -= 1; + if (cursor == 0) break; + cursor -= 1; + } + } + return self.seekCount(cursor); + } +}; + +/// Maps the recordings file next to a state file, creating it when missing. +pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 { + const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); + defer _ = posix.system.close(fd); + if (try memory.fileSize(fd) != recordings_len) switch (posix.errno(posix.system.ftruncate(fd, recordings_len))) { + .SUCCESS => {}, + else => |err| return posix.unexpectedErrno(err), + }; + return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true }); +} diff --git a/src/keys.zig b/src/keys.zig new file mode 100644 index 0000000..b195d2a --- /dev/null +++ b/src/keys.zig @@ -0,0 +1,107 @@ +//! USB HID keyboard usages: SDL scancodes use them, and browsers map +//! `KeyboardEvent.code` onto them, so recordings mean the same key everywhere. +pub const Key = enum(u8) { + a = 4, + b, + c, + d, + e, + f, + g, + h, + i, + j, + k, + l, + m, + n, + o, + p, + q, + r, + s, + t, + u, + v, + w, + x, + y, + z, + @"1", + @"2", + @"3", + @"4", + @"5", + @"6", + @"7", + @"8", + @"9", + @"0", + @"return", + escape, + backspace, + tab, + space, + minus, + equals, + left_bracket, + right_bracket, + backslash, + semicolon = 51, + apostrophe, + grave, + comma, + period, + slash, + f1 = 58, + f2, + f3, + f4, + f5, + f6, + f7, + f8, + f9, + f10, + f11, + f12, + home = 74, + page_up, + delete, + end, + page_down, + right, + left, + down, + up, + keypad_enter = 88, + return2 = 158, + left_ctrl = 224, + left_shift, + left_alt, + left_gui, + right_ctrl, + right_shift, + right_alt, + right_gui, + _, + + pub const Mod = struct { + pub const shift: u32 = 1; + pub const ctrl: u32 = 2; + pub const alt: u32 = 4; + pub const gui: u32 = 8; + }; + + pub fn isEnter(key: Key) bool { + return key == .@"return" or key == .keypad_enter or key == .return2; + } +}; + +test "HID values match the specification's anchors" { + const std = @import("std"); + try std.testing.expectEqual(4, @intFromEnum(Key.a)); + try std.testing.expectEqual(39, @intFromEnum(Key.@"0")); + try std.testing.expectEqual(53, @intFromEnum(Key.grave)); + try std.testing.expectEqual(82, @intFromEnum(Key.up)); +} diff --git a/src/layout.zig b/src/layout.zig new file mode 100644 index 0000000..e779260 --- /dev/null +++ b/src/layout.zig @@ -0,0 +1,148 @@ +//! 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. +//! +//! State is saved to disk and snapshotted, so it may not hold pointers at all. +//! Session memory lives only in the host process and may point into memory +//! the host owns (its heap, mapped files), never into the sketch library. +const std = @import("std"); +const abi = @import("abi.zig"); + +pub const Pointers = enum { forbidden, host_only }; + +pub fn of(comptime T: type, comptime pointers: Pointers) abi.Layout { + return comptime blk: { + @setEvalBranchQuota(1_000_000); + if (pointers == .forbidden) noPointers(T, @typeName(T)); + const Leaves = struct { + const list = flatten(T, "", 0); + const fields: [list.len]abi.Field = list[0..list.len].*; + }; + break :blk .{ + .size = @sizeOf(T), + .alignment = @alignOf(T), + .hash = hash(T), + .fields = &Leaves.fields, + }; + }; +} + +fn flatten(comptime T: type, comptime prefix: []const u8, comptime base: usize) []const abi.Field { + comptime { + if (@typeInfo(T) != .@"struct") return &.{leaf(T, if (prefix.len == 0) "value" else prefix, base)}; + var leaves: []const abi.Field = &.{}; + for (@typeInfo(T).@"struct".fields) |field| { + if (field.is_comptime or @sizeOf(field.type) == 0) continue; + const path = if (prefix.len == 0) field.name else prefix ++ "." ++ field.name; + const offset = base + @offsetOf(T, field.name); + leaves = leaves ++ if (@typeInfo(field.type) == .@"struct" and @typeInfo(field.type).@"struct".backing_integer == null) + flatten(field.type, path, offset) + else + &[_]abi.Field{leaf(field.type, path, offset)}; + } + return leaves; + } +} + +fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize) abi.Field { + comptime { + const kind: abi.Field.Kind = switch (@typeInfo(T)) { + .int => |i| if (i.signedness == .signed) .int else .uint, + .float => .float, + .bool => .bool, + .@"enum" => .@"enum", + .array => .array, + else => .bytes, + }; + return .{ + .path = std.fmt.comptimePrint("{s}", .{path}), + .offset = offset, + .size = @sizeOf(T), + .kind = kind, + .hash = hash(T), + .tags = if (kind == .@"enum") tags(T) else "", + }; + } +} + +fn noPointers(comptime T: type, comptime path: []const u8) void { + comptime switch (@typeInfo(T)) { + .pointer => @compileError("State cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Store handles, indices or offsets, or keep it in Session."), + .array => |a| noPointers(a.child, path ++ "[]"), + .vector => |v| noPointers(v.child, path ++ "[]"), + .optional => |o| noPointers(o.child, path), + .@"struct" => |s| for (s.fields) |f| noPointers(f.type, path ++ "." ++ f.name), + .@"union" => |u| for (u.fields) |f| noPointers(f.type, path ++ "." ++ f.name), + else => {}, + }; +} + +fn tags(comptime E: type) [:0]const u8 { + comptime { + var text: []const u8 = ""; + for (@typeInfo(E).@"enum".fields, 0..) |field, i| { + text = text ++ (if (i == 0) "" else ",") ++ std.fmt.comptimePrint("{s}={d}", .{ field.name, field.value }); + } + return std.fmt.comptimePrint("{s}", .{text}); + } +} + +/// Equal hashes mean the bytes can be copied and keep their meaning. Enum +/// leaves also carry their tags, so a host can remap them by name. +pub fn hash(comptime T: type) u64 { + return comptime blk: { + @setEvalBranchQuota(1_000_000); + break :blk std.hash.Wyhash.hash(0, signature(T)); + }; +} + +pub fn signature(comptime T: type) []const u8 { + comptime { + return switch (@typeInfo(T)) { + .int => |i| std.fmt.comptimePrint("{c}{d}", .{ if (i.signedness == .signed) 'i' else 'u', i.bits }), + .float => |f| std.fmt.comptimePrint("f{d}", .{f.bits}), + .bool => "b", + .void => "v", + .@"enum" => |e| "e(" ++ signature(e.tag_type) ++ ":" ++ tags(T) ++ ")", + .array => |a| std.fmt.comptimePrint("[{d}]", .{a.len}) ++ signature(a.child), + .vector => |v| std.fmt.comptimePrint("@{d}", .{v.len}) ++ signature(v.child), + .optional => |o| "?" ++ signature(o.child), + .@"struct" => |s| blk: { + var text: []const u8 = std.fmt.comptimePrint("s{d}{{", .{@sizeOf(T)}); + for (s.fields) |field| { + if (field.is_comptime) continue; + text = text ++ std.fmt.comptimePrint("{s}@{d}:", .{ field.name, @offsetOf(T, field.name) }) ++ signature(field.type) ++ ";"; + } + break :blk text ++ "}"; + }, + .@"union" => |u| blk: { + var text: []const u8 = std.fmt.comptimePrint("u{d}{{", .{@sizeOf(T)}); + if (u.tag_type) |tag| text = text ++ signature(tag) ++ "|"; + for (u.fields) |field| text = text ++ field.name ++ ":" ++ signature(field.type) ++ ";"; + break :blk text ++ "}"; + }, + .pointer => |p| std.fmt.comptimePrint("*{s}:{s}", .{ @tagName(p.size), @typeName(p.child) }), + .@"opaque" => "opaque", + .@"fn" => @typeName(T), + else => @compileError("unsupported type in sketch memory: " ++ @typeName(T)), + }; + } +} + +test "leaves flatten structs, keep arrays whole and reject nothing pointer-free" { + 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, .forbidden); + const fields = l.fields; + try std.testing.expectEqual(4, 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.expectEqual(@as(u32, 4), fields[2].offset); + try std.testing.expect(hash([4]f32) != hash([5]f32)); + try std.testing.expect(hash(enum(u8) { a }) != hash(enum(u8) { a, b })); +} diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..294b4dd --- /dev/null +++ b/src/main.zig @@ -0,0 +1,6 @@ +//! The generic host: `sketchbook path/to/libsketch.so`. +const std = @import("std"); + +pub fn main(init: std.process.Init) !void { + return @import("host").main(init, null); +} diff --git a/src/sketch/camera.zig b/src/sketch/camera.zig new file mode 100644 index 0000000..460fc8a --- /dev/null +++ b/src/sketch/camera.zig @@ -0,0 +1,60 @@ +//! A 2D camera maps world points to canvas pixels. Zoom keeps the world point +//! underneath the pointer stationary; panning is measured in screen pixels. +//! Points and rects are duck-typed (see `shape.zig`) and come back in the +//! caller's own type. +const std = @import("std"); +const shape = @import("shape.zig"); + +pub const Camera = struct { + x: f32 = 0, + y: f32 = 0, + zoom: f32 = 1, + + pub fn toScreen(self: Camera, world: anytype) shape.Out(@TypeOf(world)) { + const T = shape.Out(@TypeOf(world)); + const x = self.x + shape.get(world, "x") * self.zoom; + const y = self.y + shape.get(world, "y") * self.zoom; + return if (comptime shape.isRect(T)) + shape.make(T, x, y, shape.get(world, "w") * self.zoom, shape.get(world, "h") * self.zoom) + else + shape.point(T, x, y); + } + pub fn toWorld(self: Camera, screen: anytype) shape.Out(@TypeOf(screen)) { + const T = shape.Out(@TypeOf(screen)); + const x = (shape.get(screen, "x") - self.x) / self.zoom; + const y = (shape.get(screen, "y") - self.y) / self.zoom; + return if (comptime shape.isRect(T)) + shape.make(T, x, y, shape.get(screen, "w") / self.zoom, shape.get(screen, "h") / self.zoom) + else + shape.point(T, x, y); + } + pub fn pan(self: *Camera, delta: anytype) void { + self.x += shape.get(delta, "x"); + self.y += shape.get(delta, "y"); + } + /// Zoom by `1.2^wheel` around `screen`, clamped to `[min, max]`. + pub fn zoomAt(self: *Camera, screen: anytype, wheel: f32, limits: struct { min: f32 = 0.04, max: f32 = 12 }) void { + if (!std.math.isFinite(wheel)) return; + const sx = shape.get(screen, "x"); + const sy = shape.get(screen, "y"); + const wx = (sx - self.x) / self.zoom; + const wy = (sy - self.y) / self.zoom; + self.zoom = std.math.clamp(self.zoom * std.math.pow(f32, 1.2, std.math.clamp(wheel, -40, 40)), limits.min, limits.max); + self.x = sx - wx * self.zoom; + self.y = sy - wy * self.zoom; + } +}; + +test "zooming keeps the point under the cursor fixed, in any shape" { + var camera: Camera = .{ .x = 10, .y = 20, .zoom = 0.5 }; + const P = struct { x: f32, y: f32 }; + const before = camera.toWorld(P{ .x = 300, .y = 200 }); + camera.zoomAt(@Vector(2, f32){ 300, 200 }, 3, .{}); + const after = camera.toWorld(P{ .x = 300, .y = 200 }); + try std.testing.expectApproxEqAbs(before.x, after.x, 1e-3); + try std.testing.expectApproxEqAbs(before.y, after.y, 1e-3); + const r = camera.toScreen([4]f32{ 0, 0, 10, 10 }); + try std.testing.expectApproxEqAbs(camera.zoom * 10, r[2], 1e-4); + // Literals come back as f32 points. + try std.testing.expectEqual(shape.Point{ .x = 12, .y = 21 }, (Camera{ .x = 10, .y = 20 }).toScreen(.{ .x = 2, .y = 1 })); +} diff --git a/src/sketch/root.zig b/src/sketch/root.zig new file mode 100644 index 0000000..316a886 --- /dev/null +++ b/src/sketch/root.zig @@ -0,0 +1,215 @@ +//! The sketch library: compiled into every app and reloaded with it. +//! +//! An app is an ordinary Zig module. Every declaration is optional: +//! +//! pub const name = "my sketch"; +//! pub const width = 960; +//! pub const height = 600; +//! pub const State = struct { ... }; // persisted and snapshotted: no pointers +//! pub const Session = struct { ... }; // survives reloads, never saved +//! pub const commands = .{"hello"}; // console completions +//! pub fn init(state: *State, host: sk.Host) void +//! pub fn update(state: *State, in: *const sk.Input) void +//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void +//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool +//! +//! `update` must be deterministic: the host replays recorded input through it. +//! `draw` presents state as pictures and sound, and may only change `Session`. +//! Geometry and colors are duck-typed: see `shape`. +const std = @import("std"); +pub const abi = @import("abi"); +pub const shape = @import("shape.zig"); +pub const Key = abi.Key; +pub const Camera = @import("camera.zig").Camera; +pub const tween = @import("tween.zig"); +pub const web = @import("web.zig"); + +pub const Rect = abi.Rect; +pub const Color = abi.Color; +pub const Event = abi.Event; +pub const Input = abi.Input; +pub const Mode = abi.Mode; +pub const Host = abi.Host; +pub const Image = abi.Image; +pub const Audio = abi.Audio; +pub const Cursor = abi.Cursor; +pub const Voice = abi.Voice; + +/// What `draw` receives: input, host services, allocators and the command list. +pub const Frame = struct { + ctx: *const abi.Context, + in: *const Input, + host: Host, + /// Frame lifetime. + arena: std.mem.Allocator, + /// Session lifetime; survives reloads. + gpa: std.mem.Allocator, + + pub fn init(ctx: *const abi.Context) Frame { + return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .arena = ctx.arena, .gpa = ctx.gpa }; + } + + pub fn emit(f: *Frame, command: abi.Command) void { + f.ctx.commands.append(f.arena, command) catch f.host.log("frame arena full: command dropped"); + } + + pub fn clear(f: *Frame, color: anytype) void { + f.emit(.{ .clear = shape.color(color) }); + } + pub fn fill(f: *Frame, r: anytype, color: anytype) void { + f.emit(.{ .rect = .{ .dst = shape.rect(r), .color = shape.color(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, + } }); + } + /// `bytes` must live until the frame is consumed: literals, `arena` and + /// session memory all do. + 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 = bytes } }); + } + pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void { + f.text(x, y, scale, f.format(fmt, args), color); + } + /// Formats into the frame arena. + pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.allocPrint(f.arena, fmt, args) catch "?"; + } + /// 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) }); + } + pub fn canvas(f: *Frame, w: u32, h: u32) void { + f.emit(.{ .canvas = .{ .w = w, .h = h } }); + } + pub fn cursor(f: *Frame, kind: Cursor) void { + f.emit(.{ .cursor = kind }); + } + pub fn voice(f: *Frame, v: Voice) void { + f.emit(.{ .voice = v }); + } + pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void { + f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } }); + } + pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void { + f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } }); + } + /// Runs GPU work described as data (see `abi.gpu`) into `pass.image`. + pub fn gpu(f: *Frame, pass: abi.gpu.Pass) void { + f.emit(.{ .gpu = pass }); + } + pub fn quit(f: *Frame) void { + f.emit(.quit); + } +}; + +/// What `command` receives: somewhere to answer, and the current input. +pub const Console = struct { + host: Host, + in: *const Input, + + pub fn log(c: *Console, message: []const u8) void { + c.host.log(message); + } + pub fn print(c: *Console, comptime fmt: []const u8, args: anytype) void { + c.host.print(fmt, args); + } +}; + +/// The entry points of `App`, for a host that links it statically. +pub fn sketch(comptime App: type) abi.Sketch { + const G = Glue(App); + return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .update = G.update, .draw = G.draw, .command = G.command }; +} + +/// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library. +pub fn exportSketch(comptime App: type) void { + const G = Glue(App); + const names = abi.Sketch.symbols; + @export(&G.info, .{ .name = names.info }); + @export(&G.defaults, .{ .name = names.defaults }); + @export(&G.init, .{ .name = names.init }); + @export(&G.update, .{ .name = names.update }); + @export(&G.draw, .{ .name = names.draw }); + @export(&G.command, .{ .name = names.command }); +} + +pub fn Glue(comptime App: type) type { + return struct { + pub const State = if (@hasDecl(App, "State")) App.State else struct {}; + pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {}; + + pub const description: abi.Info = .{ + .abi = abi.hash, + .name = if (@hasDecl(App, "name")) App.name else "sketch", + .width = if (@hasDecl(App, "width")) App.width else 960, + .height = if (@hasDecl(App, "height")) App.height else 600, + .state = abi.layout.of(State, .forbidden), + .session = abi.layout.of(Session, .host_only), + .commands = if (@hasDecl(App, "commands")) &App.commands else &.{}, + }; + + fn state(ptr: [*]u8) *State { + return @ptrCast(@alignCast(ptr)); + } + fn session(ptr: [*]u8) *Session { + return @ptrCast(@alignCast(ptr)); + } + fn arity(comptime func: anytype) usize { + return @typeInfo(@TypeOf(func)).@"fn".params.len; + } + + pub fn info() callconv(.c) *const abi.Info { + return &description; + } + pub fn defaults(which: abi.Memory, ptr: [*]u8) callconv(.c) void { + switch (which) { + .state => state(ptr).* = .{}, + .session => session(ptr).* = .{}, + } + } + pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { + if (!@hasDecl(App, "init")) return; + switch (comptime arity(App.init)) { + 1 => App.init(state(s)), + else => App.init(state(s), ctx.host), + } + } + pub fn update(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { + if (@hasDecl(App, "update")) App.update(state(s), ctx.input); + } + pub fn draw(ctx: *const abi.Context, s: [*]const u8, ss: [*]u8) callconv(.c) void { + if (!@hasDecl(App, "draw")) return; + var f: Frame = .init(ctx); + const current: *const State = @ptrCast(@alignCast(s)); + switch (comptime arity(App.draw)) { + 2 => App.draw(current, &f), + else => App.draw(current, session(ss), &f), + } + } + pub fn command(ctx: *const abi.Context, s: [*]u8, ss: [*]u8, line: *const []const u8) callconv(.c) bool { + if (!@hasDecl(App, "command")) return false; + var c: Console = .{ .host = ctx.host, .in = ctx.input }; + return switch (comptime arity(App.command)) { + 3 => App.command(state(s), &c, line.*), + else => App.command(state(s), session(ss), &c, line.*), + } catch |err| { + c.print("{t}. Type help for usage.", .{err}); + return true; + }; + } + }; +} + +test { + _ = abi.layout; + _ = shape; + _ = @import("camera.zig"); + _ = tween; +} diff --git a/src/sketch/shape.zig b/src/sketch/shape.zig new file mode 100644 index 0000000..9bd4cee --- /dev/null +++ b/src/sketch/shape.zig @@ -0,0 +1,209 @@ +//! Duck-typed geometry. A point is anything with `x` and `y`, a rect anything +//! that also has `w` and `h` (or `width`/`height`), in any int or float type; +//! `@Vector`s and arrays of two or four elements work too. Functions return +//! the caller's own type where they build one, so sketches keep their data in +//! whatever shape suits them and never convert to library types. +const std = @import("std"); +const abi = @import("abi"); + +/// Anything with an `x` and a `y`: fields, or a 2+ element vector or array. +pub fn isPoint(comptime T: type) bool { + return switch (@typeInfo(T)) { + .vector => |v| v.len >= 2 and isNumber(v.child), + .array => |a| a.len >= 2 and isNumber(a.child), + .@"struct" => @hasField(T, "x") and @hasField(T, "y"), + .pointer => |p| p.size == .one and isPoint(p.child), + else => false, + }; +} + +/// A point that also has a size: `w`/`h` or `width`/`height`, or 4 elements. +pub fn isRect(comptime T: type) bool { + return isPoint(T) and switch (@typeInfo(T)) { + .vector => |v| v.len >= 4, + .array => |a| a.len >= 4, + .@"struct" => (@hasField(T, "w") and @hasField(T, "h")) or (@hasField(T, "width") and @hasField(T, "height")), + .pointer => |p| isRect(p.child), + else => false, + }; +} + +/// `r`, `g`, `b` (optionally `a`) fields, or a `0xRRGGBB` integer. +pub fn isColor(comptime T: type) bool { + return switch (@typeInfo(T)) { + .int, .comptime_int => true, + .@"struct" => @hasField(T, "r") and @hasField(T, "g") and @hasField(T, "b"), + .pointer => |p| p.size == .one and isColor(p.child), + else => false, + }; +} + +fn isNumber(comptime T: type) bool { + return switch (@typeInfo(T)) { + .int, .float, .comptime_int, .comptime_float => true, + else => false, + }; +} + +pub const Point = struct { x: f32 = 0, y: f32 = 0 }; + +/// The type to build results in for inputs shaped like `T`: `T` itself, or +/// for anonymous literals (whose fields are comptime-only) an f32 `Point` or +/// `abi.Rect`. +pub fn Out(comptime T: type) type { + if (@typeInfo(T) != .@"struct") return T; + for (@typeInfo(T).@"struct".fields) |field| switch (@typeInfo(field.type)) { + .comptime_int, .comptime_float => return if (isRect(T)) abi.Rect else Point, + else => {}, + }; + return T; +} + +/// Component `name` of a point- or rect-like value, as f32. +pub fn get(value: anytype, comptime name: []const u8) f32 { + const T = @TypeOf(value); + return switch (@typeInfo(T)) { + .vector, .array => num(value[comptime index(name)]), + .@"struct" => if (@hasField(T, name)) + num(@field(value, name)) + else if (comptime std.mem.eql(u8, name, "w") and @hasField(T, "width")) + num(value.width) + else if (comptime std.mem.eql(u8, name, "h") and @hasField(T, "height")) + num(value.height) + else + @compileError(@typeName(T) ++ " has no field '" ++ name ++ "'"), + .pointer => get(value.*, name), + else => @compileError("expected a point or rect, found " ++ @typeName(T)), + }; +} + +/// A value of type `T` with the given components, converted to `T`'s fields. +pub fn make(comptime T: type, x: f32, y: f32, w: f32, h: f32) T { + switch (@typeInfo(T)) { + .vector => |v| return if (v.len == 2) .{ cast(v.child, x), cast(v.child, y) } else .{ cast(v.child, x), cast(v.child, y), cast(v.child, w), cast(v.child, h) }, + .array => |a| return if (a.len == 2) .{ cast(a.child, x), cast(a.child, y) } else .{ cast(a.child, x), cast(a.child, y), cast(a.child, w), cast(a.child, h) }, + .@"struct" => { + var result: T = undefined; + inline for (@typeInfo(T).@"struct".fields) |field| { + @field(result, field.name) = if (comptime eql(field.name, "x")) + cast(field.type, x) + else if (comptime eql(field.name, "y")) + cast(field.type, y) + else if (comptime eql(field.name, "w") or eql(field.name, "width")) + cast(field.type, w) + else if (comptime eql(field.name, "h") or eql(field.name, "height")) + cast(field.type, h) + else if (field.defaultValue()) |default| + default + else + @compileError(@typeName(T) ++ "." ++ field.name ++ " has no default"); + } + return result; + }, + else => @compileError("cannot build a point or rect of type " ++ @typeName(T)), + } +} + +pub fn point(comptime T: type, x: f32, y: f32) T { + return make(T, x, y, 0, 0); +} + +pub fn rect(value: anytype) abi.Rect { + comptime if (!isRect(@TypeOf(value))) @compileError("expected a rect (x, y, w, h), found " ++ @typeName(@TypeOf(value))); + return .{ .x = get(value, "x"), .y = get(value, "y"), .w = get(value, "w"), .h = get(value, "h") }; +} + +pub fn contains(r: anytype, p: anytype) bool { + const x = get(p, "x"); + const y = get(p, "y"); + const rx = get(r, "x"); + const ry = get(r, "y"); + return x >= rx and y >= ry and x < rx + get(r, "w") and y < ry + get(r, "h"); +} + +/// `r` shrunk by `d` on every side, in `r`'s own type. +pub fn inset(r: anytype, d: f32) Out(@TypeOf(r)) { + return make(Out(@TypeOf(r)), get(r, "x") + d, get(r, "y") + d, get(r, "w") - 2 * d, get(r, "h") - 2 * d); +} + +/// `r` moved by the point `by`, in `r`'s own type. +pub fn offset(r: anytype, by: anytype) Out(@TypeOf(r)) { + const has_size = comptime isRect(@TypeOf(r)); + return make(Out(@TypeOf(r)), get(r, "x") + get(by, "x"), get(r, "y") + get(by, "y"), if (has_size) get(r, "w") else 0, if (has_size) get(r, "h") else 0); +} + +/// Anything with `r`, `g`, `b` (and optionally `a`) in 0..255 or 0..1 floats, +/// or a `0xRRGGBB` integer. +pub fn color(value: anytype) abi.Color { + const T = @TypeOf(value); + comptime if (!isColor(T)) @compileError("expected a color (r, g, b[, a]) or 0xRRGGBB, found " ++ @typeName(T)); + if (T == abi.Color) return value; + return switch (@typeInfo(T)) { + .int, .comptime_int => abi.Color.hex(@intCast(value)), + .@"struct" => .{ + .r = channel(value.r), + .g = channel(value.g), + .b = channel(value.b), + .a = if (@hasField(T, "a")) channel(value.a) else 255, + }, + .pointer => color(value.*), + else => @compileError("expected a color, found " ++ @typeName(T)), + }; +} + +fn channel(v: anytype) u8 { + return switch (@typeInfo(@TypeOf(v))) { + .float, .comptime_float => @intFromFloat(std.math.clamp(v, 0, 1) * 255 + 0.5), + else => @intCast(std.math.clamp(v, 0, 255)), + }; +} + +fn index(comptime name: []const u8) usize { + if (eql(name, "x")) return 0; + if (eql(name, "y")) return 1; + if (eql(name, "w")) return 2; + if (eql(name, "h")) return 3; + @compileError("no component " ++ name); +} + +fn num(v: anytype) f32 { + return switch (@typeInfo(@TypeOf(v))) { + .int, .comptime_int => @floatFromInt(v), + .float, .comptime_float => @floatCast(v), + else => @compileError("not a number: " ++ @typeName(@TypeOf(v))), + }; +} + +fn cast(comptime T: type, v: f32) T { + return switch (@typeInfo(T)) { + .int => @intFromFloat(@round(v)), + .float => @floatCast(v), + else => @compileError("not a number type: " ++ @typeName(T)), + }; +} + +fn eql(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +test "shapes are recognized by their data" { + try std.testing.expect(isPoint(struct { x: u8, y: u8 })); + try std.testing.expect(!isRect(struct { x: u8, y: u8 })); + try std.testing.expect(!isRect(struct { w: u8, h: u8 })); + try std.testing.expect(isRect(struct { x: f32, y: f32, width: f32, height: f32 })); + try std.testing.expect(isRect(@Vector(4, i16))); + try std.testing.expect(!isPoint([2][]const u8)); + try std.testing.expect(isColor(struct { r: f32, g: f32, b: f32 })); +} + +test "any shape with the right fields works and keeps its type" { + const P = struct { x: i32, y: i32, label: u8 = 7 }; + const R = struct { x: f64, y: f64, width: f64, height: f64 }; + try std.testing.expect(contains(R{ .x = 0, .y = 0, .width = 10, .height = 5 }, P{ .x = 3, .y = 4 })); + try std.testing.expect(!contains(@Vector(4, f32){ 0, 0, 10, 5 }, [2]f32{ 3, 6 })); + const moved = offset(P{ .x = 1, .y = 2 }, @Vector(2, f32){ 2, 3 }); + try std.testing.expectEqual(P{ .x = 3, .y = 5 }, moved); + try std.testing.expectEqual(abi.Rect{ .x = 1, .y = 1, .w = 8, .h = 3 }, rect(inset(R{ .x = 0, .y = 0, .width = 10, .height = 5 }, 1))); + try std.testing.expectEqual(abi.Color{ .r = 255, .g = 0, .b = 128 }, color(0xff0080)); + try std.testing.expectEqual(abi.Color{ .r = 255, .g = 128, .b = 0, .a = 255 }, color(.{ .r = 1.0, .g = 0.5, .b = 0.0 })); +} diff --git a/src/sketch/tween.zig b/src/sketch/tween.zig new file mode 100644 index 0000000..d3b53a1 --- /dev/null +++ b/src/sketch/tween.zig @@ -0,0 +1,133 @@ +//! Interpolation over plain data. `lerp` works field by field on any struct, +//! array, vector or number: numbers blend, and everything else (bools, enums, +//! unions) switches to `b` once `t` reaches 1. Pair it with an easing: +//! +//! camera = tween.lerp(from, to, tween.ease.inOutCubic(t)); +const std = @import("std"); + +pub fn lerp(a: anytype, b: @TypeOf(a), t: f32) @TypeOf(a) { + const T = @TypeOf(a); + return switch (@typeInfo(T)) { + .float => a + (b - a) * @as(T, @floatCast(t)), + .comptime_float => a + (b - a) * t, + .int => @intFromFloat(@round(@as(f64, @floatFromInt(a)) + (@as(f64, @floatFromInt(b)) - @as(f64, @floatFromInt(a))) * t)), + .vector => |v| if (@typeInfo(v.child) == .float) + a + (b - a) * @as(T, @splat(@floatCast(t))) + else blk: { + var out: T = undefined; + inline for (0..v.len) |i| out[i] = lerp(a[i], b[i], t); + break :blk out; + }, + .array => blk: { + var out: T = undefined; + for (&out, a, b) |*o, x, y| o.* = lerp(x, y, t); + break :blk out; + }, + .@"struct" => |s| blk: { + var out: T = undefined; + inline for (s.fields) |field| @field(out, field.name) = lerp(@field(a, field.name), @field(b, field.name), t); + break :blk out; + }, + else => if (t >= 1) b else a, + }; +} + +/// Like `lerp`, but only the fields named in `names` (a tuple of enum +/// literals, `.{ .x, .zoom }`) move; every other field stays as in `a`. +pub fn lerpFields(a: anytype, b: @TypeOf(a), t: f32, comptime names: anytype) @TypeOf(a) { + var out = a; + inline for (names) |name| { + const field = @tagName(name); + @field(out, field) = lerp(@field(a, field), @field(b, field), t); + } + return out; +} + +/// Moves the fields that `target` names toward its values: the literal is +/// the list, so `toward(sprite, .{ .x = 100, .alpha = 0 }, t)` animates just +/// those two, converting each value to the field's own type. +pub fn toward(a: anytype, target: anytype, t: f32) @TypeOf(a) { + const T = @TypeOf(a); + var out = a; + inline for (@typeInfo(@TypeOf(target)).@"struct".fields) |field| { + if (!@hasField(T, field.name)) @compileError(@typeName(T) ++ " has no field '" ++ field.name ++ "' to animate"); + const F = @FieldType(T, field.name); + const goal: F = switch (@typeInfo(F)) { + .@"struct" => toward(@field(a, field.name), @field(target, field.name), 1), + else => @field(target, field.name), + }; + @field(out, field.name) = lerp(@field(a, field.name), goal, t); + } + return out; +} + +/// Where `t` sits between `start` and `end`, clamped to 0..1. +pub fn progress(t: f32, start: f32, end: f32) f32 { + if (end <= start) return if (t >= end) 1 else 0; + return std.math.clamp((t - start) / (end - start), 0, 1); +} + +/// Easing curves, 0 to 1 over 0 to 1. Plain functions, so any `fn (f32) f32` +/// can stand in for one. +pub const ease = struct { + pub fn linear(t: f32) f32 { + return t; + } + pub fn inQuad(t: f32) f32 { + return t * t; + } + pub fn outQuad(t: f32) f32 { + return 1 - (1 - t) * (1 - t); + } + pub fn inOutQuad(t: f32) f32 { + return if (t < 0.5) 2 * t * t else 1 - std.math.pow(f32, -2 * t + 2, 2) / 2; + } + pub fn inCubic(t: f32) f32 { + return t * t * t; + } + pub fn outCubic(t: f32) f32 { + return 1 - std.math.pow(f32, 1 - t, 3); + } + pub fn inOutCubic(t: f32) f32 { + return if (t < 0.5) 4 * t * t * t else 1 - std.math.pow(f32, -2 * t + 2, 3) / 2; + } + pub fn inOutSine(t: f32) f32 { + return -(@cos(std.math.pi * t) - 1) / 2; + } + pub fn outBack(t: f32) f32 { + const c1 = 1.70158; + const c3 = c1 + 1; + return 1 + c3 * std.math.pow(f32, t - 1, 3) + c1 * std.math.pow(f32, t - 1, 2); + } + pub fn outElastic(t: f32) f32 { + if (t <= 0 or t >= 1) return std.math.clamp(t, 0, 1); + return std.math.pow(f32, 2, -10 * t) * @sin((t * 10 - 0.75) * (2 * std.math.pi / 3.0)) + 1; + } + /// manim's default: smooth start and stop. + pub fn smooth(t: f32) f32 { + const s = std.math.clamp(t, 0, 1); + return s * s * s * (s * (s * 6 - 15) + 10); + } + /// Out and back again, for pulses. + pub fn thereAndBack(t: f32) f32 { + return smooth(if (t < 0.5) 2 * t else 2 * (1 - t)); + } +}; + +test "comptime field lists pick what animates" { + const Sprite = struct { x: f32 = 0, y: f32 = 0, alpha: f32 = 1, frame: u8 = 3, pos: struct { u: f32 = 0 } = .{} }; + const a: Sprite = .{}; + const b: Sprite = .{ .x = 10, .y = 10, .alpha = 0 }; + try std.testing.expectEqual(Sprite{ .x = 5, .y = 0, .alpha = 0.5 }, lerpFields(a, b, 0.5, .{ .x, .alpha })); + try std.testing.expectEqual(Sprite{ .x = 50, .alpha = 0.5, .frame = 3, .pos = .{ .u = 2 } }, toward(a, .{ .x = 100, .alpha = 0, .pos = .{ .u = 4 } }, 0.5)); +} + +test "lerp walks plain data field by field" { + const Camera = struct { x: f32, y: f32, zoom: f32 = 1, mode: enum { free, locked } = .free }; + const mid = lerp(Camera{ .x = 0, .y = 10 }, Camera{ .x = 10, .y = 20, .zoom = 3, .mode = .locked }, 0.5); + try std.testing.expectEqual(Camera{ .x = 5, .y = 15, .zoom = 2, .mode = .free }, mid); + try std.testing.expectEqual(@Vector(2, f32){ 1, 2 }, lerp(@Vector(2, f32){ 0, 0 }, .{ 2, 4 }, 0.5)); + try std.testing.expectEqual([2]i32{ 5, -5 }, lerp([2]i32{ 0, 0 }, .{ 10, -10 }, 0.5)); + try std.testing.expectEqual(@as(f32, 1), ease.smooth(1)); + try std.testing.expectEqual(@as(f32, 0.5), progress(1.5, 1, 2)); +} diff --git a/src/sketch/web.zig b/src/sketch/web.zig new file mode 100644 index 0000000..7246c0d --- /dev/null +++ b/src/sketch/web.zig @@ -0,0 +1,201 @@ +//! Runs a sketch in a browser. `web/host.js` forwards input and implements a +//! handful of drawing imports; state, `update` and `draw` are the same Zig as +//! on native. There is no console, timeline or persistence on the web. +const std = @import("std"); +const abi = @import("abi"); +const root = @import("root.zig"); + +const js = struct { + extern "host" fn log(ptr: [*]const u8, len: usize) void; + extern "host" fn loadImage(ptr: [*]const u8, len: usize) u32; + extern "host" fn imageWidth(image: u32) u32; + extern "host" fn imageHeight(image: u32) u32; + extern "host" fn newImage(w: u32, h: u32) u32; + extern "host" fn clock() f64; + 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 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; + extern "canvas" fn cursor(kind: u32) void; + extern "canvas" fn pixels(id: u32, w: u32, h: u32, ptr: [*]const u8, len: usize, premultiplied: u32) void; +}; + +/// Exports `App` for `web/host.js`: `sk_init`, `sk_event`, `sk_frame`, and +/// `sk_field` for tests to read state by path. +pub fn exportWeb(comptime App: type) void { + const D = Driver(App); + @export(&D.init, .{ .name = "sk_init" }); + @export(&D.event, .{ .name = "sk_event" }); + @export(&D.frame, .{ .name = "sk_frame" }); + @export(&D.buffer, .{ .name = "sk_buffer" }); + @export(&D.field, .{ .name = "sk_field" }); +} + +fn Driver(comptime App: type) type { + const G = root.Glue(App); + return struct { + var state: G.State = undefined; + var session: G.Session = undefined; + var events: [1024]abi.Event = undefined; + var event_count: usize = 0; + var input: abi.Input = .{}; + var commands: std.ArrayList(abi.Command) = .empty; + var arena: std.heap.ArenaAllocator = .init(std.heap.wasm_allocator); + var session_heap: std.heap.ArenaAllocator = .init(std.heap.wasm_allocator); + var last: u64 = 0; + var path: [256]u8 = undefined; + + fn context() abi.Context { + return .{ + .host = .{ .ctx = @ptrCast(&input), .vtable = &vtable }, + .input = &input, + .arena = arena.allocator(), + .gpa = session_heap.allocator(), + .commands = &commands, + }; + } + + fn init() callconv(.c) void { + G.defaults(.state, std.mem.asBytes(&state)); + G.defaults(.session, std.mem.asBytes(&session)); + input.width = G.description.width; + input.height = G.description.height; + js.canvas(G.description.width, G.description.height); + const ctx = context(); + G.init(&ctx, std.mem.asBytes(&state)); + } + + fn event(kind: u32, code: u32, x: f32, y: f32, value: u32) callconv(.c) void { + const k = std.enums.fromInt(abi.Event.Kind, kind) orelse return; + if (event_count == events.len) { + // Never leave a gesture armed when the queue overflows. + events[0] = .{ .kind = .cancel }; + event_count = 1; + } + events[event_count] = .{ .kind = k, .code = @intCast(code), .x = x, .y = y, .value = value }; + event_count += 1; + } + + fn frame(ms: f64) callconv(.c) void { + const now: u64 = @intFromFloat(@max(0, ms) * std.time.ns_per_ms); + const dt = if (last == 0) 0 else now -| last; + last = now; + if (event_count < events.len) { + events[event_count] = .{ .kind = .tick, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) }; + event_count += 1; + } + for (events[0..event_count]) |*e| { + e.time = now; + input.track(e.*); + } + _ = arena.reset(.retain_capacity); + commands = .empty; + input.now = now; + input.dt = dt; + input.frame += 1; + input.events = events[0..event_count]; + const ctx = context(); + G.update(&ctx, std.mem.asBytes(&state)); + input.events = &.{}; + event_count = 0; + G.draw(&ctx, std.mem.asBytes(&state), std.mem.asBytes(&session)); + js.clip(0, 0, 0, 0, 0); + for (commands.items) |command| submit(command); + } + + fn submit(command: abi.Command) void { + switch (command) { + .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(@intFromEnum(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), + .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| { + input.width = @floatFromInt(v.w); + input.height = @floatFromInt(v.h); + js.canvas(v.w, v.h); + }, + .cursor => |v| js.cursor(@intFromEnum(v)), + .pixels => |v| js.pixels(@intFromEnum(v.image), v.w, v.h, v.rgba.ptr, v.rgba.len, @intFromBool(v.premultiplied)), + // No sound or GPU passes on the web yet (Host.gpu says so); + // quitting a page means nothing. + .voice, .audio, .gpu, .quit => {}, + } + } + + fn buffer() callconv(.c) [*]u8 { + return &path; + } + + /// The state field at the path written into `sk_buffer`, as a number + /// (enums by value); NaN when there is no such scalar field. + 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]; + 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) { + .float => if (f.size == 4) @as(f32, @bitCast(@as(u32, @truncate(value)))) else @bitCast(value), + .int => blk: { + const shift: u6 = @intCast(64 - f.size * 8); + break :blk @floatFromInt(@as(i64, @bitCast(value << shift)) >> shift); + }, + .uint, .@"enum", .bool => @floatFromInt(value), + else => std.math.nan(f64), + }; + } + return std.math.nan(f64); + } + + const vtable: abi.Host.VTable = .{ + .log = log, + .loadImage = loadImage, + .decodeImage = unsupportedImage, + .newImage = newImage, + .freeImage = freeImage, + .gpu = gpu, + .imageSize = imageSize, + .loadSound = unsupportedSound, + .decodeSound = unsupportedSound, + .readFile = readFile, + .env = env, + .clock = clock, + }; + fn log(_: *anyopaque, message: []const u8) void { + js.log(message.ptr, message.len); + } + fn loadImage(_: *anyopaque, p: []const u8) abi.Image { + return @enumFromInt(js.loadImage(p.ptr, p.len)); + } + fn unsupportedImage(_: *anyopaque, _: []const u8) abi.Image { + return .none; + } + fn newImage(_: *anyopaque, w: u32, h: u32) abi.Image { + return @enumFromInt(js.newImage(w, h)); + } + fn freeImage(_: *anyopaque, _: abi.Image) void {} + fn gpu(_: *anyopaque) bool { + return false; + } + fn imageSize(_: *anyopaque, img: abi.Image) [2]u32 { + return .{ js.imageWidth(@intFromEnum(img)), js.imageHeight(@intFromEnum(img)) }; + } + fn unsupportedSound(_: *anyopaque, _: []const u8) abi.Audio { + return .none; + } + fn readFile(_: *anyopaque, _: []const u8) []const u8 { + return &.{}; + } + fn env(_: *anyopaque, _: []const u8) ?[]const u8 { + return null; + } + fn clock(_: *anyopaque) u64 { + return @intFromFloat(@max(js.clock(), 0) * std.time.ns_per_ms); + } + }; +} diff --git a/src/vector/Cpu.zig b/src/vector/Cpu.zig new file mode 100644 index 0000000..c17366f --- /dev/null +++ b/src/vector/Cpu.zig @@ -0,0 +1,185 @@ +//! The CPU backend: polygons into premultiplied RGBA8, with exact coverage. +//! +//! Each edge adds its signed area to a grid of cells (the font-rs method); a +//! running sum along a row is then the winding coverage of every pixel, so +//! the cost is proportional to the fill's bounding box. It runs anywhere, +//! 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 Drawing = @import("Drawing.zig"); +const Polygons = @import("Polygons.zig"); +const Paint = @import("Paint.zig"); +const Vec = geom.Vec; + +gpa: std.mem.Allocator, +width: u32, +height: u32, +/// Premultiplied RGBA, `width * 4` bytes per row. +pixels: []u8, +/// Signed-area cells, `width + 2` per row; zero between fills. +cells: []f32, + +pub fn init(gpa: std.mem.Allocator, width: u32, height: u32) !Cpu { + const pixels = try gpa.alloc(u8, @as(usize, width) * height * 4); + errdefer gpa.free(pixels); + const cells = try gpa.alloc(f32, (@as(usize, width) + 2) * (height + 1)); + @memset(cells, 0); + @memset(pixels, 0); + return .{ .gpa = gpa, .width = width, .height = height, .pixels = pixels, .cells = cells }; +} + +pub fn deinit(c: *Cpu) void { + c.gpa.free(c.pixels); + c.gpa.free(c.cells); +} + +pub fn clear(c: *Cpu, color: Drawing.Color) void { + const px = Paint.premultiply(color); + const word: [4]u8 = .{ toByte(px[0]), toByte(px[1]), toByte(px[2]), toByte(px[3]) }; + @memset(std.mem.bytesAsSlice([4]u8, c.pixels), word); +} + +pub fn fill(c: *Cpu, polys: *const Polygons, rule: Drawing.FillRule, paint: *const Paint, alpha: f32) void { + if (polys.empty() or alpha <= 0) return; + var extent: geom.Bounds = .{}; + var it = polys.iterator(); + while (it.next()) |pts| { + var prev = pts[pts.len - 1]; + for (pts) |p| { + c.edge(prev, p, &extent); + prev = p; + } + } + c.composite(extent, rule, paint, alpha); +} + +/// Adds one edge, in device pixels. +fn edge(c: *Cpu, p0: Vec, p1: Vec, extent: *geom.Bounds) void { + if (p0[1] == p1[1] or !std.math.isFinite(p0[0] + p0[1] + p1[0] + p1[1])) return; + const w: f32 = @floatFromInt(c.width); + const h: f32 = @floatFromInt(c.height); + const dir: f32 = if (p0[1] < p1[1]) 1 else -1; + const a = if (dir > 0) p0 else p1; + const b = if (dir > 0) p1 else p0; + if (b[1] <= 0 or a[1] >= h) return; + const dxdy = (b[0] - a[0]) / (b[1] - a[1]); + var x = a[0]; + var y0 = a[1]; + if (y0 < 0) { + x -= y0 * dxdy; + y0 = 0; + } + const y1 = @min(b[1], h); + extent.add(.{ @min(a[0], b[0]), y0 }); + extent.add(.{ @max(a[0], b[0]), y1 }); + const stride = c.width + 2; + var y: u32 = @intFromFloat(y0); + const y_end: u32 = @intFromFloat(@ceil(y1)); + while (y < y_end) : (y += 1) { + const fy: f32 = @floatFromInt(y); + const dy = @min(fy + 1, y1) - @max(fy, y0); + const xnext = x + dxdy * dy; + const d = dy * dir; + // Left of the canvas counts at its left edge and right of it is + // never drawn: clamping keeps every winding number exact. + const x0 = std.math.clamp(@min(x, xnext), 0, w); + const x1 = std.math.clamp(@max(x, xnext), 0, w); + const row = c.cells[@as(usize, y) * stride ..][0..stride]; + const x0f = @floor(x0); + const x0i: usize = @intFromFloat(x0f); + const x1c = @ceil(x1); + const x1i: usize = @intFromFloat(x1c); + if (x1i <= x0i + 1) { + const xm = 0.5 * (x0 + x1) - x0f; + row[x0i] += d - d * xm; + row[x0i + 1] += d * xm; + } else { + const s = 1 / (x1 - x0); + const fx0 = x0 - x0f; + const a0 = 0.5 * s * (1 - fx0) * (1 - fx0); + const fx1 = x1 - x1c + 1; + const am = 0.5 * s * fx1 * fx1; + row[x0i] += d * a0; + if (x1i == x0i + 2) { + row[x0i + 1] += d * (1 - a0 - am); + } else { + const a1 = s * (1.5 - fx0); + row[x0i + 1] += d * (a1 - a0); + for (x0i + 2..x1i - 1) |xi| row[xi] += d * s; + const a2 = a1 + @as(f32, @floatFromInt(x1i - x0i - 3)) * s; + row[x1i - 1] += d * (1 - a2 - am); + } + row[x1i] += d * am; + } + x = xnext; + } +} + +/// Pixels from the cells in `extent`, zeroing the cells again. +fn composite(c: *Cpu, extent: geom.Bounds, rule: Drawing.FillRule, paint: *const Paint, alpha: f32) void { + if (extent.empty()) return; + const w = c.width; + const fw: f32 = @floatFromInt(w); + const stride = w + 2; + const x_start: usize = @intFromFloat(std.math.clamp(@floor(extent.min[0]), 0, fw)); + const x_end: usize = @min(@as(usize, @intFromFloat(std.math.clamp(@floor(extent.max[0]), 0, fw))) + 2, stride); + const y_start: usize = @intFromFloat(@max(0, @floor(extent.min[1]))); + const y_end: usize = @min(@as(usize, @intFromFloat(@ceil(extent.max[1]))), c.height); + // Gradients sample a table: 256 steps is below 8-bit output precision. + var lut: [256]@Vector(4, f32) = undefined; + if (paint.kind != .solid) for (&lut, 0..) |*e, i| { + e.* = paint.stopColor(@as(f32, @floatFromInt(i)) / 255); + }; + for (y_start..y_end) |y| { + const row = c.cells[y * stride ..][0..stride]; + const out = c.pixels[y * w * 4 ..][0 .. w * 4]; + var acc: f32 = 0; + for (x_start..x_end) |x| { + acc += row[x]; + row[x] = 0; + if (x >= w) continue; + const cover = switch (rule) { + .nonzero => @min(@abs(acc), 1), + .evenodd => blk: { + const t = @mod(@abs(acc), 2); + break :blk if (t > 1) 2 - t else t; + }, + }; + const a = cover * alpha; + if (a < 1.0 / 512.0) continue; + const color = if (paint.kind == .solid) + paint.color + else + lut[@intFromFloat(paint.param(.{ @as(f32, @floatFromInt(x)) + 0.5, @as(f32, @floatFromInt(y)) + 0.5 }) * 255 + 0.5)]; + blend(out[x * 4 ..][0..4], color * @as(@Vector(4, f32), @splat(a))); + } + } +} + +fn toByte(v: f32) u8 { + return @intFromFloat(std.math.clamp(v * 255 + 0.5, 0, 255)); +} + +/// Source-over, premultiplied. +inline fn blend(dst: *[4]u8, src: @Vector(4, f32)) void { + const d: @Vector(4, f32) = .{ @floatFromInt(dst[0]), @floatFromInt(dst[1]), @floatFromInt(dst[2]), @floatFromInt(dst[3]) }; + const out = src * @as(@Vector(4, f32), @splat(255)) + d * @as(@Vector(4, f32), @splat(1 - src[3])); + inline for (0..4) |i| dst[i] = @intFromFloat(@min(out[i] + 0.5, 255)); +} + +test "a half-covered pixel is half covered, under both rules" { + var c: Cpu = try .init(std.testing.allocator, 4, 4); + defer c.deinit(); + var p: Polygons = .init(std.testing.allocator); + defer p.deinit(); + try p.points.appendSlice(std.testing.allocator, &.{ .{ 1, 1 }, .{ 2.5, 1 }, .{ 2.5, 3 }, .{ 1, 3 } }); + try p.contours.append(std.testing.allocator, 4); + const white: Paint = .solid(.{ 1, 1, 1, 1 }); + c.fill(&p, .nonzero, &white, 1); + try std.testing.expectEqual(@as(u8, 255), c.pixels[(1 * 4 + 1) * 4 + 3]); + try std.testing.expectEqual(@as(u8, 128), c.pixels[(1 * 4 + 2) * 4 + 3]); + try std.testing.expectEqual(@as(u8, 0), c.pixels[(0 * 4 + 1) * 4 + 3]); + // Cells are clean for the next fill. + for (c.cells) |cell| try std.testing.expectEqual(@as(f32, 0), cell); +} diff --git a/src/vector/Drawing.zig b/src/vector/Drawing.zig new file mode 100644 index 0000000..0a3b77b --- /dev/null +++ b/src/vector/Drawing.zig @@ -0,0 +1,195 @@ +//! A vector drawing as plain data: shapes made of subpaths made of cubics. +//! Parsers and generators build these; the rasterizer and animations only +//! read and recombine them. +const Drawing = @This(); +const std = @import("std"); +const geom = @import("geom.zig"); +const Vec = geom.Vec; +const Cubic = geom.Cubic; + +cubics: []const Cubic = &.{}, +subpaths: []const Subpath = &.{}, +shapes: []const Shape = &.{}, +gradients: []const Gradient = &.{}, +/// The user-space rectangle the drawing occupies (SVG `viewBox`). +view: geom.Rect = .{}, +/// Intended size in pixels (SVG `width`/`height`). +width: f32 = 0, +height: f32 = 0, + +pub const Subpath = struct { + first: u32, + count: u32, + closed: bool, +}; + +/// Straight (not premultiplied) RGBA in 0..1. +pub const Color = @Vector(4, f32); + +pub const Paint = union(enum) { + none, + color: Color, + /// Index into `gradients`. + gradient: u32, +}; + +pub const Cap = enum { butt, round, square }; +pub const Join = enum { miter, round, bevel }; +pub const FillRule = enum { nonzero, evenodd }; + +pub const Style = struct { + fill: Paint = .{ .color = .{ 0, 0, 0, 1 } }, + fill_rule: FillRule = .nonzero, + fill_opacity: f32 = 1, + stroke: Paint = .none, + stroke_width: f32 = 1, + stroke_opacity: f32 = 1, + cap: Cap = .butt, + join: Join = .miter, + miter_limit: f32 = 4, + dashes: [8]f32 = @splat(0), + dash_count: u8 = 0, + dash_offset: f32 = 0, + /// Applied to fill and stroke alike. + opacity: f32 = 1, +}; + +pub const Shape = struct { + first: u32, + count: u32, + /// From the shape's own coordinates to the drawing's user space. + transform: geom.Affine = .identity, + style: Style = .{}, + /// A convex quad in the drawing's user space outside of which nothing + /// shows (a symbol's viewport). + clip: ?[4]Vec = null, +}; + +pub const Gradient = struct { + kind: enum { linear, radial } = .linear, + /// Linear: start and end. Radial: center and focus. + p0: Vec = .{ 0, 0 }, + p1: Vec = .{ 1, 0 }, + radius: f32 = 0.5, + /// Coordinates are fractions of the shape's bounds, not user space. + bounding_box: bool = true, + transform: geom.Affine = .identity, + spread: enum { pad, reflect, repeat } = .pad, + stops: []const Stop = &.{}, + + pub const Stop = struct { offset: f32, color: Color }; +}; + +pub fn subpathsOf(d: Drawing, shape: Shape) []const Subpath { + return d.subpaths[shape.first..][0..shape.count]; +} + +pub fn cubicsOf(d: Drawing, subpath: Subpath) []const Cubic { + return d.cubics[subpath.first..][0..subpath.count]; +} + +/// Bounds of `shape` in its own coordinates (control points: a little loose). +pub fn shapeBounds(d: Drawing, shape: Shape) geom.Bounds { + var b: geom.Bounds = .{}; + for (d.subpathsOf(shape)) |sp| for (d.cubicsOf(sp)) |c| for (c) |p| b.add(p); + return b; +} + +/// Bounds of the whole drawing in user space. +pub fn bounds(d: Drawing) geom.Bounds { + var b: geom.Bounds = .{}; + for (d.shapes) |shape| for (d.subpathsOf(shape)) |sp| for (d.cubicsOf(sp)) |c| for (c) |p| b.add(shape.transform.apply(p)); + return b; +} + +/// Accumulates a drawing. Everything lands in one allocator (an arena, in +/// practice), so a drawing is freed all at once. +pub const Builder = struct { + gpa: std.mem.Allocator, + cubics: std.ArrayList(Cubic) = .empty, + subpaths: std.ArrayList(Subpath) = .empty, + shapes: std.ArrayList(Shape) = .empty, + gradients: std.ArrayList(Gradient) = .empty, + shape_start: u32 = 0, + subpath_start: u32 = 0, + + pub fn init(gpa: std.mem.Allocator) Builder { + return .{ .gpa = gpa }; + } + + pub fn cubic(b: *Builder, c: Cubic) !void { + try b.cubics.append(b.gpa, c); + } + pub fn lineTo(b: *Builder, from: Vec, to: Vec) !void { + try b.cubic(geom.line(from, to)); + } + /// Ends the current subpath, if it has any segments. + pub fn closeSubpath(b: *Builder, closed: bool) !void { + const count: u32 = @intCast(b.cubics.items.len - b.subpath_start); + if (count > 0) try b.subpaths.append(b.gpa, .{ .first = b.subpath_start, .count = count, .closed = closed }); + b.subpath_start = @intCast(b.cubics.items.len); + } + /// Ends the current shape, if it has any subpaths. + pub fn endShape(b: *Builder, transform: geom.Affine, style: Style) !void { + try b.closeSubpath(false); + const count: u32 = @intCast(b.subpaths.items.len - b.shape_start); + if (count > 0) try b.shapes.append(b.gpa, .{ .first = b.shape_start, .count = count, .transform = transform, .style = style }); + b.shape_start = @intCast(b.subpaths.items.len); + } + pub fn finish(b: *Builder, view: geom.Rect, width: f32, height: f32) !Drawing { + return .{ + .cubics = try b.cubics.toOwnedSlice(b.gpa), + .subpaths = try b.subpaths.toOwnedSlice(b.gpa), + .shapes = try b.shapes.toOwnedSlice(b.gpa), + .gradients = try b.gradients.toOwnedSlice(b.gpa), + .view = view, + .width = width, + .height = height, + }; + } + + // Primitive shapes, each a closed subpath of cubics. + + pub fn rect(b: *Builder, r: geom.Rect, radius: f32) !void { + const rr = @min(radius, @min(r.w, r.h) / 2); + if (rr <= 0) { + const p = [4]Vec{ .{ r.x, r.y }, .{ r.x + r.w, r.y }, .{ r.x + r.w, r.y + r.h }, .{ r.x, r.y + r.h } }; + for (0..4) |i| try b.lineTo(p[i], p[(i + 1) % 4]); + } else { + try b.roundedRect(r, rr, rr); + } + try b.closeSubpath(true); + } + pub fn roundedRect(b: *Builder, r: geom.Rect, rx: f32, ry: f32) !void { + const k = 0.5522847498; + const x0 = r.x; + const y0 = r.y; + const x1 = r.x + r.w; + const y1 = r.y + r.h; + try b.lineTo(.{ x0 + rx, y0 }, .{ x1 - rx, y0 }); + try b.cubic(.{ .{ x1 - rx, y0 }, .{ x1 - rx + rx * k, y0 }, .{ x1, y0 + ry - ry * k }, .{ x1, y0 + ry } }); + try b.lineTo(.{ x1, y0 + ry }, .{ x1, y1 - ry }); + try b.cubic(.{ .{ x1, y1 - ry }, .{ x1, y1 - ry + ry * k }, .{ x1 - rx + rx * k, y1 }, .{ x1 - rx, y1 } }); + try b.lineTo(.{ x1 - rx, y1 }, .{ x0 + rx, y1 }); + try b.cubic(.{ .{ x0 + rx, y1 }, .{ x0 + rx - rx * k, y1 }, .{ x0, y1 - ry + ry * k }, .{ x0, y1 - ry } }); + try b.lineTo(.{ x0, y1 - ry }, .{ x0, y0 + ry }); + try b.cubic(.{ .{ x0, y0 + ry }, .{ x0, y0 + ry - ry * k }, .{ x0 + rx - rx * k, y0 }, .{ x0 + rx, y0 } }); + } + pub fn ellipse(b: *Builder, center: Vec, rx: f32, ry: f32) !void { + const k = 0.5522847498; + const cx = center[0]; + const cy = center[1]; + // Clockwise from the right, like SVG's circle. + try b.cubic(.{ .{ cx + rx, cy }, .{ cx + rx, cy + ry * k }, .{ cx + rx * k, cy + ry }, .{ cx, cy + ry } }); + try b.cubic(.{ .{ cx, cy + ry }, .{ cx - rx * k, cy + ry }, .{ cx - rx, cy + ry * k }, .{ cx - rx, cy } }); + try b.cubic(.{ .{ cx - rx, cy }, .{ cx - rx, cy - ry * k }, .{ cx - rx * k, cy - ry }, .{ cx, cy - ry } }); + try b.cubic(.{ .{ cx, cy - ry }, .{ cx + rx * k, cy - ry }, .{ cx + rx, cy - ry * k }, .{ cx + rx, cy } }); + try b.closeSubpath(true); + } + pub fn polyline(b: *Builder, points: []const Vec, closed: bool) !void { + if (points.len < 2) return; + for (points[0 .. points.len - 1], points[1..]) |p, q| try b.lineTo(p, q); + if (closed and !@reduce(.And, points[0] == points[points.len - 1])) try b.lineTo(points[points.len - 1], points[0]); + try b.closeSubpath(closed); + } +}; diff --git a/src/vector/Gpu.zig b/src/vector/Gpu.zig new file mode 100644 index 0000000..a557537 --- /dev/null +++ b/src/vector/Gpu.zig @@ -0,0 +1,174 @@ +//! 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`. +const Gpu = @This(); +const std = @import("std"); +const abi = @import("abi"); +const geom = @import("geom.zig"); +const Drawing = @import("Drawing.zig"); +const Polygons = @import("Polygons.zig"); +const Paint = @import("Paint.zig"); +const layouts = @import("vector_layouts"); +const shaders = @import("vector_shaders"); + +pub const samples = 8; + +const vertex: abi.gpu.Shader = .{ .spirv = shaders.path_vert, .uniform_buffers = 1 }; +const stencil_only: abi.gpu.Shader = .{ .spirv = shaders.stencil_frag }; + +const pipelines = [_]abi.gpu.Pipeline{ + // 0: nonzero winding. + abi.gpu.pipeline(layouts.Vertex, .{ + .vertex = vertex, + .fragment = stencil_only, + .blend = .none, + .write_color = false, + .stencil = .{ .front = .{ .pass = .increment_and_wrap }, .back = .{ .pass = .decrement_and_wrap } }, + }), + // 1: even-odd. + abi.gpu.pipeline(layouts.Vertex, .{ + .vertex = vertex, + .fragment = stencil_only, + .blend = .none, + .write_color = false, + .stencil = .{ .front = .{ .pass = .invert }, .back = .{ .pass = .invert } }, + }), + // 2: cover. + abi.gpu.pipeline(layouts.Vertex, .{ + .vertex = vertex, + .fragment = .{ .spirv = shaders.cover_frag, .uniform_buffers = 1 }, + .stencil = .{ + .front = .{ .compare = .not_equal, .pass = .zero }, + .back = .{ .compare = .not_equal, .pass = .zero }, + }, + }), +}; + +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 = &.{}, + +pub fn begin(g: *Gpu, arena: std.mem.Allocator, clear: Drawing.Color) void { + g.arena = arena; + g.draws = .empty; + g.clear_color = Paint.premultiply(clear); + g.viewport = abi.gpu.uniform(arena, layouts.Viewport{ .size = .{ @floatFromInt(g.width), @floatFromInt(g.height) } }); +} + +pub fn fill(g: *Gpu, polys: *const Polygons, rule: Drawing.FillRule, paint: *const Paint, alpha: f32) void { + if (polys.empty() or alpha <= 0) return; + g.record(polys, rule, paint, alpha) catch {}; +} + +fn record(g: *Gpu, polys: *const Polygons, rule: Drawing.FillRule, paint: *const Paint, alpha: f32) !void { + // 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); + 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] }; + 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)), + }); +} + +/// `Paint` as the shader's uniform 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 = .{ + .color = paint.color, + .row0 = .{ m.a, m.c, m.e, @floatFromInt(@intFromEnum(paint.kind)) }, + .row1 = .{ m.b, m.d, m.f, @floatFromInt(@intFromEnum(paint.spread)) }, + .points = .{ paint.p0[0], paint.p0[1], paint.p1[0], paint.p1[1] }, + .extra = .{ paint.radius, alpha, 0, 0 }, + .offsets = @splat(@splat(0)), + .colors = @splat(@splat(0)), + }; + const stops = paint.stops; + const n = @min(stops.len, layouts.max_stops); + for (0..n) |i| { + const t = if (stops.len <= layouts.max_stops) stops[i].offset else @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(n - 1)); + const color = if (stops.len <= layouts.max_stops) stops[i].color else unpremultiply(paint.stopColor(t)); + out.offsets[i / 4][i % 4] = t; + out.colors[i] = color; + } + out.extra[2] = @floatFromInt(n); + return out; +} + +fn unpremultiply(c: @Vector(4, f32)) [4]f32 { + if (c[3] <= 0) return .{ 0, 0, 0, 0 }; + return .{ c[0] / c[3], c[1] / c[3], c[2] / c[3], c[3] }; +} + +/// The pass that draws everything recorded since `begin`. +pub fn pass(g: *const Gpu) abi.gpu.Pass { + return .{ + .image = g.image, + .width = g.width, + .height = g.height, + .samples = samples, + .stencil = true, + .clear = g.clear_color, + .pipelines = &pipelines, + .draws = g.draws.items, + }; +} + +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 = @enumFromInt(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]); +} diff --git a/src/vector/Paint.zig b/src/vector/Paint.zig new file mode 100644 index 0000000..fb838d0 --- /dev/null +++ b/src/vector/Paint.zig @@ -0,0 +1,110 @@ +//! A paint resolved for one fill: a premultiplied color, or a gradient with +//! the map from device pixels into its own space. The CPU backend samples it +//! here; the GPU backend uploads the same numbers to its fragment shader, +//! which mirrors `param` and `stopColor`. +const Paint = @This(); +const std = @import("std"); +const geom = @import("geom.zig"); +const Drawing = @import("Drawing.zig"); +const Vec = geom.Vec; + +pub const Kind = enum(u32) { solid, linear, radial }; +pub const Spread = enum(u32) { pad, reflect, repeat }; + +kind: Kind = .solid, +/// Premultiplied, for solid paints. +color: @Vector(4, f32) = .{ 0, 0, 0, 0 }, +/// Linear: start and end. Radial: center and focus. +p0: Vec = .{ 0, 0 }, +p1: Vec = .{ 0, 0 }, +radius: f32 = 0, +spread: Spread = .pad, +/// Device pixels to gradient space. +to_gradient: geom.Affine = .identity, +stops: []const Drawing.Gradient.Stop = &.{}, + +pub fn solid(color: Drawing.Color) Paint { + return .{ .color = premultiply(color) }; +} + +/// `paint` of `shape`, drawn with `m` from shape to device space. +pub fn of(d: Drawing, shape: Drawing.Shape, paint: Drawing.Paint, m: geom.Affine) Paint { + return switch (paint) { + .none => .{}, + .color => |c| solid(c), + .gradient => |index| blk: { + const g = d.gradients[index]; + var space = m; + if (g.bounding_box) { + const b = d.shapeBounds(shape).rect(); + space = space.mul(.translate(b.x, b.y)).mul(.scale(@max(b.w, 1e-6), @max(b.h, 1e-6))); + } + break :blk .{ + .kind = if (g.kind == .linear) .linear else .radial, + .p0 = g.p0, + .p1 = g.p1, + .radius = g.radius, + .spread = switch (g.spread) { + .pad => .pad, + .reflect => .reflect, + .repeat => .repeat, + }, + .to_gradient = space.mul(g.transform).invert(), + .stops = g.stops, + }; + }, + }; +} + +/// The gradient parameter at device point `q`, spread applied: 0..1. +pub fn param(p: *const Paint, q: Vec) f32 { + const g = p.to_gradient.apply(q); + var t: f32 = switch (p.kind) { + .solid => 0, + .linear => blk: { + const dir = p.p1 - p.p0; + const len2 = geom.dot(dir, dir); + break :blk if (len2 > 0) geom.dot(g - p.p0, dir) / len2 else 0; + }, + .radial => blk: { + // Where the ray from the focus through g meets the circle. + const dq = g - p.p1; + const cf = p.p1 - p.p0; + const a = geom.dot(dq, dq); + if (a <= 0) break :blk 0; + const b = geom.dot(dq, cf); + const c = geom.dot(cf, cf) - p.radius * p.radius; + const s = (-b + @sqrt(@max(b * b - a * c, 0))) / a; + break :blk if (s > 0) 1 / s else 1; + }, + }; + t = switch (p.spread) { + .pad => std.math.clamp(t, 0, 1), + .repeat => t - @floor(t), + .reflect => blk: { + const r = @mod(t, 2); + break :blk if (r > 1) 2 - r else r; + }, + }; + return t; +} + +/// The premultiplied color at gradient parameter `t`. +pub fn stopColor(p: *const Paint, t: f32) @Vector(4, f32) { + const stops = p.stops; + if (stops.len == 0) return .{ 0, 0, 0, 0 }; + if (t <= stops[0].offset) return premultiply(stops[0].color); + for (stops[0 .. stops.len - 1], stops[1..]) |a, b| { + if (t <= b.offset) { + const span = b.offset - a.offset; + const u = if (span > 0) (t - a.offset) / span else 1; + // Interpolate straight colors, as SVG does, then premultiply. + return premultiply(a.color + (b.color - a.color) * @as(Drawing.Color, @splat(u))); + } + } + return premultiply(stops[stops.len - 1].color); +} + +pub fn premultiply(c: Drawing.Color) @Vector(4, f32) { + return .{ c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3] }; +} diff --git a/src/vector/Polygons.zig b/src/vector/Polygons.zig new file mode 100644 index 0000000..c0ed335 --- /dev/null +++ b/src/vector/Polygons.zig @@ -0,0 +1,395 @@ +//! Closed polygons in device pixels: what a fill or a stroke becomes before +//! any backend sees it. Fills keep their contours as the path had them; +//! strokes become many small pieces (segment quads, joins, caps), all wound +//! the same way, so the nonzero rule unions them. +const Polygons = @This(); +const std = @import("std"); +const geom = @import("geom.zig"); +const Drawing = @import("Drawing.zig"); +const Vec = geom.Vec; +const Affine = geom.Affine; + +/// Device-space flattening tolerance, in pixels. +pub const tolerance = 0.2; + +gpa: std.mem.Allocator, +points: std.ArrayList(Vec) = .empty, +/// Point count of each contour, in order. +contours: std.ArrayList(u32) = .empty, +/// Scratch polylines. +line: std.ArrayList(Vec) = .empty, +dashed: std.ArrayList(Vec) = .empty, +clipped: std.ArrayList(Vec) = .empty, +clip_scratch: std.ArrayList(Vec) = .empty, +clip_counts: std.ArrayList(u32) = .empty, + +pub fn init(gpa: std.mem.Allocator) Polygons { + return .{ .gpa = gpa }; +} + +pub fn deinit(p: *Polygons) void { + p.points.deinit(p.gpa); + p.contours.deinit(p.gpa); + p.line.deinit(p.gpa); + p.dashed.deinit(p.gpa); + p.clipped.deinit(p.gpa); + p.clip_scratch.deinit(p.gpa); + p.clip_counts.deinit(p.gpa); +} + +/// Keeps only what lies inside the convex `quad` (device space), contour by +/// contour (Sutherland–Hodgman). Winding numbers inside the quad are +/// unchanged, so both fill rules still hold. +pub fn clipConvex(p: *Polygons, quad: [4]Vec) !void { + var area: f32 = 0; + for (quad, 0..) |q, i| area += geom.cross(q, quad[(i + 1) % 4]); + const sign: f32 = if (area >= 0) 1 else -1; + p.clipped.clearRetainingCapacity(); + p.clip_counts.clearRetainingCapacity(); + var it = p.iterator(); + while (it.next()) |pts| { + p.clip_scratch.clearRetainingCapacity(); + try p.clip_scratch.appendSlice(p.gpa, pts); + for (quad, 0..) |a, i| { + const b = quad[(i + 1) % 4]; + const edge = b - a; + const input = try p.gpa.dupe(Vec, p.clip_scratch.items); + defer p.gpa.free(input); + p.clip_scratch.clearRetainingCapacity(); + if (input.len == 0) break; + var prev = input[input.len - 1]; + var prev_in = sign * geom.cross(edge, prev - a) >= 0; + for (input) |cur| { + const cur_in = sign * geom.cross(edge, cur - a) >= 0; + if (cur_in != prev_in) { + const d0 = geom.cross(edge, prev - a); + const d1 = geom.cross(edge, cur - a); + try p.clip_scratch.append(p.gpa, geom.mix(prev, cur, d0 / (d0 - d1))); + } + if (cur_in) try p.clip_scratch.append(p.gpa, cur); + prev = cur; + prev_in = cur_in; + } + } + if (p.clip_scratch.items.len >= 3) { + try p.clipped.appendSlice(p.gpa, p.clip_scratch.items); + try p.clip_counts.append(p.gpa, @intCast(p.clip_scratch.items.len)); + } + } + p.points.clearRetainingCapacity(); + p.contours.clearRetainingCapacity(); + try p.points.appendSlice(p.gpa, p.clipped.items); + try p.contours.appendSlice(p.gpa, p.clip_counts.items); +} + +pub fn clear(p: *Polygons) void { + p.points.clearRetainingCapacity(); + p.contours.clearRetainingCapacity(); +} + +pub fn empty(p: *const Polygons) bool { + return p.contours.items.len == 0; +} + +pub fn bounds(p: *const Polygons) geom.Bounds { + var b: geom.Bounds = .{}; + for (p.points.items) |q| b.add(q); + return b; +} + +/// Iterates contours as point slices. +pub fn iterator(p: *const Polygons) Iterator { + return .{ .p = p }; +} + +pub const Iterator = struct { + p: *const Polygons, + contour: usize = 0, + start: usize = 0, + + pub fn next(it: *Iterator) ?[]const Vec { + if (it.contour == it.p.contours.items.len) return null; + const len = it.p.contours.items[it.contour]; + defer { + it.start += len; + it.contour += 1; + } + return it.p.points.items[it.start..][0..len]; + } +}; + +fn contour(p: *Polygons, pts: []const Vec) !void { + if (pts.len < 3) return; + try p.points.appendSlice(p.gpa, pts); + try p.contours.append(p.gpa, @intCast(pts.len)); +} + +/// A closed polygon wound positively (in device space) whatever its order, +/// so overlapping stroke pieces add up instead of cancelling. +fn piece(p: *Polygons, m: Affine, pts: []const Vec) !void { + var area: f32 = 0; + for (pts, 0..) |q, i| area += geom.cross(q, pts[(i + 1) % pts.len]); + if (m.determinant() < 0) area = -area; + const start = p.points.items.len; + for (0..pts.len) |k| try p.points.append(p.gpa, m.apply(if (area >= 0) pts[k] else pts[(pts.len - k) % pts.len])); + try p.contours.append(p.gpa, @intCast(p.points.items.len - start)); +} + +// --------------------------------------------------------------------------- +// Fills + +/// The subpaths of `shape` as contours, with `m` from shape to device space. +pub fn fill(p: *Polygons, d: Drawing, shape: Drawing.Shape, m: Affine) !void { + for (d.subpathsOf(shape)) |sp| { + p.line.clearRetainingCapacity(); + try flatten(p.gpa, &p.line, d.cubicsOf(sp), m, tolerance); + try p.contour(p.line.items); + } +} + +// --------------------------------------------------------------------------- +// Strokes + +pub const Stroke = struct { + width: f32, + cap: Drawing.Cap = .butt, + join: Drawing.Join = .miter, + miter_limit: f32 = 4, + dashes: []const f32 = &.{}, + dash_offset: f32 = 0, + /// The drawn fraction of the path, along its length (0..1). + trim: f32 = 1, + /// From the space the stroke is laid out in to pixels: the shape's own + /// space (width and dashes then follow its transform), or identity for a + /// fixed pixel width. + space: Affine, + + pub fn of(style: Drawing.Style, space: Affine) Stroke { + return .{ + .width = style.stroke_width, + .cap = style.cap, + .join = style.join, + .miter_limit = style.miter_limit, + .dash_offset = style.dash_offset, + .space = space, + }; + } +}; + +/// The stroke of `shape` as positively wound pieces; `m` takes the shape to +/// device space. +pub fn stroke(p: *Polygons, d: Drawing, shape: Drawing.Shape, m: Affine, st: Stroke) !void { + if (st.width <= 0) return; + const to_layout = st.space.invert().mul(m); + const layout_tolerance = tolerance / @max(st.space.scaleFactor(), 1e-6); + var budget = std.math.inf(f32); + if (st.trim < 1) { + var total: f32 = 0; + for (d.subpathsOf(shape)) |sp| { + p.line.clearRetainingCapacity(); + try flatten(p.gpa, &p.line, d.cubicsOf(sp), to_layout, layout_tolerance); + total += length(p.line.items); + } + budget = @max(st.trim, 0) * total; + if (budget <= 0) return; + } + for (d.subpathsOf(shape)) |sp| { + if (budget <= 0) break; + p.line.clearRetainingCapacity(); + try flatten(p.gpa, &p.line, d.cubicsOf(sp), to_layout, layout_tolerance); + var pts: []const Vec = p.line.items; + var closed = sp.closed; + const len = length(pts); + if (len > budget) { + pts = truncate(&p.line, budget); + closed = false; + } + budget -= len; + if (st.dashes.len > 0) try p.dash(pts, closed, st) else try p.polyline(pts, closed, st); + } +} + +fn dash(p: *Polygons, pts: []const Vec, closed: bool, st: Stroke) !void { + var period: f32 = 0; + for (st.dashes) |v| period += v; + if (period <= 0 or pts.len < 2) return p.polyline(pts, closed, st); + var index: usize = 0; + var left = @mod(st.dash_offset, period); + while (left >= st.dashes[index]) { + left -= st.dashes[index]; + index = (index + 1) % st.dashes.len; + } + var remaining = st.dashes[index] - left; + var on = index % 2 == 0; + p.dashed.clearRetainingCapacity(); + if (on) try p.dashed.append(p.gpa, pts[0]); + const segments = pts.len - 1 + @intFromBool(closed); + for (0..segments) |i| { + var a = pts[i]; + const b = pts[(i + 1) % pts.len]; + var seg = geom.length(b - a); + while (seg > remaining) { + const q = geom.mix(a, b, remaining / seg); + try p.dashed.append(p.gpa, q); + if (on) try p.polyline(p.dashed.items, false, st); + p.dashed.clearRetainingCapacity(); + if (!on) try p.dashed.append(p.gpa, q); + seg -= remaining; + a = q; + on = !on; + index = (index + 1) % st.dashes.len; + remaining = st.dashes[index]; + } + remaining -= seg; + if (on) try p.dashed.append(p.gpa, b); + } + if (on and p.dashed.items.len > 1) try p.polyline(p.dashed.items, false, st); +} + +fn polyline(p: *Polygons, pts: []const Vec, closed: bool, st: Stroke) !void { + const hw = st.width / 2; + if (pts.len == 0) return; + const m = st.space; + var moved = false; + for (pts[1..]) |q| if (geom.length(q - pts[0]) > 1e-6) { + moved = true; + break; + }; + // A lone point still shows with round or square caps. + if (!moved) return switch (st.cap) { + .round => p.circle(m, pts[0], hw), + .square => p.piece(m, &.{ pts[0] + Vec{ -hw, -hw }, pts[0] + Vec{ hw, -hw }, pts[0] + Vec{ hw, hw }, pts[0] + Vec{ -hw, hw } }), + .butt => {}, + }; + var first: ?struct { point: Vec, dir: Vec } = null; + var last_dir: Vec = undefined; + var last_point: Vec = undefined; + const count = pts.len - 1 + @intFromBool(closed); + for (0..count) |i| { + const a = pts[i]; + const b = pts[(i + 1) % pts.len]; + const delta = b - a; + if (geom.length(delta) < 1e-6) continue; + const dir = geom.normalize(delta); + const n = geom.perp(dir) * geom.splat(hw); + try p.piece(m, &.{ a + n, b + n, b - n, a - n }); + if (first == null) first = .{ .point = a, .dir = dir } else try p.join(m, a, last_dir, dir, hw, st); + last_dir = dir; + last_point = b; + } + const f = first orelse return; + if (closed) { + try p.join(m, f.point, last_dir, f.dir, hw, st); + } else { + try p.cap(m, f.point, -f.dir, hw, st.cap); + try p.cap(m, last_point, last_dir, hw, st.cap); + } +} + +fn join(p: *Polygons, m: Affine, v: Vec, d0: Vec, d1: Vec, hw: f32, st: Stroke) !void { + const turn = geom.cross(d0, d1); + if (@abs(turn) < 1e-6 and geom.dot(d0, d1) > 0) return; + if (st.join == .round) return p.circle(m, v, hw); + // Offsets on the outer side of the turn: `perp` is the left side, which + // is outside when the path turns right (positive cross in y-down space). + const side: f32 = if (turn > 0) 1 else -1; + const n0 = geom.perp(d0) * geom.splat(hw * side); + const n1 = geom.perp(d1) * geom.splat(hw * side); + if (st.join == .miter) { + // The tip lies along the bisector; SVG's limit bounds its length + // over the stroke width. + const bisector = geom.normalize(n0 + n1); + const cos_half = geom.dot(bisector, geom.normalize(n0)); + if (cos_half > 1e-6 and 1 / cos_half <= st.miter_limit) { + return p.piece(m, &.{ v, v + n0, v + bisector * geom.splat(hw / cos_half), v + n1 }); + } + } + try p.piece(m, &.{ v, v + n0, v + n1 }); +} + +fn cap(p: *Polygons, m: Affine, at: Vec, dir: Vec, hw: f32, kind: Drawing.Cap) !void { + switch (kind) { + .butt => {}, + .round => try p.circle(m, at, hw), + .square => { + const n = geom.perp(dir) * geom.splat(hw); + const out = dir * geom.splat(hw); + try p.piece(m, &.{ at + n, at + n + out, at - n + out, at - n }); + }, + } +} + +fn circle(p: *Polygons, m: Affine, center: Vec, r: f32) !void { + const device_r = @max(r * m.scaleFactor(), tolerance); + const steps: usize = @intFromFloat(std.math.clamp(@ceil(std.math.pi / std.math.acos(@max(1 - tolerance / device_r, -1))), 8, 128)); + var buf: [128]Vec = undefined; + for (0..steps) |i| { + const a = @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(steps)) * std.math.tau; + buf[i] = center + Vec{ @cos(a), @sin(a) } * geom.splat(r); + } + try p.piece(m, buf[0..steps]); +} + +// --------------------------------------------------------------------------- +// Polylines + +/// Cubics to a polyline, each transformed by `m`, within `tol`. +pub fn flatten(gpa: std.mem.Allocator, out: *std.ArrayList(Vec), cubics: []const geom.Cubic, m: Affine, tol: f32) !void { + for (cubics, 0..) |raw, i| { + const c: geom.Cubic = .{ m.apply(raw[0]), m.apply(raw[1]), m.apply(raw[2]), m.apply(raw[3]) }; + if (i == 0) try out.append(gpa, c[0]); + const n = geom.flattenCount(c, tol); + const step = 1 / @as(f32, @floatFromInt(n)); + for (1..n) |k| try out.append(gpa, geom.eval(c, @as(f32, @floatFromInt(k)) * step)); + try out.append(gpa, c[3]); + } +} + +pub fn length(pts: []const Vec) f32 { + if (pts.len < 2) return 0; + var total: f32 = 0; + for (pts[0 .. pts.len - 1], pts[1..]) |a, b| total += geom.length(b - a); + return total; +} + +/// Shortens the polyline in `list` to `len` and returns it. +fn truncate(list: *std.ArrayList(Vec), len: f32) []const Vec { + const pts = list.items; + var left = len; + for (pts[0 .. pts.len - 1], pts[1..], 1..) |a, b, i| { + const seg = geom.length(b - a); + if (seg >= left) { + pts[i] = geom.mix(a, b, if (seg > 0) left / seg else 0); + list.shrinkRetainingCapacity(i + 1); + return list.items; + } + left -= seg; + } + return pts; +} + +test "a square stroke is four quads and four miters, all wound one way" { + var p: Polygons = .init(std.testing.allocator); + defer p.deinit(); + var b: Drawing.Builder = .init(std.testing.allocator); + defer { + b.cubics.deinit(b.gpa); + b.subpaths.deinit(b.gpa); + b.shapes.deinit(b.gpa); + b.gradients.deinit(b.gpa); + } + try b.rect(.{ .w = 10, .h = 10 }, 0); + try b.endShape(.identity, .{}); + const d: Drawing = .{ .cubics = b.cubics.items, .subpaths = b.subpaths.items, .shapes = b.shapes.items }; + try p.stroke(d, d.shapes[0], .identity, .{ .width = 2, .space = .identity }); + try std.testing.expectEqual(@as(usize, 8), p.contours.items.len); + var it = p.iterator(); + while (it.next()) |pts| { + var area: f32 = 0; + for (pts, 0..) |q, i| area += geom.cross(q, pts[(i + 1) % pts.len]); + try std.testing.expect(area > 0); + } + const bb = p.bounds().rect(); + try std.testing.expectEqual(@as(f32, -1), bb.x); + try std.testing.expectEqual(@as(f32, 12), bb.w); +} diff --git a/src/vector/geom.zig b/src/vector/geom.zig new file mode 100644 index 0000000..b80c55a --- /dev/null +++ b/src/vector/geom.zig @@ -0,0 +1,239 @@ +//! 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 new file mode 100644 index 0000000..097e682 --- /dev/null +++ b/src/vector/layouts.zig @@ -0,0 +1,40 @@ +//! What the vector GPU backend hands its shaders. These Zig structs are the +//! only definition: the shaders include GLSL generated from them (see +//! `glsl.zig`). No imports, so the shader build can compile this alone. + +pub const max_stops = 32; + +/// A path point in device pixels. +pub const Vertex = extern struct { + position: [2]f32, + + pub const glsl = .vertex; +}; + +pub const Viewport = extern struct { + size: [2]f32, + pad: [2]f32 = .{ 0, 0 }, + + pub const glsl = .{ .uniform = .{ .set = 1, .instance = "viewport" } }; +}; + +/// A resolved `Paint`, as `cover.frag` reads it. +pub const Paint = extern struct { + /// Premultiplied solid color. + color: [4]f32, + /// Device pixels to gradient space: a, c, e; then the kind (0 solid, + /// 1 linear, 2 radial). + row0: [4]f32, + /// b, d, f; then the spread (0 pad, 1 reflect, 2 repeat). + row1: [4]f32, + /// p0 then p1. + points: [4]f32, + /// Radius, alpha, 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" } }; +}; diff --git a/src/vector/morph.zig b/src/vector/morph.zig new file mode 100644 index 0000000..319eccf --- /dev/null +++ b/src/vector/morph.zig @@ -0,0 +1,178 @@ +//! Drawings in between two drawings, as manim transforms them: shapes pair up +//! in order; each pair's subpaths, then each subpath's cubics, are made equal +//! in number by splitting the longest curves; then every control point and +//! 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 Drawing = @import("Drawing.zig"); +const Vec = geom.Vec; +const Cubic = geom.Cubic; + +/// The drawing `t` of the way from `a` (placed by `ma`) to `b` (placed by +/// `mb`), in the space both transforms map to. Allocated in `arena`. +pub fn between(arena: std.mem.Allocator, a: Drawing, ma: geom.Affine, b: Drawing, mb: geom.Affine, t: f32) !Drawing { + var out: Drawing.Builder = .init(arena); + const ca = center(a, ma); + const cb = center(b, mb); + const n = @max(a.shapes.len, b.shapes.len); + for (0..n) |i| { + const sa: ?Drawing.Shape = if (i < a.shapes.len) a.shapes[i] else null; + const sb: ?Drawing.Shape = if (i < b.shapes.len) b.shapes[i] else null; + // The missing side is the other side, shrunk to a point. + const pa = try placed(arena, a, sa, ma, sb, b, mb, cb); + const pb = try placed(arena, b, sb, mb, sa, a, ma, ca); + const count = @max(pa.len, pb.len); + for (0..count) |k| { + const from = try pad(arena, pa, k, if (pa.len > 0) lastPoint(pa) else ca); + const to = try pad(arena, pb, k, if (pb.len > 0) lastPoint(pb) else cb); + const aligned = try align2(arena, from.cubics, to.cubics); + for (aligned[0], aligned[1]) |x, y| { + var c: Cubic = undefined; + for (&c, x, y) |*p, u, v| p.* = geom.mix(u, v, t); + try out.cubic(c); + } + try out.closeSubpath(from.closed or to.closed); + } + const style_a = if (sa) |s| s.style else fade(sb.?.style); + const style_b = if (sb) |s| s.style else fade(sa.?.style); + try out.endShape(.identity, mixStyle(a, style_a, b, style_b, t)); + } + return out.finish(a.view, a.width, a.height); +} + +const Path = struct { cubics: []const Cubic, closed: bool }; + +/// The subpaths of `shape` in the shared space; for a missing shape, its +/// partner's subpaths collapsed onto `point`. +fn placed(arena: std.mem.Allocator, d: Drawing, shape: ?Drawing.Shape, m: geom.Affine, partner: ?Drawing.Shape, pd: Drawing, pm: geom.Affine, point: Vec) ![]Path { + const s = shape orelse { + const p = partner.?; + const subpaths = pd.subpathsOf(p); + const out = try arena.alloc(Path, subpaths.len); + for (out, subpaths) |*o, sp| { + const cubics = try arena.alloc(Cubic, pd.cubicsOf(sp).len); + @memset(cubics, .{ point, point, point, point }); + o.* = .{ .cubics = cubics, .closed = sp.closed }; + } + _ = pm; + return out; + }; + const subpaths = d.subpathsOf(s); + const full = m.mul(s.transform); + const out = try arena.alloc(Path, subpaths.len); + for (out, subpaths) |*o, sp| { + const src = d.cubicsOf(sp); + const cubics = try arena.alloc(Cubic, src.len); + for (cubics, src) |*dst, c| dst.* = .{ full.apply(c[0]), full.apply(c[1]), full.apply(c[2]), full.apply(c[3]) }; + o.* = .{ .cubics = cubics, .closed = sp.closed }; + } + return out; +} + +/// Subpath `k`, or a point-sized one where the list is shorter. +fn pad(arena: std.mem.Allocator, paths: []const Path, k: usize, point: Vec) !Path { + if (k < paths.len) return paths[k]; + const one = try arena.alloc(Cubic, 1); + one[0] = .{ point, point, point, point }; + return .{ .cubics = one, .closed = false }; +} + +fn lastPoint(paths: []const Path) Vec { + const last = paths[paths.len - 1].cubics; + return last[last.len - 1][3]; +} + +/// Both lists with the same number of cubics: the shorter one's longest +/// curves are split in half until they match. +fn align2(arena: std.mem.Allocator, a: []const Cubic, b: []const Cubic) ![2][]const Cubic { + if (a.len == b.len) return .{ a, b }; + if (a.len < b.len) return .{ try refine(arena, a, b.len), b }; + return .{ a, try refine(arena, b, a.len) }; +} + +fn refine(arena: std.mem.Allocator, cubics: []const Cubic, n: usize) ![]const Cubic { + var list: std.ArrayList(Cubic) = try .initCapacity(arena, n); + list.appendSliceAssumeCapacity(cubics); + while (list.items.len < n) { + var longest: usize = 0; + var best: f32 = -1; + for (list.items, 0..) |c, i| { + const len = geom.roughLength(c); + if (len > best) { + best = len; + longest = i; + } + } + const halves = geom.split(list.items[longest], 0.5); + list.items[longest] = halves[0]; + list.insertAssumeCapacity(longest + 1, halves[1]); + } + return list.items; +} + +fn center(d: Drawing, m: geom.Affine) Vec { + const b = d.bounds(); + return m.apply(if (b.empty()) d.view.center() else b.rect().center()); +} + +/// A style that draws nothing, for shapes appearing from or vanishing into +/// a point. +fn fade(s: Drawing.Style) Drawing.Style { + var out = s; + out.opacity = 0; + return out; +} + +/// Styles in between: numbers blend; solid colors blend; anything else +/// switches halfway. +fn mixStyle(a: Drawing, sa: Drawing.Style, b: Drawing, sb: Drawing.Style, t: f32) Drawing.Style { + var s = if (t < 0.5) sa else sb; + s.fill = mixPaint(a, sa.fill, b, sb.fill, t); + s.stroke = mixPaint(a, sa.stroke, b, sb.stroke, t); + s.stroke_width = std.math.lerp(sa.stroke_width, sb.stroke_width, t); + s.opacity = std.math.lerp(sa.opacity, sb.opacity, t); + s.fill_opacity = std.math.lerp(sa.fill_opacity, sb.fill_opacity, t); + s.stroke_opacity = std.math.lerp(sa.stroke_opacity, sb.stroke_opacity, t); + return s; +} + +fn mixPaint(a: Drawing, pa: Drawing.Paint, b: Drawing, pb: Drawing.Paint, t: f32) Drawing.Paint { + _ = a; + _ = b; + const ca = switch (pa) { + .color => |c| c, + .none => if (pb == .color) pb.color * Drawing.Color{ 1, 1, 1, 0 } else return pb, + .gradient => return if (t < 0.5) pa else pb, + }; + const cb = switch (pb) { + .color => |c| c, + .none => ca * Drawing.Color{ 1, 1, 1, 0 }, + .gradient => return if (t < 0.5) pa else pb, + }; + return .{ .color = ca + (cb - ca) * @as(Drawing.Color, @splat(t)) }; +} + +test "a square becomes a circle through aligned cubics" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var ba: Drawing.Builder = .init(arena.allocator()); + try ba.rect(.{ .x = -10, .y = -10, .w = 20, .h = 20 }, 0); + try ba.endShape(.identity, .{ .fill = .{ .color = .{ 1, 0, 0, 1 } } }); + const square = try ba.finish(.{}, 0, 0); + var bb: Drawing.Builder = .init(arena.allocator()); + try bb.ellipse(.{ 0, 0 }, 10, 10); + try bb.ellipse(.{ 30, 0 }, 5, 5); + try bb.endShape(.identity, .{ .fill = .{ .color = .{ 0, 0, 1, 1 } } }); + const circles = try bb.finish(.{}, 0, 0); + + const start = try between(arena.allocator(), square, .identity, circles, .identity, 0); + const end = try between(arena.allocator(), square, .identity, circles, .identity, 1); + const mid = try between(arena.allocator(), square, .identity, circles, .identity, 0.5); + try std.testing.expectEqual(@as(usize, 2), mid.subpaths.len); + try std.testing.expectEqual(mid.subpaths[0].count, mid.subpaths[1].count); + // The ends are the originals. + try std.testing.expectEqual(square.cubics[0][0], start.cubics[0][0]); + try std.testing.expectEqual(geom.vec(10, 0), end.cubics[0][0]); + try std.testing.expectEqual(Drawing.Color{ 0.5, 0, 0.5, 1 }, mid.shapes[0].style.fill.color); +} diff --git a/src/vector/root.zig b/src/vector/root.zig new file mode 100644 index 0000000..7556948 --- /dev/null +++ b/src/vector/root.zig @@ -0,0 +1,144 @@ +//! 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 +//! 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 Drawing = @import("Drawing.zig"); +pub const svg = @import("svg.zig"); +pub const Polygons = @import("Polygons.zig"); +pub const Paint = @import("Paint.zig"); +pub const Cpu = @import("Cpu.zig"); +pub const Gpu = @import("Gpu.zig"); +pub const layouts = @import("vector_layouts"); +pub const morph = @import("morph.zig"); + +pub const Backend = enum { cpu, gpu }; + +pub const Options = struct { + /// Multiplies everything the shape draws. + alpha: f32 = 1, + fill: bool = true, + stroke: bool = true, + /// Also outline the shape in its fill color, `width` device pixels wide + /// (manim's Write draws glyph borders before filling them). + outline: ?struct { width: f32, alpha: f32 = 1 } = null, + /// The drawn fraction of strokes and outlines, along their length. + trim: f32 = 1, +}; + +/// Draws drawings into an image of `width` x `height` pixels. `host` is a +/// `sketch.Host`; `f` a `sketch.Frame`. Both are duck-typed, so the library +/// depends on nothing but the ABI. +pub fn Renderer(comptime backend: Backend) type { + return struct { + const Self = @This(); + pub const kind = backend; + + target: switch (backend) { + .cpu => Cpu, + .gpu => Gpu, + }, + polys: Polygons, + image: abi.Image, + + pub fn init(gpa: std.mem.Allocator, host: anytype, w: u32, h: u32) !Self { + const image = host.newImage(w, h); + return .{ + .target = switch (backend) { + .cpu => try .init(gpa, w, h), + .gpu => .{ .width = w, .height = h, .image = image }, + }, + .polys = .init(gpa), + .image = image, + }; + } + + pub fn deinit(r: *Self, host: anytype) void { + if (backend == .cpu) r.target.deinit(); + r.polys.deinit(); + host.freeImage(r.image); + } + + pub fn width(r: *const Self) u32 { + return r.target.width; + } + pub fn height(r: *const Self) u32 { + return r.target.height; + } + + /// Starts a picture. `f.arena` holds what the GPU pass needs until + /// the frame is consumed. + pub fn begin(r: *Self, f: anytype, clear: Drawing.Color) void { + switch (backend) { + .cpu => r.target.clear(clear), + .gpu => r.target.begin(f.arena, clear), + } + } + + /// All shapes of `d`; `m` maps its user space to pixels. + pub fn draw(r: *Self, d: Drawing, m: geom.Affine, alpha: f32) !void { + for (d.shapes) |shape| try r.drawShape(d, shape, m, .{ .alpha = alpha }); + } + + pub fn drawShape(r: *Self, d: Drawing, shape: Drawing.Shape, user_to_device: geom.Affine, o: Options) !void { + const m = user_to_device.mul(shape.transform); + const s = shape.style; + const clip: ?[4]geom.Vec = if (shape.clip) |q| .{ user_to_device.apply(q[0]), user_to_device.apply(q[1]), user_to_device.apply(q[2]), user_to_device.apply(q[3]) } else null; + if (o.fill and s.fill != .none) { + r.polys.clear(); + try r.polys.fill(d, shape, m); + if (clip) |q| try r.polys.clipConvex(q); + r.fill(s.fill_rule, &Paint.of(d, shape, s.fill, m), o.alpha * s.opacity * s.fill_opacity); + } + if (o.stroke and s.stroke != .none and s.stroke_width > 0) { + var st: Polygons.Stroke = .of(s, m); + st.dashes = s.dashes[0..s.dash_count]; + st.trim = o.trim; + r.polys.clear(); + try r.polys.stroke(d, shape, m, st); + if (clip) |q| try r.polys.clipConvex(q); + r.fill(.nonzero, &Paint.of(d, shape, s.stroke, m), o.alpha * s.opacity * s.stroke_opacity); + } + if (o.outline) |outline| if (s.fill != .none) { + r.polys.clear(); + try r.polys.stroke(d, shape, m, .{ .width = outline.width, .cap = .round, .join = .round, .trim = o.trim, .space = .identity }); + r.fill(.nonzero, &Paint.of(d, shape, s.fill, m), o.alpha * s.opacity * outline.alpha); + }; + } + + /// Fills whatever is in `r.polys`. + pub fn fill(r: *Self, rule: Drawing.FillRule, paint: *const Paint, alpha: f32) void { + r.target.fill(&r.polys, rule, paint, alpha); + } + + /// Hands the picture to the host and draws it at `dst`. + 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()), + } + f.image(r.image, dst, .{}); + } + }; +} + +/// The transform placing a drawing's view box into `dst`, centered and +/// scaled to fit (SVG's default `xMidYMid meet`). +pub fn fit(d: Drawing, dst: geom.Rect) geom.Affine { + const v = d.view; + if (v.w <= 0 or v.h <= 0) return .translate(dst.x, dst.y); + const s = @min(dst.w / v.w, dst.h / v.h); + return geom.Affine.translate(dst.x + (dst.w - v.w * s) / 2, dst.y + (dst.h - v.h * s) / 2).mul(.scale(s, s)).mul(.translate(-v.x, -v.y)); +} + +test { + _ = morph; + _ = geom; + _ = svg; + _ = Polygons; + _ = Cpu; + _ = Gpu; +} diff --git a/src/vector/shaders/cover.frag b/src/vector/shaders/cover.frag new file mode 100644 index 0000000..a57a916 --- /dev/null +++ b/src/vector/shaders/cover.frag @@ -0,0 +1,65 @@ +#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/path.vert b/src/vector/shaders/path.vert new file mode 100644 index 0000000..dbca9f8 --- /dev/null +++ b/src/vector/shaders/path.vert @@ -0,0 +1,9 @@ +#version 450 +#extension GL_GOOGLE_include_directive : require +// Device pixels (y down) to normalized device coordinates (y up). +#include "Vertex.glsl" +#include "Viewport.glsl" + +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); +} diff --git a/src/vector/shaders/stencil.frag b/src/vector/shaders/stencil.frag new file mode 100644 index 0000000..caf85f4 --- /dev/null +++ b/src/vector/shaders/stencil.frag @@ -0,0 +1,7 @@ +#version 450 +// Stencil passes write no color; the pipeline masks it out anyway. +layout(location = 0) out vec4 color; + +void main() { + color = vec4(0.0); +} diff --git a/src/vector/svg.zig b/src/vector/svg.zig new file mode 100644 index 0000000..9c0ec53 --- /dev/null +++ b/src/vector/svg.zig @@ -0,0 +1,768 @@ +//! SVG to `Drawing`: the static subset that documents (Typst's output in +//! particular) are made of. Structure: `svg`, `g`, `defs`, `symbol`, `use`. +//! Shapes: `path` (every command, arcs included), `rect`, `circle`, +//! `ellipse`, `line`, `polyline`, `polygon`. Styling: presentation +//! attributes and `style="..."`, inherited as SVG specifies; solid colors, +//! linear and radial gradients; fill rules; stroke width, caps, joins, miter +//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. +//! +//! Not supported: text (Typst outlines it), filters, masks, clipping, +//! 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 Drawing = @import("Drawing.zig"); +const Vec = geom.Vec; +const Affine = geom.Affine; + +pub const Error = error{ InvalidSvg, OutOfMemory }; + +/// Parses `source` into a drawing allocated with `arena`. +pub fn parse(arena: std.mem.Allocator, source: []const u8) Error!Drawing { + var doc = try Document.parse(arena, source); + const root = doc.root orelse return error.InvalidSvg; + if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return error.InvalidSvg; + + var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = .{} }; + const n = doc.nodes.items[root]; + const w = doc.attr(n, "width"); + const h = doc.attr(n, "height"); + var view: geom.Rect = .{}; + if (doc.attr(n, "viewBox")) |vb| { + var nums = Numbers{ .text = vb }; + view = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 }; + } + var width = if (w) |v| lengthPx(v, view.w) else view.w; + var height = if (h) |v| lengthPx(v, view.h) else view.h; + if (view.w <= 0 or view.h <= 0) view = .{ .w = width, .h = height }; + if (width <= 0) width = view.w; + if (height <= 0) height = view.h; + p.view = view; + try p.children(root, .identity, .{}); + return p.b.finish(view, width, height); +} + +// --------------------------------------------------------------------------- +// A minimal XML reader: elements and attributes into flat arrays. + +const Attr = struct { name: []const u8, value: []const u8 }; +const Node = struct { + name: []const u8, + attrs: []const Attr, + first_child: ?u32 = null, + next_sibling: ?u32 = null, +}; + +const Document = struct { + nodes: std.ArrayList(Node) = .empty, + ids: std.StringHashMapUnmanaged(u32) = .empty, + root: ?u32 = null, + + fn attr(doc: *const Document, n: Node, name: []const u8) ?[]const u8 { + _ = doc; + for (n.attrs) |a| if (std.mem.eql(u8, a.name, name)) return a.value; + return null; + } + + fn parse(arena: std.mem.Allocator, s: []const u8) Error!Document { + var doc: Document = .{}; + // Open elements, and the last child appended to each. + var stack: std.ArrayList(struct { node: u32, last: ?u32 }) = .empty; + var i: usize = 0; + while (std.mem.indexOfScalarPos(u8, s, i, '<')) |lt| { + i = lt + 1; + if (std.mem.startsWith(u8, s[i..], "!--")) { + i = (std.mem.indexOfPos(u8, s, i, "-->") orelse return error.InvalidSvg) + 3; + } else if (std.mem.startsWith(u8, s[i..], "![CDATA[")) { + i = (std.mem.indexOfPos(u8, s, i, "]]>") orelse return error.InvalidSvg) + 3; + } else if (s.len > i and (s[i] == '?' or s[i] == '!')) { + i = (std.mem.indexOfScalarPos(u8, s, i, '>') orelse return error.InvalidSvg) + 1; + } else if (s.len > i and s[i] == '/') { + i = (std.mem.indexOfScalarPos(u8, s, i, '>') orelse return error.InvalidSvg) + 1; + _ = stack.pop() orelse return error.InvalidSvg; + } else { + const name_end = std.mem.indexOfAnyPos(u8, s, i, " \t\r\n/>") orelse return error.InvalidSvg; + const name = localName(s[i..name_end]); + i = name_end; + var attrs: std.ArrayList(Attr) = .empty; + var self_closing = false; + while (true) { + while (i < s.len and std.ascii.isWhitespace(s[i])) i += 1; + if (i >= s.len) return error.InvalidSvg; + if (s[i] == '>') { + i += 1; + break; + } + if (s[i] == '/') { + self_closing = true; + i = (std.mem.indexOfScalarPos(u8, s, i, '>') orelse return error.InvalidSvg) + 1; + break; + } + const eq = std.mem.indexOfScalarPos(u8, s, i, '=') orelse return error.InvalidSvg; + const attr_name = std.mem.trim(u8, s[i..eq], " \t\r\n"); + var q = eq + 1; + while (q < s.len and std.ascii.isWhitespace(s[q])) q += 1; + if (q >= s.len or (s[q] != '"' and s[q] != '\'')) return error.InvalidSvg; + const close = std.mem.indexOfScalarPos(u8, s, q + 1, s[q]) orelse return error.InvalidSvg; + try attrs.append(arena, .{ .name = attr_name, .value = try entities(arena, s[q + 1 .. close]) }); + i = close + 1; + } + const index: u32 = @intCast(doc.nodes.items.len); + try doc.nodes.append(arena, .{ .name = name, .attrs = attrs.items }); + for (attrs.items) |a| if (std.mem.eql(u8, a.name, "id")) try doc.ids.put(arena, a.value, index); + if (stack.items.len == 0) { + if (doc.root == null) doc.root = index; + } else { + const parent = &stack.items[stack.items.len - 1]; + if (parent.last) |last| doc.nodes.items[last].next_sibling = index else doc.nodes.items[parent.node].first_child = index; + parent.last = index; + } + if (!self_closing) try stack.append(arena, .{ .node = index, .last = null }); + } + } + return doc; + } +}; + +/// `svg:path` and `path` are the same element to us. +fn localName(qualified: []const u8) []const u8 { + return if (std.mem.indexOfScalar(u8, qualified, ':')) |colon| qualified[colon + 1 ..] else qualified; +} + +fn entities(arena: std.mem.Allocator, raw: []const u8) ![]const u8 { + if (std.mem.indexOfScalar(u8, raw, '&') == null) return raw; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < raw.len) { + if (raw[i] == '&') if (std.mem.indexOfScalarPos(u8, raw, i, ';')) |semi| { + const name = raw[i + 1 .. semi]; + const char: ?u21 = if (std.mem.eql(u8, name, "amp")) '&' else if (std.mem.eql(u8, name, "lt")) '<' else if (std.mem.eql(u8, name, "gt")) '>' else if (std.mem.eql(u8, name, "quot")) '"' else if (std.mem.eql(u8, name, "apos")) '\'' else if (name.len > 1 and name[0] == '#') + (if (name[1] == 'x') std.fmt.parseInt(u21, name[2..], 16) catch null else std.fmt.parseInt(u21, name[1..], 10) catch null) + else + null; + if (char) |ch| { + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(ch, &buf) catch 0; + try out.appendSlice(arena, buf[0..len]); + i = semi + 1; + continue; + } + }; + try out.append(arena, raw[i]); + i += 1; + } + return out.items; +} + +// --------------------------------------------------------------------------- +// Tree walk: inherited style and transforms, shapes into the builder. + +const Parser = struct { + doc: *Document, + b: Drawing.Builder, + arena: std.mem.Allocator, + /// The root viewport, which `100%` lengths refer to. + view: geom.Rect, + /// Gradient ids already converted, by index in the builder. + gradients: std.StringHashMapUnmanaged(u32) = .empty, + /// Guards against `use` cycles. + depth: u32 = 0, + + const Inherited = struct { + style: Drawing.Style = .{}, + color: Drawing.Color = .{ 0, 0, 0, 1 }, + /// The innermost viewport clip, in the drawing's user space. + clip: ?[4]Vec = null, + }; + + fn children(p: *Parser, index: u32, transform: Affine, inherited: Inherited) Error!void { + var child = p.doc.nodes.items[index].first_child; + while (child) |c| : (child = p.doc.nodes.items[c].next_sibling) try p.element(c, transform, inherited); + } + + fn element(p: *Parser, index: u32, parent_transform: Affine, parent: Inherited) Error!void { + const n = p.doc.nodes.items[index]; + const name = n.name; + const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "image", "foreignObject" }; + for (skip) |s| if (std.mem.eql(u8, name, s)) return; + if (p.depth > 64) return; + var inherited = parent; + try p.applyStyle(n, &inherited); + if (std.mem.eql(u8, p.doc.attr(n, "display") orelse "", "none")) return; + var transform = parent_transform; + if (p.doc.attr(n, "transform")) |t| transform = transform.mul(parseTransform(t)); + + if (std.mem.eql(u8, name, "g") or std.mem.eql(u8, name, "svg") or std.mem.eql(u8, name, "a") or std.mem.eql(u8, name, "switch")) { + if (std.mem.eql(u8, name, "svg")) transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); + return p.children(index, transform, inherited); + } + if (std.mem.eql(u8, name, "use")) { + const href = p.doc.attr(n, "href") orelse p.doc.attr(n, "xlink:href") orelse return; + if (href.len < 2 or href[0] != '#') return; + const target = p.doc.ids.get(href[1..]) orelse return; + transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); + p.depth += 1; + defer p.depth -= 1; + const t = p.doc.nodes.items[target]; + if (std.mem.eql(u8, t.name, "symbol")) { + var sym = inherited; + try p.applyStyle(t, &sym); + // A symbol is a new viewport: the use's size, or the whole + // canvas; its viewBox maps into it, and it clips unless its + // overflow is visible. + const w = if (p.doc.attr(n, "width")) |v| lengthPx(v, p.view.w) else p.view.w; + const h = if (p.doc.attr(n, "height")) |v| lengthPx(v, p.view.h) else p.view.h; + const overflow = p.doc.attr(t, "overflow") orelse "hidden"; + if (!std.mem.eql(u8, overflow, "visible") and !std.mem.eql(u8, overflow, "auto")) { + sym.clip = .{ transform.apply(.{ 0, 0 }), transform.apply(.{ w, 0 }), transform.apply(.{ w, h }), transform.apply(.{ 0, h }) }; + } + var inner = transform; + if (p.doc.attr(t, "viewBox")) |vb| { + var nums = Numbers{ .text = vb }; + const v: geom.Rect = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 }; + if (v.w > 0 and v.h > 0) { + const s = @min(w / v.w, h / v.h); + inner = inner.mul(.translate((w - v.w * s) / 2, (h - v.h * s) / 2)).mul(.scale(s, s)).mul(.translate(-v.x, -v.y)); + } + } + return p.children(target, inner, sym); + } + return p.element(target, transform, inherited); + } + + const b = &p.b; + if (std.mem.eql(u8, name, "path")) { + try pathData(b, p.arena, p.doc.attr(n, "d") orelse return); + } else if (std.mem.eql(u8, name, "rect")) { + const w = p.number(n, "width"); + const h = p.number(n, "height"); + if (w <= 0 or h <= 0) return; + var rx = p.doc.attr(n, "rx"); + var ry = p.doc.attr(n, "ry"); + if (rx == null) rx = ry; + if (ry == null) ry = rx; + const r: geom.Rect = .{ .x = p.number(n, "x"), .y = p.number(n, "y"), .w = w, .h = h }; + const rxv = @min(if (rx) |v| parseLength(v) else 0, w / 2); + const ryv = @min(if (ry) |v| parseLength(v) else 0, h / 2); + if (rxv > 0 and ryv > 0) { + try b.roundedRect(r, rxv, ryv); + try b.closeSubpath(true); + } else try b.rect(r, 0); + } else if (std.mem.eql(u8, name, "circle")) { + const r = p.number(n, "r"); + if (r <= 0) return; + try b.ellipse(.{ p.number(n, "cx"), p.number(n, "cy") }, r, r); + } else if (std.mem.eql(u8, name, "ellipse")) { + const rx = p.number(n, "rx"); + const ry = p.number(n, "ry"); + if (rx <= 0 or ry <= 0) return; + try b.ellipse(.{ p.number(n, "cx"), p.number(n, "cy") }, rx, ry); + } else if (std.mem.eql(u8, name, "line")) { + try b.lineTo(.{ p.number(n, "x1"), p.number(n, "y1") }, .{ p.number(n, "x2"), p.number(n, "y2") }); + try b.closeSubpath(false); + } else if (std.mem.eql(u8, name, "polyline") or std.mem.eql(u8, name, "polygon")) { + var points: std.ArrayList(Vec) = .empty; + var nums = Numbers{ .text = p.doc.attr(n, "points") orelse return }; + while (nums.next()) |x| try points.append(p.arena, .{ x, nums.next() orelse break }); + try b.polyline(points.items, std.mem.eql(u8, name, "polygon")); + } else return; + const before = b.shapes.items.len; + try b.endShape(transform, inherited.style); + if (b.shapes.items.len > before) b.shapes.items[before].clip = inherited.clip; + } + + fn number(p: *Parser, n: Node, name: []const u8) f32 { + return parseLength(p.doc.attr(n, name) orelse return 0); + } + + /// Presentation attributes, then `style="..."` declarations on top. + fn applyStyle(p: *Parser, n: Node, inherited: *Inherited) Error!void { + // `opacity` multiplies down the tree (see `property`). + for (n.attrs) |a| try p.property(a.name, a.value, inherited); + if (p.doc.attr(n, "style")) |css| { + var decls = std.mem.tokenizeScalar(u8, css, ';'); + while (decls.next()) |decl| { + const colon = std.mem.indexOfScalar(u8, decl, ':') orelse continue; + try p.property(std.mem.trim(u8, decl[0..colon], " \t\r\n"), std.mem.trim(u8, decl[colon + 1 ..], " \t\r\n"), inherited); + } + } + } + + fn property(p: *Parser, name: []const u8, raw: []const u8, inherited: *Inherited) Error!void { + const value = std.mem.trim(u8, raw, " \t\r\n"); + const s = &inherited.style; + const eql = std.mem.eql; + if (eql(u8, value, "inherit")) return; + if (eql(u8, name, "color")) { + if (parseColor(value, inherited.color)) |c| inherited.color = c; + } else if (eql(u8, name, "fill")) { + s.fill = try p.paint(value, inherited.color) orelse s.fill; + } else if (eql(u8, name, "stroke")) { + s.stroke = try p.paint(value, inherited.color) orelse s.stroke; + } else if (eql(u8, name, "fill-rule")) { + s.fill_rule = if (eql(u8, value, "evenodd")) .evenodd else .nonzero; + } else if (eql(u8, name, "fill-opacity")) { + s.fill_opacity = parseOpacity(value); + } else if (eql(u8, name, "stroke-opacity")) { + s.stroke_opacity = parseOpacity(value); + } else if (eql(u8, name, "opacity")) { + s.opacity *= parseOpacity(value); + } else if (eql(u8, name, "stroke-width")) { + s.stroke_width = parseLength(value); + } else if (eql(u8, name, "stroke-linecap")) { + s.cap = std.meta.stringToEnum(Drawing.Cap, value) orelse s.cap; + } else if (eql(u8, name, "stroke-linejoin")) { + s.join = if (eql(u8, value, "miter-clip") or eql(u8, value, "arcs")) .miter else std.meta.stringToEnum(Drawing.Join, value) orelse s.join; + } else if (eql(u8, name, "stroke-miterlimit")) { + s.miter_limit = @max(1, parseLength(value)); + } else if (eql(u8, name, "stroke-dasharray")) { + s.dash_count = 0; + if (!eql(u8, value, "none")) { + var nums = Numbers{ .text = value }; + var total: f32 = 0; + while (nums.next()) |d| { + if (s.dash_count == s.dashes.len or d < 0) break; + s.dashes[s.dash_count] = d; + s.dash_count += 1; + total += d; + } + if (total <= 0) s.dash_count = 0; + // An odd list repeats to make an even one. + if (s.dash_count % 2 == 1 and s.dash_count * 2 <= s.dashes.len) { + @memcpy(s.dashes[s.dash_count..][0..s.dash_count], s.dashes[0..s.dash_count]); + s.dash_count *= 2; + } + } + } else if (eql(u8, name, "stroke-dashoffset")) { + s.dash_offset = parseLength(value); + } + } + + fn paint(p: *Parser, value: []const u8, current: Drawing.Color) Error!?Drawing.Paint { + if (std.mem.eql(u8, value, "none")) return .none; + if (std.mem.startsWith(u8, value, "url(")) { + const close = std.mem.indexOfScalar(u8, value, ')') orelse return null; + const ref = std.mem.trim(u8, value[4..close], " '\""); + if (ref.len > 1 and ref[0] == '#') if (try p.gradient(ref[1..])) |g| return .{ .gradient = g }; + // A missing paint server falls back to what follows it, or none. + const fallback = std.mem.trim(u8, value[close + 1 ..], " "); + return if (fallback.len > 0) try p.paint(fallback, current) else .none; + } + return if (parseColor(value, current)) |c| .{ .color = c } else null; + } + + fn gradient(p: *Parser, id: []const u8) Error!?u32 { + if (p.gradients.get(id)) |g| return g; + const index = p.doc.ids.get(id) orelse return null; + const n = p.doc.nodes.items[index]; + const radial = std.mem.eql(u8, n.name, "radialGradient"); + if (!radial and !std.mem.eql(u8, n.name, "linearGradient")) return null; + var g: Drawing.Gradient = .{ .kind = if (radial) .radial else .linear }; + if (radial) { + g.p0 = .{ 0.5, 0.5 }; + g.p1 = .{ 0.5, 0.5 }; + } + // Attributes and stops come from the first element in the href chain + // that has them. + var chain: [8]Node = undefined; + var len: usize = 0; + var at: ?u32 = index; + while (at) |i| : (len += 1) { + if (len == chain.len) break; + chain[len] = p.doc.nodes.items[i]; + const href = p.doc.attr(chain[len], "href") orelse p.doc.attr(chain[len], "xlink:href") orelse ""; + at = if (href.len > 1 and href[0] == '#') p.doc.ids.get(href[1..]) else null; + } + const find = struct { + fn find(doc: *Document, nodes: []const Node, name: []const u8) ?[]const u8 { + for (nodes) |node| if (doc.attr(node, name)) |v| return v; + return null; + } + }.find; + const nodes = chain[0..len]; + if (find(p.doc, nodes, "gradientUnits")) |u| g.bounding_box = !std.mem.eql(u8, u, "userSpaceOnUse"); + if (find(p.doc, nodes, "gradientTransform")) |t| g.transform = parseTransform(t); + if (find(p.doc, nodes, "spreadMethod")) |s| g.spread = if (std.mem.eql(u8, s, "reflect")) .reflect else if (std.mem.eql(u8, s, "repeat")) .repeat else .pad; + const coord = struct { + fn coord(doc: *Document, ns: []const Node, name: []const u8, default: f32, bbox: bool) f32 { + const v = find(doc, ns, name) orelse return default; + const t = std.mem.trim(u8, v, " "); + if (bbox and t.len > 0 and t[t.len - 1] == '%') return (std.fmt.parseFloat(f32, t[0 .. t.len - 1]) catch 0) / 100; + return parseLength(t); + } + }.coord; + if (radial) { + const cx = coord(p.doc, nodes, "cx", 0.5, g.bounding_box); + const cy = coord(p.doc, nodes, "cy", 0.5, g.bounding_box); + g.p0 = .{ cx, cy }; + g.p1 = .{ coord(p.doc, nodes, "fx", cx, g.bounding_box), coord(p.doc, nodes, "fy", cy, g.bounding_box) }; + g.radius = coord(p.doc, nodes, "r", 0.5, g.bounding_box); + } else { + g.p0 = .{ coord(p.doc, nodes, "x1", 0, g.bounding_box), coord(p.doc, nodes, "y1", 0, g.bounding_box) }; + g.p1 = .{ coord(p.doc, nodes, "x2", 1, g.bounding_box), coord(p.doc, nodes, "y2", 0, g.bounding_box) }; + } + var stops: std.ArrayList(Drawing.Gradient.Stop) = .empty; + for (nodes) |node| { + var child = node.first_child; + while (child) |c| : (child = p.doc.nodes.items[c].next_sibling) { + const stop = p.doc.nodes.items[c]; + if (!std.mem.eql(u8, stop.name, "stop")) continue; + var color: Drawing.Color = .{ 0, 0, 0, 1 }; + var opacity: f32 = 1; + var offset: f32 = 0; + const apply = struct { + fn apply(name: []const u8, value: []const u8, col: *Drawing.Color, op: *f32, off: *f32) void { + const v = std.mem.trim(u8, value, " "); + if (std.mem.eql(u8, name, "stop-color")) { + if (parseColor(v, .{ 0, 0, 0, 1 })) |parsed| col.* = parsed; + } else if (std.mem.eql(u8, name, "stop-opacity")) { + op.* = parseOpacity(v); + } else if (std.mem.eql(u8, name, "offset")) { + off.* = parseOpacity(v); + } + } + }.apply; + for (stop.attrs) |a| apply(a.name, a.value, &color, &opacity, &offset); + if (p.doc.attr(stop, "style")) |css| { + var decls = std.mem.tokenizeScalar(u8, css, ';'); + while (decls.next()) |decl| { + const colon = std.mem.indexOfScalar(u8, decl, ':') orelse continue; + apply(std.mem.trim(u8, decl[0..colon], " "), decl[colon + 1 ..], &color, &opacity, &offset); + } + } + color[3] *= opacity; + // Offsets never go backwards. + if (stops.items.len > 0) offset = @max(offset, stops.items[stops.items.len - 1].offset); + try stops.append(p.arena, .{ .offset = std.math.clamp(offset, 0, 1), .color = color }); + } + if (stops.items.len > 0) break; + } + if (stops.items.len == 0) return null; + g.stops = stops.items; + const at_index: u32 = @intCast(p.b.gradients.items.len); + try p.b.gradients.append(p.arena, g); + try p.gradients.put(p.arena, id, at_index); + return at_index; + } +}; + +// --------------------------------------------------------------------------- +// Values + +/// Numbers separated by whitespace and/or commas, SVG style: "1-2" is two +/// numbers, ".5.5" too. +pub const Numbers = struct { + text: []const u8, + i: usize = 0, + + pub fn next(n: *Numbers) ?f32 { + n.skip(); + if (n.i >= n.text.len) return null; + const start = n.i; + var j = n.i; + if (j < n.text.len and (n.text[j] == '+' or n.text[j] == '-')) j += 1; + var dot = false; + while (j < n.text.len) : (j += 1) { + const ch = n.text[j]; + if (std.ascii.isDigit(ch)) continue; + if (ch == '.' and !dot) { + dot = true; + continue; + } + if ((ch == 'e' or ch == 'E') and j + 1 < n.text.len and (std.ascii.isDigit(n.text[j + 1]) or ((n.text[j + 1] == '-' or n.text[j + 1] == '+') and j + 2 < n.text.len and std.ascii.isDigit(n.text[j + 2])))) { + j += 2; + while (j < n.text.len and std.ascii.isDigit(n.text[j])) j += 1; + break; + } + break; + } + if (j == start) return null; + n.i = j; + return std.fmt.parseFloat(f32, n.text[start..j]) catch null; + } + /// A single `0`/`1` arc flag, which may be glued to what follows. + pub fn flag(n: *Numbers) ?bool { + n.skip(); + if (n.i >= n.text.len) return null; + const ch = n.text[n.i]; + if (ch != '0' and ch != '1') return null; + n.i += 1; + return ch == '1'; + } + fn skip(n: *Numbers) void { + while (n.i < n.text.len and (std.ascii.isWhitespace(n.text[n.i]) or n.text[n.i] == ',')) n.i += 1; + } +}; + +/// A length in user units: unitless and px as-is, other absolute units +/// converted at 96 dpi. Percentages and font units fall back to the number. +pub fn parseLength(raw: []const u8) f32 { + const v = std.mem.trim(u8, raw, " \t\r\n"); + var nums = Numbers{ .text = v }; + const n = nums.next() orelse return 0; + const unit = std.mem.trim(u8, v[nums.i..], " "); + const scale: f32 = if (std.mem.eql(u8, unit, "pt")) 4.0 / 3.0 else if (std.mem.eql(u8, unit, "pc")) 16 else if (std.mem.eql(u8, unit, "in")) 96 else if (std.mem.eql(u8, unit, "cm")) 96.0 / 2.54 else if (std.mem.eql(u8, unit, "mm")) 96.0 / 25.4 else if (std.mem.eql(u8, unit, "em")) 16 else 1; + return n * scale; +} + +/// Like `parseLength`, but a percentage of `reference`. +fn lengthPx(raw: []const u8, reference: f32) f32 { + const v = std.mem.trim(u8, raw, " "); + if (v.len > 0 and v[v.len - 1] == '%') return (std.fmt.parseFloat(f32, v[0 .. v.len - 1]) catch 100) / 100 * reference; + return parseLength(v); +} + +fn parseOpacity(raw: []const u8) f32 { + const v = std.mem.trim(u8, raw, " "); + if (v.len > 0 and v[v.len - 1] == '%') return std.math.clamp((std.fmt.parseFloat(f32, v[0 .. v.len - 1]) catch 100) / 100, 0, 1); + return std.math.clamp(std.fmt.parseFloat(f32, v) catch 1, 0, 1); +} + +pub fn parseTransform(text: []const u8) Affine { + var m: Affine = .identity; + var i: usize = 0; + while (std.mem.indexOfScalarPos(u8, text, i, '(')) |open| { + const name = std.mem.trim(u8, text[i..open], " \t\r\n,"); + const close = std.mem.indexOfScalarPos(u8, text, open, ')') orelse break; + var nums = Numbers{ .text = text[open + 1 .. close] }; + var v: [6]f32 = @splat(0); + var count: usize = 0; + while (nums.next()) |x| : (count += 1) { + if (count == v.len) break; + v[count] = x; + } + const deg = std.math.pi / 180.0; + const t: Affine = if (std.mem.eql(u8, name, "matrix") and count == 6) + .{ .a = v[0], .b = v[1], .c = v[2], .d = v[3], .e = v[4], .f = v[5] } + else if (std.mem.eql(u8, name, "translate")) + .translate(v[0], if (count > 1) v[1] else 0) + else if (std.mem.eql(u8, name, "scale")) + .scale(v[0], if (count > 1) v[1] else v[0]) + else if (std.mem.eql(u8, name, "rotate")) + Affine.translate(v[1], v[2]).mul(.rotate(v[0] * deg)).mul(.translate(-v[1], -v[2])) + else if (std.mem.eql(u8, name, "skewX")) + .skew(v[0] * deg, 0) + else if (std.mem.eql(u8, name, "skewY")) + .skew(0, v[0] * deg) + else + .identity; + m = m.mul(t); + i = close + 1; + } + return m; +} + +/// `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()` (numbers or +/// percentages), `currentColor`, `transparent` and the common named colors. +pub fn parseColor(raw: []const u8, current: Drawing.Color) ?Drawing.Color { + const v = std.mem.trim(u8, raw, " \t\r\n"); + if (v.len == 0) return null; + if (v[0] == '#') { + const hex = v[1..]; + const digit = struct { + fn d(ch: u8) ?f32 { + return @floatFromInt(std.fmt.charToDigit(ch, 16) catch return null); + } + }.d; + switch (hex.len) { + 3, 4 => { + var c: [4]f32 = .{ 0, 0, 0, 1 }; + for (hex, 0..) |ch, i| c[i] = (digit(ch) orelse return null) * 17 / 255; + return c; + }, + 6, 8 => { + var c: [4]f32 = .{ 0, 0, 0, 1 }; + for (0..hex.len / 2) |i| c[i] = ((digit(hex[2 * i]) orelse return null) * 16 + (digit(hex[2 * i + 1]) orelse return null)) / 255; + return c; + }, + else => return null, + } + } + if (std.ascii.startsWithIgnoreCase(v, "rgb")) { + const open = std.mem.indexOfScalar(u8, v, '(') orelse return null; + const close = std.mem.indexOfScalar(u8, v, ')') orelse return null; + var parts = std.mem.tokenizeAny(u8, v[open + 1 .. close], ", /"); + var c: [4]f32 = .{ 0, 0, 0, 1 }; + var i: usize = 0; + while (parts.next()) |part| : (i += 1) { + if (i == 4) break; + const pct = part[part.len - 1] == '%'; + const n = std.fmt.parseFloat(f32, if (pct) part[0 .. part.len - 1] else part) catch return null; + c[i] = std.math.clamp(if (i == 3) (if (pct) n / 100 else n) else if (pct) n / 100 else n / 255, 0, 1); + } + return c; + } + if (std.ascii.eqlIgnoreCase(v, "currentColor")) return current; + if (std.ascii.eqlIgnoreCase(v, "transparent")) return .{ 0, 0, 0, 0 }; + for (named) |entry| if (std.ascii.eqlIgnoreCase(v, entry[0])) { + const rgb: u24 = entry[1]; + return .{ @as(f32, @floatFromInt(rgb >> 16)) / 255, @as(f32, @floatFromInt((rgb >> 8) & 0xff)) / 255, @as(f32, @floatFromInt(rgb & 0xff)) / 255, 1 }; + }; + return null; +} + +const named = [_]struct { []const u8, u24 }{ + .{ "black", 0x000000 }, .{ "white", 0xffffff }, .{ "red", 0xff0000 }, .{ "lime", 0x00ff00 }, + .{ "green", 0x008000 }, .{ "blue", 0x0000ff }, .{ "yellow", 0xffff00 }, .{ "cyan", 0x00ffff }, + .{ "aqua", 0x00ffff }, .{ "magenta", 0xff00ff }, .{ "fuchsia", 0xff00ff }, .{ "gray", 0x808080 }, + .{ "grey", 0x808080 }, .{ "silver", 0xc0c0c0 }, .{ "maroon", 0x800000 }, .{ "olive", 0x808000 }, + .{ "navy", 0x000080 }, .{ "purple", 0x800080 }, .{ "teal", 0x008080 }, .{ "orange", 0xffa500 }, + .{ "pink", 0xffc0cb }, .{ "brown", 0xa52a2a }, .{ "gold", 0xffd700 }, .{ "indigo", 0x4b0082 }, + .{ "violet", 0xee82ee }, .{ "coral", 0xff7f50 }, .{ "salmon", 0xfa8072 }, .{ "tomato", 0xff6347 }, + .{ "orchid", 0xda70d6 }, .{ "crimson", 0xdc143c }, .{ "skyblue", 0x87ceeb }, .{ "steelblue", 0x4682b4 }, + .{ "darkgray", 0xa9a9a9 }, .{ "lightgray", 0xd3d3d3 }, .{ "darkgreen", 0x006400 }, .{ "darkblue", 0x00008b }, + .{ "darkred", 0x8b0000 }, .{ "lightblue", 0xadd8e6 }, .{ "turquoise", 0x40e0d0 }, .{ "khaki", 0xf0e68c }, +}; + +/// Path data into cubics: every command, absolute and relative, with +/// implicit repeats and the smooth-curve reflections. +pub fn pathData(b: *Drawing.Builder, gpa: std.mem.Allocator, d: []const u8) !void { + var nums = Numbers{ .text = d }; + var command: u8 = 0; + var current: Vec = .{ 0, 0 }; + var start: Vec = .{ 0, 0 }; + // Last control point, for S and T reflections. + var last_cubic: ?Vec = null; + var last_quad: ?Vec = null; + var arcs: std.ArrayList(geom.Cubic) = .empty; + while (true) { + nums.skip(); + if (nums.i >= d.len) break; + const ch = d[nums.i]; + if (std.ascii.isAlphabetic(ch) and ch != 'e' and ch != 'E') { + command = ch; + nums.i += 1; + if (ch == 'z' or ch == 'Z') { + if (@reduce(.Or, current != start)) try b.lineTo(current, start); + try b.closeSubpath(true); + current = start; + last_cubic = null; + last_quad = null; + continue; + } + } else if (command == 0) return; + const rel = std.ascii.isLower(command); + const base: Vec = if (rel) current else .{ 0, 0 }; + const cubic_before = last_cubic; + const quad_before = last_quad; + last_cubic = null; + last_quad = null; + switch (std.ascii.toUpper(command)) { + 'M' => { + const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + try b.closeSubpath(false); + current = p; + start = p; + // Further pairs are line-tos. + command = if (rel) 'l' else 'L'; + }, + 'L' => { + const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + try b.lineTo(current, p); + current = p; + }, + 'H' => { + const x = nums.next() orelse return; + const p: Vec = .{ if (rel) current[0] + x else x, current[1] }; + try b.lineTo(current, p); + current = p; + }, + 'V' => { + const y = nums.next() orelse return; + const p: Vec = .{ current[0], if (rel) current[1] + y else y }; + try b.lineTo(current, p); + current = p; + }, + 'C' => { + const c1 = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + const c2 = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + try b.cubic(.{ current, c1, c2, p }); + last_cubic = c2; + current = p; + }, + 'S' => { + const c1 = if (cubic_before) |c| current * geom.splat(2) - c else current; + const c2 = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + try b.cubic(.{ current, c1, c2, p }); + last_cubic = c2; + current = p; + }, + 'Q' => { + const c = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + try b.cubic(geom.quad(current, c, p)); + last_quad = c; + current = p; + }, + 'T' => { + const c = if (quad_before) |q| current * geom.splat(2) - q else current; + const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + try b.cubic(geom.quad(current, c, p)); + last_quad = c; + current = p; + }, + 'A' => { + const rx = nums.next() orelse return; + const ry = nums.next() orelse return; + const rotation = nums.next() orelse return; + const large = nums.flag() orelse return; + const sweep = nums.flag() orelse return; + const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; + arcs.clearRetainingCapacity(); + try geom.arc(&arcs, gpa, current, .{ rx, ry }, rotation, large, sweep, p); + for (arcs.items) |c| try b.cubic(c); + current = p; + }, + else => return, + } + } + try b.closeSubpath(false); +} + +test "typst-style use of symbols, transforms and inherited fill" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const d = try parse(arena.allocator(), + \\ + \\ + \\ + \\ + ); + try std.testing.expectEqual(@as(f32, 20), d.width); + try std.testing.expectEqual(@as(usize, 1), d.shapes.len); + const shape = d.shapes[0]; + try std.testing.expectEqual(Drawing.FillRule.evenodd, shape.style.fill_rule); + try std.testing.expectEqual(Drawing.Color{ 1, 0, 0, 1 }, shape.style.fill.color); + try std.testing.expectEqual(@as(usize, 4), d.cubicsOf(d.subpathsOf(shape)[0]).len); + const corner = shape.transform.apply(d.cubics[0][0]); + try std.testing.expectEqual(geom.vec(6, 7), corner); +} + +test "path data: implicit repeats, relative commands, smooth curves and arcs" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var b: Drawing.Builder = .init(arena.allocator()); + try pathData(&b, arena.allocator(), "M10-20l5 5 5-5h-1e1s1,2,3,4q1 1 2 0t2 0a5 5 0 1 0 10 0z"); + try std.testing.expectEqual(@as(usize, 1), b.subpaths.items.len); + try std.testing.expect(b.subpaths.items[0].closed); + const cubics = b.cubics.items; + try std.testing.expectEqual(geom.vec(15, -15), cubics[0][3]); + try std.testing.expectEqual(geom.vec(20, -20), cubics[1][3]); + try std.testing.expectEqual(geom.vec(10, -20), cubics[2][3]); + // The first S has no previous curve: its first control is the current point. + try std.testing.expectEqual(geom.vec(10, -20), cubics[3][1]); + try std.testing.expectEqual(geom.vec(13, -16), cubics[3][3]); + var nums = Numbers{ .text = "1.5.5-2e-1" }; + try std.testing.expectEqual(@as(f32, 1.5), nums.next().?); + try std.testing.expectEqual(@as(f32, 0.5), nums.next().?); + try std.testing.expectEqual(@as(f32, -0.2), nums.next().?); +} + +test "colors and lengths" { + try std.testing.expectEqual(Drawing.Color{ 1, 1, 1, 1 }, parseColor("#fff", .{ 0, 0, 0, 1 }).?); + try std.testing.expectEqual(Drawing.Color{ 0, 0.5, 1, 1 }, parseColor("rgb(0, 50%, 255)", .{ 0, 0, 0, 1 }).?); + try std.testing.expectEqual(@as(f32, 20), parseLength("15pt")); + try std.testing.expectEqual(@as(f32, 0.5), parseOpacity("50%")); +} diff --git a/test/counter_v1.zig b/test/counter_v1.zig new file mode 100644 index 0000000..28f7379 --- /dev/null +++ b/test/counter_v1.zig @@ -0,0 +1,24 @@ +//! Reload fixture, first build: counts clicks. +const sk = @import("sketch"); + +pub const name = "counter"; +pub const width = 320; +pub const height = 200; + +pub const State = struct { + clicks: u32 = 0, + label: enum(u8) { cold, warm } = .cold, + retired: f32 = 1, +}; + +pub fn update(state: *State, in: *const sk.Input) void { + for (in.events) |e| if (e.kind == .mouse_up) { + state.clicks += 1; + if (state.clicks >= 2) state.label = .warm; + }; +} + +pub fn draw(state: *const State, f: *sk.Frame) void { + f.clear(0x202830); + f.print(8, 8, 2, 0xffffff, "clicks {d}", .{state.clicks}); +} diff --git a/test/counter_v2.zig b/test/counter_v2.zig new file mode 100644 index 0000000..7771470 --- /dev/null +++ b/test/counter_v2.zig @@ -0,0 +1,23 @@ +//! Reload fixture, second build: a new field, one gone, the rest moved. +const sk = @import("sketch"); + +pub const name = "counter"; +pub const width = 320; +pub const height = 200; + +pub const State = struct { + streak: u16 = 7, + label: enum(u8) { cold, warm, hot } = .cold, + clicks: u32 = 0, +}; + +pub fn update(state: *State, in: *const sk.Input) void { + for (in.events) |e| if (e.kind == .mouse_up) { + state.clicks += 10; + }; +} + +pub fn draw(state: *const State, f: *sk.Frame) void { + f.clear(0x302820); + f.print(8, 8, 2, 0xffffff, "clicks {d} streak {d}", .{ state.clicks, state.streak }); +} diff --git a/test/readme.zig b/test/readme.zig new file mode 100644 index 0000000..70673db --- /dev/null +++ b/test/readme.zig @@ -0,0 +1,16 @@ +//! The example from README.md, compiled by `zig build test`. +const sk = @import("sketch"); + +pub const State = struct { x: f32 = 480, y: f32 = 300, hue: f32 = 0 }; + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.pressed(sk.Key.space)) s.hue += 30; + s.x += (in.mouse_x - s.x) * 0.1; + s.y += (in.mouse_y - s.y) * 0.1; +} + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(0x202020); + f.fill(.{ .x = s.x - 10, .y = s.y - 10, .w = 20, .h = 20 }, 0xff8040); + f.print(8, 8, 2, 0xffffff, "hue {d}", .{s.hue}); +} diff --git a/test/reload.script b/test/reload.script new file mode 100644 index 0000000..863ecc6 --- /dev/null +++ b/test/reload.script @@ -0,0 +1,18 @@ +# The counter sketch reloads with a changed layout and keeps its values. +click 10 10 +click 10 10 +expect clicks 2 +expect label warm +console snapshot 3 +console save +load {v2} +expect clicks 2 +expect label warm +expect streak 7 +click 10 10 +expect clicks 12 +# The snapshot was migrated with the live state. +console load 3 +expect clicks 2 +console set streak 9 +expect streak 9 diff --git a/tools/serve_web.py b/tools/serve_web.py new file mode 100644 index 0000000..fd5b811 --- /dev/null +++ b/tools/serve_web.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Serve only the built web directory on a LAN interface (no directory listing).""" +import argparse +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +class Handler(SimpleHTTPRequestHandler): + extensions_map = {**SimpleHTTPRequestHandler.extensions_map, '.wasm': 'application/wasm'} + + def list_directory(self, path): + self.send_error(404) + return None + + def end_headers(self): + self.send_header('Cache-Control', 'no-cache') + super().end_headers() + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1] / 'zig-out/web') + parser.add_argument('--port', type=int, default=8042) + args = parser.parse_args() + root = args.root.resolve() + if not (root / 'sketch.wasm').is_file() or not (root / 'index.html').is_file(): + parser.error('Build first with zig build web; root must contain sketch.wasm and index.html') + server = ThreadingHTTPServer(('0.0.0.0', args.port), partial(Handler, directory=str(root))) + print(f'Serving {root} on 0.0.0.0:{args.port}', flush=True) + server.serve_forever() + +if __name__ == '__main__': + main() diff --git a/web/host.js b/web/host.js new file mode 100644 index 0000000..9f92a75 --- /dev/null +++ b/web/host.js @@ -0,0 +1,167 @@ +// sketchbook web host: forwards input to the sketch and draws what it asks. +// It knows nothing about any particular sketch. +const canvas = document.querySelector('canvas'); +const status = document.querySelector('#status'); +const ctx = canvas.getContext('2d', {alpha: false}); +const decoder = new TextDecoder(); +const images = [null]; +const byPath = new Map(); +const loads = []; +let wasm, clipped = false, size = [960, 600]; + +const bytes = (ptr, len) => new Uint8Array(wasm.memory.buffer, ptr, len); +const string = (ptr, len) => decoder.decode(bytes(ptr, len)); +const rgba = (r, g, b, a) => `rgba(${r},${g},${b},${a / 255})`; +const Kind = {move: 1, down: 2, up: 3, wheel: 4, keyDown: 5, keyUp: 6, text: 7, cancel: 8}; + +function fit() { + const [w, h] = size; + canvas.style.width = `min(100vw, ${w / h * 100}vh)`; + canvas.style.height = `min(${h / w * 100}vw, 100vh)`; + const ratio = Math.min(window.devicePixelRatio || 1, 2); + const box = canvas.getBoundingClientRect(); + const pw = Math.round(box.width * ratio), ph = Math.round(box.height * ratio); + if (canvas.width !== pw || canvas.height !== ph) { canvas.width = pw; canvas.height = ph; clipped = false; } + if (clipped) { ctx.restore(); clipped = false; } + ctx.setTransform(canvas.width / w, 0, 0, canvas.height / h, 0, 0); + ctx.imageSmoothingEnabled = false; +} + +const imports = { + host: { + log(ptr, len) { console.log(string(ptr, len)); }, + loadImage(ptr, len) { + const path = string(ptr, len); + if (byPath.has(path)) return byPath.get(path); + const entry = {source: new Image(), w: 0, h: 0}; + loads.push(new Promise(resolve => { + entry.source.onload = () => { entry.w = entry.source.naturalWidth; entry.h = entry.source.naturalHeight; resolve(); }; + entry.source.onerror = () => { console.warn(`missing image ${path}`); entry.source = null; resolve(); }; + })); + entry.source.src = path; + images.push(entry); + byPath.set(path, images.length - 1); + return images.length - 1; + }, + clock: () => performance.now(), + imageWidth: id => images[id]?.w ?? 0, + imageHeight: id => images[id]?.h ?? 0, + newImage(w, h) { + const source = document.createElement('canvas'); + source.width = w; source.height = h; + images.push({source, w, h, ctx: source.getContext('2d')}); + return images.length - 1; + }, + }, + canvas: { + clear(r, g, b, a) { ctx.fillStyle = rgba(r, g, b, a); ctx.fillRect(0, 0, size[0], size[1]); }, + fill(x, y, w, h, r, g, b, a) { ctx.fillStyle = rgba(r, g, b, a); ctx.fillRect(x, y, w, h); }, + image(id, x, y, w, h, sx, sy, sw, sh, alpha) { + const entry = images[id]; + if (!entry?.source || (entry.source instanceof Image && !entry.w)) { ctx.fillStyle = '#6e1e46'; ctx.fillRect(x, y, w, h); return; } + ctx.globalAlpha = alpha / 255; + if (sw > 0) ctx.drawImage(entry.source, sx, sy, sw, sh, x, y, w, h); else ctx.drawImage(entry.source, x, y, w, h); + ctx.globalAlpha = 1; + }, + text(x, y, scale, ptr, len, r, g, b, a) { + ctx.fillStyle = rgba(r, g, b, a); + ctx.font = `${12 * scale}px monospace`; + ctx.textBaseline = 'top'; + // The native font is a fixed 8px cell; keep the same geometry. + for (const [i, ch] of Array.from(string(ptr, len)).entries()) ctx.fillText(ch, x + i * 8 * scale, y); + }, + clip(enabled, x, y, w, h) { + if (clipped) { ctx.restore(); clipped = false; } + if (enabled) { ctx.save(); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); clipped = true; } + }, + canvas(w, h) { if (size[0] !== w || size[1] !== h) { size = [w, h]; } fit(); }, + cursor(kind) { canvas.style.cursor = ['none', 'default', 'pointer'][kind] ?? 'default'; }, + pixels(id, w, h, ptr, len, premultiplied) { + const entry = images[id]; + if (!entry?.ctx || len < w * h * 4) return; + const data = new Uint8ClampedArray(wasm.memory.buffer.slice(ptr, ptr + w * h * 4)); + if (premultiplied) for (let i = 0; i < data.length; i += 4) { + const a = data[i + 3]; + if (a && a < 255) { data[i] = data[i] * 255 / a; data[i + 1] = data[i + 1] * 255 / a; data[i + 2] = data[i + 2] * 255 / a; } + } + entry.ctx.putImageData(new ImageData(data, w, h), 0, 0); + }, + }, +}; + +// DOM `code` to USB HID usage, the numbering recordings and sketches use. +const hid = code => { + if (/^Key[A-Z]$/.test(code)) return code.charCodeAt(3) - 61; + if (/^Digit[0-9]$/.test(code)) return code[5] === '0' ? 39 : code.charCodeAt(5) - 19; + return {Enter: 40, Escape: 41, Backspace: 42, Tab: 43, Space: 44, Minus: 45, Equal: 46, BracketLeft: 47, BracketRight: 48, + Backslash: 49, Semicolon: 51, Quote: 52, Backquote: 53, Comma: 54, Period: 55, Slash: 56, Home: 74, PageUp: 75, + Delete: 76, End: 77, PageDown: 78, ArrowRight: 79, ArrowLeft: 80, ArrowDown: 81, ArrowUp: 82, NumpadEnter: 88, + ControlLeft: 224, ShiftLeft: 225, AltLeft: 226, MetaLeft: 227, ControlRight: 228, ShiftRight: 229, AltRight: 230, MetaRight: 231}[code] ?? 0; +}; +const floatBits = f => new Uint32Array(new Float32Array([f]).buffer)[0]; + +try { + const response = await fetch('sketch.wasm'); + if (!response.ok) throw new Error('The sketch could not be loaded.'); + wasm = (await WebAssembly.instantiate(await response.arrayBuffer(), imports)).instance.exports; + wasm.sk_init(); + wasm.sk_frame(0); + await Promise.all(loads); + status.hidden = true; + + const send = (kind, x = 0, y = 0, code = 0, value = 0) => wasm.sk_event(kind, code, x, y, value); + const point = e => { + const r = canvas.getBoundingClientRect(); + return [(e.clientX - r.left) * size[0] / r.width, (e.clientY - r.top) * size[1] / r.height]; + }; + let pointer = null; + canvas.addEventListener('pointerdown', e => { + if (pointer !== null) return; + e.preventDefault(); + pointer = e.pointerId; canvas.setPointerCapture(pointer); + send(Kind.down, ...point(e), e.button + 1); + }); + canvas.addEventListener('pointermove', e => send(Kind.move, ...point(e))); + canvas.addEventListener('pointerup', e => { + if (e.pointerId !== pointer) return; + send(Kind.up, ...point(e), e.button + 1); + const id = pointer; pointer = null; + if (canvas.hasPointerCapture(id)) canvas.releasePointerCapture(id); + }); + const cancel = () => { pointer = null; send(Kind.cancel); }; + canvas.addEventListener('pointercancel', cancel); + canvas.addEventListener('lostpointercapture', () => { if (pointer !== null) cancel(); }); + canvas.addEventListener('pointerleave', () => { if (pointer === null) send(Kind.move, -1, -1); }); + canvas.addEventListener('wheel', e => { e.preventDefault(); send(Kind.wheel, ...point(e), 0, floatBits(-Math.sign(e.deltaY))); }, {passive: false}); + window.addEventListener('keydown', e => { + send(Kind.keyDown, 0, 0, hid(e.code), 0); + if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) send(Kind.text, 0, 0, 0, e.key.codePointAt(0)); + }); + window.addEventListener('keyup', e => send(Kind.keyUp, 0, 0, hid(e.code), 0)); + window.addEventListener('blur', cancel); + window.addEventListener('resize', fit); + document.addEventListener('visibilitychange', () => { if (document.hidden) cancel(); }); + + // Tests read state by field path, like the native probe. + window.sketch = { + field(path) { + const encoded = new TextEncoder().encode(path); + new Uint8Array(wasm.memory.buffer, wasm.sk_buffer(), encoded.length).set(encoded); + return wasm.sk_field(encoded.length); + }, + size: () => size, + }; + + const frame = ms => { + try { + wasm.sk_frame(ms); + requestAnimationFrame(frame); + } catch (error) { + status.textContent = 'The sketch stopped. Reload to start again.'; status.hidden = false; console.error(error); + } + }; + requestAnimationFrame(frame); +} catch (error) { + status.textContent = 'The sketch could not start. Reload to try again.'; + console.error(error); +} diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..4b55799 --- /dev/null +++ b/web/index.html @@ -0,0 +1,18 @@ + + + + +{title} + + + +
Loading…
+ + -- cgit v1.3