summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-30 21:34:41 -0300
committerGabriel Schneider <[email protected]>2026-11-12 13:22:02 -0300
commit2348776791e9dd17afeb12a06ba42a4a71917bcf (patch)
tree780c4b12b76c8b97a28408dd40944d65f159fdc7
parent590ba7b9b579b97e34b51ab7e3460ebc85713343 (diff)
downloadsketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.tar.gz
sketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.zip
sketchbook: a drawing layer on top, host fixes for replay and migration
-rw-r--r--README.md356
-rw-r--r--build.zig478
-rw-r--r--build.zig.zon2
-rw-r--r--examples/flock.zig56
-rw-r--r--examples/pen.zig43
-rw-r--r--src/abi.zig133
-rw-r--r--src/host/Console.zig26
-rw-r--r--src/host/Host.zig120
-rw-r--r--src/host/fields.zig137
-rw-r--r--src/host/gfx.zig475
-rw-r--r--src/host/gpu.zig74
-rw-r--r--src/host/gpu.zig.orig641
-rw-r--r--src/host/memory.zig482
-rw-r--r--src/host/overlay.zig13
-rw-r--r--src/host/probe.zig26
-rw-r--r--src/host/root.zig16
-rw-r--r--src/host/script.zig200
-rw-r--r--src/host/timeline.zig216
-rw-r--r--src/layout.zig147
-rw-r--r--src/math/noise.zig157
-rw-r--r--src/math/root.zig (renamed from src/vector/geom.zig)102
-rw-r--r--src/sketch/clock.zig127
-rw-r--r--src/sketch/derived.zig56
-rw-r--r--src/sketch/draw.zig1024
-rw-r--r--src/sketch/list.zig109
-rw-r--r--src/sketch/root.zig102
-rw-r--r--src/sketch/web.zig46
-rw-r--r--src/vector/Cpu.zig2
-rw-r--r--src/vector/Drawing.zig2
-rw-r--r--src/vector/Gpu.zig381
-rw-r--r--src/vector/Paint.zig2
-rw-r--r--src/vector/Polygons.zig59
-rw-r--r--src/vector/layouts.zig22
-rw-r--r--src/vector/morph.zig2
-rw-r--r--src/vector/root.zig15
-rw-r--r--src/vector/shaders/paint.frag (renamed from src/vector/shaders/cover.frag)14
-rw-r--r--src/vector/shaders/paint.vert15
-rw-r--r--src/vector/svg.zig2
-rw-r--r--test/fixtures/drat-meout-v1.state-fixturebin0 -> 229376 bytes
-rw-r--r--test/reload.script17
-rw-r--r--test/render.script43
-rw-r--r--test/render.zig101
-rw-r--r--test/replay.script73
-rw-r--r--test/replay.zig48
-rw-r--r--test/shapes.script30
-rw-r--r--test/shapes.zig63
-rw-r--r--tools/chrome.mjs119
-rw-r--r--tools/reload_edit.zig49
-rw-r--r--tools/render_web.mjs13
-rw-r--r--tools/shapes_web.mjs41
-rw-r--r--tools/spirv_strip.zig33
-rw-r--r--tools/wasi_run.mjs9
-rw-r--r--web/host.js152
53 files changed, 6298 insertions, 373 deletions
diff --git a/README.md b/README.md
index ff9e538..e364c30 100644
--- a/README.md
+++ b/README.md
@@ -73,13 +73,24 @@ console) and one `tick` per frame carrying `dt`. Pointer and wheel events
carry the modifier keys held as they happened (`e.modifiers()`, `Key.Mod`
bits): read those, not `input.held`, for ctrl+wheel and the like, since a
trackpad's or a touch screen's pinch arrives as ctrl+wheel with no key
-events at all. Recorded ticks make
-time-driven sketches replay exactly. `input.started` is true on the first update after
+events at all. `update` is called once per frame, with that frame's events
+ending in its tick, live and replayed alike; in `update`, `input.now` and
+`input.dt` come from that tick (`dt` read back from the tick's f32
+seconds, so a replay sees the same bits). `input.mouse_x`/`buttons`/`held`
+follow the events fed so far. So time-driven and pointer-driven sketches
+replay exactly. Fields no event carries (`width`, `window_width`,
+`console`, `frame`) are not replayed: a sketch that reads them in `update`
+can replay differently. `input.started` is true on the first update after
the program starts, never after a reload: state is saved, so this is where
-to stop what should not resume on its own.
+to stop what should not resume on its own. In `draw`, `input.jumped` says
+State got where it is other than by `update` from what the last `draw`
+saw: the first frame, a seek, step, snapshot load, `set`, `reset`, play or
+record start, a sketch command, a reload. Anything `draw` piles up in
+Session (a trail in an offscreen image) is stale then; repaint it from
+State.
-`draw` gets a `Frame`: `clear`, `fill`, `image`, `text`, `print`, `clip`,
-`canvas`, `cursor`, `voice`, `audio`, `microphone`, `pixels`, `gpu`,
+`draw` gets a `Frame`: `clear`, `fill`, `shape`, `shapeColors`, `image`,
+`imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `audio`, `microphone`, `pixels`, `gpu`,
`compute`, `upload`, `download`, `openFile`, `run`, `quit`, plus the three allocators and
`f.host` (`loadImage`, `decodeImage`, `newImage`, `newBuffer`, `loadSound`,
`decodeSound`, `samples`, `readFile`, `env`, `log`). Commands may be built
@@ -102,12 +113,212 @@ not for pixels.
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:
+`Color`'s constants also go by name (`f.clear(.white)`); its functions
+need the type (`sk.Color.gray(220)`), since an `anytype` parameter gives a
+decl literal nothing to resolve against. 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`
+The drawing layer below is the exception: new, and typed (`sk.math.Vec`,
+`sk.Color`), so decl literals and completion work.
+
+## Drawing shapes
+
+Circles, lines and polygons are one host command, `Command.shape`: a
+region in one colour, given as points, subpath ends and triangle
+indices into the points. The web fills the subpaths (nonzero, one fill
+per outline and the holes after it); native draws the triangles with
+`SDL_RenderGeometry`. Both describe the same region, so translucent
+shapes blend alike, and shapes keep their order among `fill`, `image`,
+`text` and the clip. Both antialias: the canvas does, and native draws
+4x4 samples a pixel (with a GPU renderer: runs of consecutive shapes go
+into a supersampled layer, composited when another command comes) and
+averages them. Edges come out within a few levels of the web's, and a
+1 px line on a pixel row stays full black on both.
+
+`sk.draw` makes them, at two levels, neither with state of its own:
+
+```zig
+const ball: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 };
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ f.clear(0xffffff);
+ sk.draw.circle(f, s.position, 24, ball); // radius, not diameter
+ const pen = ball.transformed(.place(s.position, s.angle)); // push, translate, rotate
+ sk.draw.line(f, .{ 0, 0 }, .{ 24, 0 }, pen); // round ends
+ sk.draw.polygon(f, &.{ .{ 30, 0 }, .{ 26, -4 }, .{ 26, 4 } }, pen);
+}
+```
+
+A `Pen` is plain data (`fill: ?Color`, `stroke: ?Color`, `width`, `join`,
+`cap`, `xf: Affine`), so it can be a `const`, a State field, or a copy
+changed for one call. A null fill is `noFill()`, a null stroke
+`noStroke()`. `circle`, `line`, `polyline` (Processing's `beginShape()` /
+`endShape()`, open), `polygon` (`endShape(CLOSE)`), `rect` and `point` (a
+dot `width` across, Processing's `point`) tessellate into `f.scratch` and
+emit a shape for the fill and one for the stroke; out of memory, they log
+and drop it, as `emit` does. Joins are `.miter` (bevelled past 4
+half-widths), `.round` or `.bevel`, caps `.butt`, `.round` or `.square`;
+the defaults are Processing's (miter, round).
+
+```zig
+// A translucent road with round joins: each pixel blended once, joins included.
+const road: sk.draw.Pen = .{ .stroke = sk.Color.black.alpha(55), .width = 40, .join = .round };
+sk.draw.polyline(f, &s.path, road);
+```
+
+Underneath, an `sk.draw.Tessellation` is the shape as a value the caller
+owns: `fillCircle`, `strokeCircle`, `fillPolygon` (simple polygons,
+concave too), `strokePolygon`, `strokePolyline` (mitered, bevelled past 4
+half-widths), `strokeLine` (round ends), `fillRect`, `strokeRect`, and
+`strokePath(t, gpa, points, .{ .width, .join, .cap, .closed, .miter_limit
+}, xf)`, which the other strokes are, append to it with an allocator and
+an `Affine`. A round join is the circular segment beyond the bevel, a
+round cap the half disc beyond the end, so they stay disjoint like the
+rest; a square cap is a butt cap half a width further out. Emit it with `f.shape(&t, color)` or as
+`.{ .shape = ... }` yourself, put many shapes in one (1000 boids in two
+commands; a quadtree's 700 outlines and 2000 points in one), or hand
+`t.triangles(gpa)` to a GPU pass. Shapes of many
+colours share one command through `f.shapeColors(&t, colors)`, a colour
+per subpath (`t.ends`): fading particles batch too. A stroked circle is
+two subpaths, its outline and its hole, which take the same colour. `appendPoint`,
+`endSubpath` and `appendTriangle` build shapes of your own.
+
+What the functions guarantee: triangles that do not overlap, wound
+clockwise on screen (mirroring transforms included), covering exactly
+what the subpaths do. One case cannot keep it: a stroke that overlaps
+itself (a self-crossing polyline, or segments shorter than the stroke is
+wide at an acute turn) blends twice natively where it overlaps and once
+on the web. Circles get as many segments as keep them within a quarter
+pixel of round, after the transform. `tools/shapes_web.mjs` (`zig build
+test-web`) draws the same frame in headless Chrome and compares it with
+the native screenshot, pixel for pixel away from edges.
+
+## Offscreen images, blending, placed images
+
+Processing's canvas that is never cleared is an image you draw into.
+`host.newImage(w, h)` makes one, transparent; `f.target(img)` sends the 2D
+commands after it there (any of them: `sk.draw`, `fill`, `image`, `text`),
+`f.target(.none)` back to the canvas, and the image keeps what was drawn,
+frame to frame, until `f.image` shows it:
+
+```zig
+pub const Session = struct { trail: sk.Image = .none, drawn: u64 = 0 };
+
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ if (ss.trail == .none or f.in.jumped) {
+ if (ss.trail == .none) ss.trail = f.host.newImage(width, height);
+ ss.drawn = 0;
+ f.target(ss.trail);
+ f.clear(.white);
+ } else f.target(ss.trail);
+ while (ss.drawn < s.steps) : (ss.drawn += 1) sk.draw.circle(f, at(ss.drawn), 24, pen);
+ f.target(.none);
+ f.image(ss.trail, .{ .x = 0, .y = 0, .w = width, .h = height }, .{});
+}
+```
+
+The image is a cache in Session, never truth: after a seek or a load
+(`in.jumped`) it is repainted from State, so what a seek shows is what
+playing showed. Natively a target is supersampled whole and holds
+premultiplied colour, so it looks the same whether its steps were painted
+one a frame or all at once, and translucent edges are not darkened when
+it is drawn. A frame starts on the canvas.
+
+`f.blend(.add)` adds what follows (colour times alpha, and alpha: canvas
+`lighter`; natively a custom SDL blend, since SDL's `ADD` keeps a
+transparent target's alpha), `f.blend(.alpha)` goes back. It applies to
+`fill`, shapes and images; `clear` and `text` ignore it. Each frame starts
+with `.alpha`. There is no `multiply`: SDL's differs from the canvas's for
+translucent colours, and images have no fixed-function equivalent.
+
+`f.imageAt(img, xf, .{})` is `imageMode(CENTER)` under a transform: the
+image centred on `xf`'s origin, along its axes (`.translate(x, y)`,
+`.place(at, radians)`), at its own size or `.size`. Underneath,
+`Command.image.corners` places an image anywhere an affine can. A tint
+multiplies colour per channel and alpha as a whole, alike on both hosts
+(the web multiplies the pixels itself, cached per tint, as canvas
+compositing cannot where an image is translucent). Natively images sample
+nearest; the web antialiases a turned image's edges.
+
+## Math, time and lists
+
+`sk.math` is the geometry the `vector` module uses too (`vector.geom`):
+`Vec = @Vector(2, f32)`, so `+`, `-`, `*` and `+=` work on points as on a
+shader's `vec2`; free functions; `Affine` transforms; cubic Béziers; and
+noise. Processing's PVector, by name:
+
+| PVector | `sk.math` |
+| --- | --- |
+| `add`, `sub`, `mult` by a vector | `a + b`, `a - b`, `a * b` |
+| `mult(k)`, `div(k)` | `scale(a, k)`, `scale(a, 1 / k)` |
+| `mag()` | `length(a)` |
+| `normalize()` | `normalize(a)` (zero stays zero) |
+| `setMag(m)` | `withLength(a, m)` |
+| `limit(m)` | `clampLength(a, m)` |
+| `heading()` | `angle(a)` (radians; not in shader code, `atan2` uses tables) |
+| `PVector.fromAngle(r)` | `unit(r)` |
+| `dist(b)` | `distance(a, b)` |
+| `dot(b)`, `cross(b)` | `dot(a, b)`, `cross(a, b)` (the z of the 3D cross) |
+| `lerp(b, t)` | `mix(a, b, t)` |
+| `translate(p); rotate(r)` | `Affine.place(p, r)`, or `.translate(x, y).mul(.rotate(r))` |
+| `random(lo, hi)` | `uniform(rng, lo, hi)` |
+| `PVector.random2D()` | `randomUnit(rng)` |
+
+`sk.math.noise(seed, x, y, z)` is smooth noise in 0..1 like Processing's
+`noise()` (four octaves, each half the last): gradient noise on a hashed
+lattice, no table, so the seed can live in State. Unused axes are 0. Its
+spread is Processing's (a deviation of about 0.11, nearly all of it in
+0.1..0.9, so `noise → angle` turns all the way round), and integer
+inputs are not special: each octave is offset off the lattice. It gives
+the same bits natively and on wasm32 (a golden-value test runs on both).
+For random numbers keep a concrete `std.Random.Xoshiro256` in State (not
+`DefaultPrng`, an alias that may change) and pass `s.rng.random()`;
+`uniform(rng, lo, hi)` is `std.math.lerp(lo, hi, rng.float(f32))` by
+another name, and `std.Random` has the rest (`floatNorm`,
+`uintLessThan`).
+
+`sk.Clock` steps a simulation at a fixed rate from the recorded ticks:
+`clock: sk.Clock = .{ .hz = 60 }` in State, `for (0..s.clock.steps(in)) |_|
+step(s);` in `update`. It owes at most 8 steps per tick and drops the rest
+after a stall; `count` is the steps taken; `set clock.hz 30` is slow
+motion. A frame of N ticks steps exactly as N frames of one. It counts
+integer nanoseconds and allows an eighth of a step either way, so at the
+display's rate it steps once a frame, jitter and all: a 60 Hz frame is
+16 666 666 ns, a 60 Hz step 16 666 667, and 60 frames are 60 steps.
+
+`sk.List(T, capacity)` is a list for State: `buffer` and `len` (public, so
+`boids.buffer[3].pos[0]` works in the console), `slice`, `constSlice`,
+`appendBounded` (`error.OutOfMemory` when full), `orderedRemove`,
+`swapRemove`. Every method clamps `len` to the capacity, which matters
+after a reload that shrinks it. The default buffer is the element's own
+defaults, never `std.mem.zeroes` (an enum may have no 0).
+
+**Data that grows.** State is snapshotted, replayed and migrated, so it
+holds what `update` changes, at a size fixed in its type. Store is not
+snapshotted or replayed, so what is in it does not follow a seek. Three
+cases, by who needs the data:
+
+- `update` needs it: a `List` in State, sized for the worst case (the
+ quadtree's 4096 points, 32 KiB; flocking's 2048 boids).
+- Only `draw` needs it, and it follows from a few State fields: keep
+ those fields in State and the data in Session, rebuilt when they
+ change. A Koch curve's 65536 segments are a function of its
+ generation, one byte; an L-system's 89 000-character sentence of its
+ generation too. `sk.Derived(T)` is that: `if (ss.curve.stale(s.generation,
+ f.in)) rebuild(...)`; it is stale when the key changes (a click, a
+ seek, a step) and on the first frame after a reload, since new code
+ may derive it differently. A cheap derivation needs no cache at all:
+ the quadtree builds its tree in `f.scratch` every frame.
+- It is the user's work, not a function of State (a recording, a
+ document): Store.
+
+The timeline then needs nothing more: a seek changes the key like an
+update does (`sketches/noc`: `koch`, `lsystem`, `quadtree`).
+
**Sound scopes**, in the `scope` module (import `sb.modules.scope`): a
`scope.Scope` kept in Session takes samples with `push` and, once a frame,
`draw`s the views given rects for: the last seconds as a scrolling waveform
@@ -121,8 +332,9 @@ 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).
+backend describes one pass (8× MSAA, gradients in a shader): convex fills
+drawn directly, the rest stencil-then-cover, all batched into layers of
+non-overlapping fills, a few draws per layer whatever the shape count. Both are tested against resvg (see `sketches/vecanim` in the game repository).
**GPU work is data.** A sketch describes pipelines (shader code, vertex
layout, blend, stencil) and passes (`f.gpu(.{ .image, .pipelines, .draws,
@@ -164,31 +376,64 @@ stb_vorbis): WAV, FLAC and Ogg Vorbis, chosen by content.
- **State file.** `<name>.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.
+ name, and `sketchbook-probe` can print any sketch's state. Arrays and
+ vectors migrate element by element: the elements both layouts have, each
+ field by field, so an element type can gain a field and a capacity can
+ grow (new elements take their defaults) or shrink (the rest is dropped; a
+ count field such as `sk.List`'s `len` is kept, and `List` clamps it where
+ it is read). An array whose type is unchanged is copied whole. Files from
+ before element leaves (`SKETCH01`) are read and rewritten; a file that
+ is not a state file is refused, never truncated.
- **Store file.** `<name>.state.store` is a heap mapped at a fixed address
(`0x2000_0000_0000`, 64 GiB reserved), grown in place, locked to one
process. Power-of-two size classes with free lists in the file. Snapshots
and replays do not cover it (only `draw` and `command` change it).
- **Time travel.** Recordings, replay, seek and step work on any sketch,
- because they only need state bytes and events.
-- **Console and overlays.** `get`/`set <field path>`, snapshots, recordings and
+ because they only need state bytes and events. A recording is whole
+ frames; playback, `seek` and `step N` (frames) stop only between them.
+ Restoring a snapshot (play, seek, step, `load`) clears the pointer,
+ button and key state, and a recording begins with events that bring back
+ what was held when it started (a pointer move, a button or key down), so
+ a replay starts from the same input whatever the live pointer did since.
+ A recording carries a hash of the build that made it; `play` warns when
+ the running build differs (edited `update`, a new compiler), since the
+ replay may then diverge.
+- **Console and overlays.** `get`/`set <field path>` (`get` of a vector,
+ array or struct shows its values, in memory order), snapshots, recordings and
the memory and scope overlays come from the host; unknown lines go to the
- sketch.
+ sketch. Paths index arrays and vector lanes: `get pos[0]`,
+ `set boids.buffer[3].pos[1] 20`. `diff N` compares live state with
+ snapshot N leaf by leaf, so padding (a Debug `@Vector`'s spare lane)
+ never counts.
- **Scripts** (`--headless --fresh --script file`) drive the same routing and
frames as a player: `click`, `key`, `hold`/`release` (a key down until
- released, for modifiers), `wheel`, `type`, `console`, `expect field value`,
- `await field value` (frames until it holds, a minute at most),
- `expect-audio`, `screenshot`, `load`, `reload`, `await-reload`. A failed
+ released, for modifiers), `wheel`, `type`, `console`, `print field`
+ (to stderr, no frame: a vector, array or struct prints every value in
+ it, `{ 300, 200 }`), `expect field value`
+ (`expect pos[0] 250 ~0.5` within a tolerance; a failure prints what it
+ found),
+ `await field value [~tol]` (frames until it holds, a minute at most),
+ `expect-snapshot N` (live state equals snapshot N, leaf by leaf, printing
+ the first differences), `expect-log`/`expect-no-log text` (the console's
+ recent lines), `expect-audio`, `screenshot`,
+ `expect-same-screenshot a b [max [x y w h]]`,
+ `expect-different-screenshot a b [x y w h]`, `expect-pixel file x y r g b
+ a [tol]`, `load`, `reload`, `await-reload`. A failed
`expect`, or a console line that errors (a sketch command returning an
error included), fails the script. Headless always means offscreen, even
- with `SDL_VIDEO_DRIVER` set, and GPU work still runs, into a texture.
+ with `SDL_VIDEO_DRIVER` set, and GPU work still runs, into a texture. A
+ scripted `--fresh` run works on files of its own (`<state>.<pid>`),
+ renamed to the given `--state` at exit, so two builds running the same
+ script at once do not share them.
- **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.
`--profile-gpu` times every upload, dispatch and pass alone on an idle
GPU (SDL_GPU has no timestamp queries) and prints count, mean, worst and
per-frame time by `label` at exit.
- **Memory.** SDL allocations go through a leak-checking allocator; a leak
- fails the exit.
+ fails the exit. SDL's Vulkan backend leaked when `vkAllocateMemory`
+ failed and it fell back to another memory type (it happens with many
+ headless hosts at once); the build compiles that file with the fix.
## The web host
@@ -243,12 +488,45 @@ and returns plain `std.Build` objects:
| --- | --- |
| `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, built from the app's modules with every shader module swapped for its WGSL twin; tests can read its state by path with `sk_field` (numbers) and `sk_tag` (enum tag names) |
+| `app.addScriptExecutable()` | the same, built in `script_optimize` mode, as `e2e` plays scripts with |
+| `app.addWeb(.{ .assets = ... })` | the wasm module and a ready-to-serve directory, built from the app's modules with every shader module swapped for its WGSL twin; tests can read its state by path (indices too: `list[2].x`) with `sk_field` (numbers) and `sk_tag` (enum tag names) |
| `app.addServe(install)` | `miniserve` serving an installed web directory over https, on every interface, with a self-signed certificate made once by `openssl`: https makes the page a secure context on any device, which WebGPU and the microphone need. Its defaults are environment variables, so miniserve options after `--` replace them |
| `app.addRun(lib, .{})` | the generic host running the installed library |
| `app.addScript(exe_or_lib, file, .{})` | a headless, fresh-state scripted run, of the executable or of the library through the host (so the script can `reload` it) |
| `app.addProbe(state)` | the probe on a state file |
| `app.addTest(.{})` | tests with the app importable as `app` |
+| `app.addReloadCheck(.{ .script, .edits })` | a check that the app hot-reloads with State kept (below) |
+
+`sketchbook.init(b, .{ ..., .script_optimize = .ReleaseSafe })` builds
+the executables `e2e` plays scripts with in another mode than the rest,
+for sketches whose per-pixel loops crawl in Debug; null (the default) is
+`optimize`. Only Zig code changes mode (the host's and the app's), so it
+costs one more compile, not SDL's. A `b.option` makes it a `-D` flag.
+
+**Hot reload, checked.** `addReloadCheck` builds the app's library as
+written, and again from a copy of its sources with textual edits applied,
+then plays a script on the first through the generic host with `{v2}`
+defined as the second:
+
+```zig
+const check = app.addReloadCheck(.{ .script = b.path("test/reload.script"), .edits = &.{
+ .{ .file = "src/main.zig", .old = "0xff8040", .new = "0x40c0ff" },
+ .{ .file = "shaders/glsl/expo.frag", .old = "vec3(0.0, 1.0, 0.0)", .new = "vec3(1.0, 0.0, 0.0)" },
+} });
+steps.e2e.dependOn(&check.run.step);
+```
+
+Each `old` must occur exactly once in its `file` (a path as given to
+`b.path`), or the build fails. The copy is of each directory holding a
+source the app builds from (a module's root directory holds what it
+imports), and every module and shader set made from it (`addShaders`,
+`addZigShaders`) is made again from the copy, so edits to Zig code, GLSL
+and Zig shaders all reach the second library. The script plays, checks
+State, runs `load {v2}`, checks the same State, and compares screenshots
+(`expect-different-screenshot a.png b.png [x y w h]`). Pausing a replay
+first (`record`, `play`, `pause`) keeps the State still, so the two
+screenshots differ only by the edit. `sketches/shaders` and
+`sketches/noc` (bouncing_ball) have one each.
Shaders:
@@ -277,9 +555,25 @@ write-only storage buffers and no `coherent`: write them plain, or under
what includes it. `addGlslLayouts` and `addGlslc` are the pieces, for
anything else.
+Shaders can be Zig too: `sb.addZigShaders(.{ .sources, .imports })`, one
+shader per file with `export fn main() callconv(.{ .spirv_fragment = .{} })`,
+returns the same `Shaders`, so a sketch cannot tell the language. Zig's own
+SPIR-V backend compiles each for `spirv32-vulkan` (`spirv64` asks for
+physical pointers, which naga refuses), self-hosted (through LLVM the
+object comes out empty, silently); `tools/spirv_strip.zig` then drops the
+`Aligned` operands Zig puts on every load and store, which Vulkan accepts
+and naga's reader does not; and naga translates the result for the web as
+for GLSL. Shader code cannot use table-driven `std.math` (`atan2`: call
+GLSL.std.450 through inline assembly), and a uniform struct shared with
+the CPU needs a vec2 that is `@Vector(2, f32)` only on SPIR-V and `[2]f32`
+elsewhere. `sketches/shaders` has five Book of Shaders examples in both
+languages.
+
Tools: `glslc` (shaderc, or the Vulkan SDK's) for shaders, for web builds
with shaders `naga` (`cargo install naga-cli`; found on PATH or in cargo's
-directory), and for `serve`, `miniserve` and `openssl`.
+directory), and for `serve`, `miniserve` and `openssl`. This repository's
+own tests also run `node` (noise on wasm32, under WASI) and, for `zig build
+test-web`, Chrome.
`sb.modules`, `sb.host_exe` and `sb.probe_exe` are exposed for anything else.
Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`.
@@ -294,6 +588,12 @@ Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`.
leave it inconsistent, and `--fresh` starts it over.
- Handles inside Store containers (`std.ArrayList(sk.Image)`) are not caught
at compile time: the check does not follow pointers.
+- Native antialiasing resolves coverage per sample within a run of
+ shapes, the canvas per shape, so where two shapes' edges meet the web
+ can show a faint seam native does not. `fill` rects and images are
+ antialiased natively only inside a target. Without a GPU renderer,
+ native draws aliased. A stroke that overlaps itself blends twice
+ natively where it overlaps, once on the web.
- On the web: nothing persists (Store lasts as long as the page),
synthesised voices are silent, `loadSound` knows only sounds the page
decoded, multisampling is 4× at most, and mixing runs on the main thread
@@ -315,6 +615,20 @@ 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
+`zig build test` in this directory runs the unit tests, a headless reload
through `dlopen`, where a counter sketch changes its layout mid-run and keeps
-its values.
+its values, and a replay test (`test/replay.script`): a recording played,
+sought, stepped and replayed after a live pointer move, each ending on the
+state it was stopped at.
+
+The drawing layer's tests are there too: the shape cases drawn natively
+and checked pixel by pixel (`test/shapes.zig`), noise's golden values on
+wasm32 under Node, and the examples in `examples/` (`pen.zig`: Pens and a
+Clock; `flock.zig`: tessellations batched by hand, between Frame
+methods). `test/render.zig` covers targets (and that `set` and `load`
+repaint them while plain frames do not), blending, placed and tinted
+images and colours per subpath, checked pixel by pixel. `zig build
+test-web` draws the shape and render cases in headless Chrome, compares
+them with the native screenshots (`tools/chrome.mjs`), and times 5000
+circles a frame (software Canvas2D here: about 12 ms as 5000 shapes, 8 ms
+batched).
diff --git a/build.zig b/build.zig
index 40cb49e..ef6bc0c 100644
--- a/build.zig
+++ b/build.zig
@@ -31,16 +31,17 @@ pub fn build(b: *Build) void {
// 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 }},
- });
+ // Geometry and noise, shared by the sketch library and `vector`.
+ const math = b.addModule("math", .{ .root_source_file = b.path("src/math/root.zig") });
+ const sketch_imports: []const Build.Module.Import = &.{ .{ .name = "abi", .module = abi }, .{ .name = "math", .module = math } };
+ const sketch = b.addModule("sketch", .{ .root_source_file = b.path("src/sketch/root.zig"), .imports = sketch_imports });
const c = cModule(b, target, optimize);
+ // No optimize mode of its own: the host's Zig code builds in the mode
+ // of the executable it is part of (`script_optimize` makes use of it).
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 } },
});
@@ -66,19 +67,20 @@ pub fn build(b: *Build) void {
});
b.installArtifact(probe);
- var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined, .scope = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .shared = .create(b) };
+ var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined, .scope = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .script_optimize = optimize, .shared = .create(b) };
// Vector graphics: built with the same shader step apps use. Both forms
// of its shaders are exported, so apps' web builds can swap them too.
const vector_layouts = b.createModule(.{ .root_source_file = b.path("src/vector/layouts.zig") });
const vector_shaders = sb.addShaders(.{
- .layouts = .{ .module = vector_layouts, .types = &.{ "Vertex", "Viewport", "Paint" } },
- .sources = &.{ b.path("src/vector/shaders/path.vert"), b.path("src/vector/shaders/stencil.frag"), b.path("src/vector/shaders/cover.frag") },
+ .layouts = .{ .module = vector_layouts, .types = &.{ "Vertex", "Painted", "Viewport", "Paint" } },
+ .sources = &.{ b.path("src/vector/shaders/path.vert"), b.path("src/vector/shaders/stencil.frag"), b.path("src/vector/shaders/paint.vert"), b.path("src/vector/shaders/paint.frag") },
});
b.modules.put(b.graph.arena, "vector_shaders", vector_shaders.module) catch @panic("OOM");
b.modules.put(b.graph.arena, "vector_shaders_web", vector_shaders.web) catch @panic("OOM");
const vector_imports: []const Build.Module.Import = &.{
.{ .name = "abi", .module = abi },
+ .{ .name = "math", .module = math },
.{ .name = "vector_layouts", .module = vector_layouts },
.{ .name = "vector_shaders", .module = vector_shaders.module },
};
@@ -114,14 +116,70 @@ pub fn build(b: *Build) void {
b.createModule(.{ .root_source_file = b.path("src/scope/root.zig"), .target = target, .optimize = optimize, .imports = scope_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/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }),
+ b.createModule(.{ .root_source_file = b.path("src/math/root.zig"), .target = target, .optimize = optimize }),
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);
+ // The noise tests again on wasm32 as the web builds it, under Node's
+ // WASI: the golden bits must come out the same in the browser as
+ // natively. (Only noise: LLVM 21 cannot select code for one of the
+ // Bézier tests' vector constants on wasm32 in release modes.)
+ const wasm_math = b.addTest(.{ .root_module = b.createModule(.{
+ .root_source_file = b.path("src/math/noise.zig"),
+ .target = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .wasi }),
+ .optimize = .ReleaseSafe,
+ }) });
+ const wasi = Build.Step.Run.create(b, "noise tests on wasm32-wasi");
+ wasi.addFileArg(sb.program(&sb.shared.node, &.{"node"}));
+ wasi.addArg("--no-warnings");
+ wasi.addFileArg(b.path("tools/wasi_run.mjs"));
+ wasi.addArtifactArg(wasm_math);
+ // The test runner's progress is not a warning.
+ _ = wasi.captureStdErr(.{});
+ wasi.expectExitCode(0);
+ test_step.dependOn(&wasi.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();
+ // Command.shape on the native host: the parity cases, screenshotted
+ // and checked pixel by pixel (tools/shapes_web.mjs compares the same
+ // sketch in headless Chrome: `zig build test-web`).
+ const shapes = sb.app(.{ .name = "shapes", .root_source_file = b.path("test/shapes.zig") });
+ const shapes_native = shapes.addScript(shapes.addExecutable(), b.path("test/shapes.script"), .{});
+ test_step.dependOn(&shapes_native.step);
+ const shapes_web = Build.Step.Run.create(b, "shapes in headless Chrome");
+ shapes_web.addFileArg(sb.program(&sb.shared.node, &.{"node"}));
+ shapes_web.addFileArg(b.path("tools/shapes_web.mjs"));
+ shapes_web.addDirectoryArg(shapes.addWeb(.{}).dir);
+ shapes_web.addFileArg(b.path(".zig-cache/shapes/native.png"));
+ shapes_web.addFileArg(b.findProgramLazy(.{ .names = &.{ "google-chrome-stable", "google-chrome", "chromium", "chromium-browser" } }));
+ shapes_web.step.dependOn(&shapes_native.step);
+ shapes_web.has_side_effects = true;
+ shapes_web.expectExitCode(0);
+ const test_web = b.step("test-web", "Compare shapes, targets, blending and images in headless Chrome with the native host, and time 5000 circles");
+ test_web.dependOn(&shapes_web.step);
+ // Targets, blend modes, image placement and tint, colours per subpath
+ // (test/render.zig): natively, checked pixel by pixel, and in Chrome.
+ const render = sb.app(.{ .name = "render", .root_source_file = b.path("test/render.zig") });
+ const render_native = render.addScript(render.addExecutable(), b.path("test/render.script"), .{});
+ test_step.dependOn(&render_native.step);
+ const render_web = Build.Step.Run.create(b, "render in headless Chrome");
+ render_web.addFileArg(sb.program(&sb.shared.node, &.{"node"}));
+ render_web.addFileArg(b.path("tools/render_web.mjs"));
+ render_web.addDirectoryArg(render.addWeb(.{}).dir);
+ render_web.addFileArg(b.path(".zig-cache/render/native.png"));
+ render_web.addFileArg(b.findProgramLazy(.{ .names = &.{ "google-chrome-stable", "google-chrome", "chromium", "chromium-browser" } }));
+ render_web.step.dependOn(&render_native.step);
+ render_web.has_side_effects = true;
+ render_web.expectExitCode(0);
+ test_web.dependOn(&render_web.step);
+ // The examples, so they always compile.
+ for ([_][]const u8{ "pen", "flock" }) |example| {
+ test_step.dependOn(&sb.app(.{ .name = example, .root_source_file = b.path(b.fmt("examples/{s}.zig", .{example})) }).addLibrary().step);
+ }
// 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);
@@ -135,12 +193,24 @@ pub fn build(b: *Build) void {
reload.addArtifactArg(v1);
reload.expectExitCode(0);
test_step.dependOn(&reload.step);
+
+ // Recorded input replays to the same state: played, seeked, stepped,
+ // and after a live pointer move (core host behaviour, not an API).
+ const replay = b.addRunArtifact(host_exe);
+ replay.addArgs(&.{ "--headless", "--fresh", "--script" });
+ replay.addFileArg(b.path("test/replay.script"));
+ replay.addArg("--state");
+ _ = replay.addOutputFileArg("replay.state");
+ replay.addArtifactArg(sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig") }).addLibrary());
+ replay.expectExitCode(0);
+ test_step.dependOn(&replay.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"));
+ fixSdlVulkanAllocationLeak(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
@@ -196,6 +266,51 @@ fn fixSdlThreadCleanup(b: *Build, sdl: *Build.Module, source: Build.LazyPath) vo
sdl.addCSourceFile(.{ .file = patched, .flags = flags.? });
}
+/// SDL 3.4's Vulkan backend leaks a memory allocation's region list and
+/// mutex when `vkAllocateMemory` fails (SDL_gpu_vulkan.c,
+/// `VULKAN_INTERNAL_AllocateMemory`), which it then survives by trying
+/// another memory type. Many headless hosts at once (parallel `e2e`) run
+/// small heaps out, and the leak check failed random scripts. The file is
+/// compiled from a copy with the two frees added.
+fn fixSdlVulkanAllocationLeak(b: *Build, sdl: *Build.Module, source: Build.LazyPath) void {
+ const file = "src/gpu/vulkan/SDL_gpu_vulkan.c";
+ var found = false;
+ var flags: []const []const u8 = &.{};
+ for (sdl.link_objects.items) |object| {
+ if (object != .c_source_files) continue;
+ const group = object.c_source_files;
+ for (group.files, 0..) |f, i| {
+ if (!std.mem.eql(u8, f, file)) 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;
+ found = true;
+ break;
+ }
+ }
+ if (!found) return;
+ const tool = b.addExecutable(.{ .name = "reload-edit", .root_module = b.createModule(.{
+ .root_source_file = b.path("tools/reload_edit.zig"),
+ .target = b.graph.host,
+ }) });
+ const edit = b.addRunArtifact(tool);
+ edit.setName("patch SDL_gpu_vulkan.c");
+ edit.addDirectoryArg(source.path(b, "gpu/vulkan"));
+ const out = edit.addOutputDirectoryArg("vulkan");
+ edit.addArgs(&.{
+ "SDL_gpu_vulkan.c",
+ " // Uh oh, we couldn't allocate, time to clean up\n SDL_free(allocation->freeRegions);\n",
+ " // Uh oh, we couldn't allocate, time to clean up\n SDL_free(allocation->freeRegions);\n SDL_free(allocation->usedRegions);\n SDL_DestroyMutex(allocation->memoryLock);\n",
+ });
+ // The copy's relative includes (`../SDL_sysgpu.h`) resolve from the
+ // original directory.
+ sdl.addIncludePath(source.path(b, "gpu/vulkan"));
+ sdl.addIncludePath(source);
+ sdl.addCSourceFile(.{ .file = out.path(b, "SDL_gpu_vulkan.c"), .flags = flags });
+}
+
// ---------------------------------------------------------------------------
// Build API for apps
@@ -204,6 +319,12 @@ pub const Options = struct {
optimize: std.builtin.OptimizeMode,
/// This package's name in the app's build.zig.zon.
dependency: []const u8 = "sketchbook",
+ /// The optimize mode of the executables `e2e` plays scripts with
+ /// (`App.addScriptExecutable`); `optimize` when null. Pass it a
+ /// `b.option`, say `-Dscript-optimize=ReleaseSafe`, when Debug is too
+ /// slow for a sketch's scripts. Only the host's and the app's Zig code
+ /// change mode; SDL and the C pieces keep `optimize`.
+ script_optimize: ?std.builtin.OptimizeMode = null,
};
pub fn init(b: *Build, options: Options) Sketchbook {
@@ -221,6 +342,8 @@ pub fn init(b: *Build, options: Options) Sketchbook {
.probe_exe = dep.artifact("sketchbook-probe"),
.web = dep.path("web"),
.glsl = dep.path("src/glsl.zig"),
+ .tools = dep.path("tools"),
+ .script_optimize = options.script_optimize orelse options.optimize,
.shared = shared,
};
}
@@ -229,15 +352,20 @@ pub fn init(b: *Build, options: Options) Sketchbook {
const Shared = struct {
/// SPIR-V shader modules and their WGSL twins (see `addShaders`).
web_twins: std.AutoArrayHashMapUnmanaged(*Build.Module, *Build.Module) = .empty,
+ /// How each shader module was made, so `addReloadCheck` can make it
+ /// again from edited sources.
+ recipes: std.AutoArrayHashMapUnmanaged(*Build.Module, Recipe) = .empty,
/// Lookups of external tools, made once, run when a step needs them.
glslc: ?Build.LazyPath = null,
naga: ?Build.LazyPath = null,
miniserve: ?Build.LazyPath = null,
+ node: ?Build.LazyPath = null,
openssl: ?Build.LazyPath = null,
/// A self-signed certificate and its key, for `addServe`.
certificate: ?Certificate = null,
const Certificate = struct { cert: Build.LazyPath, key: Build.LazyPath };
+ const Recipe = union(enum) { glsl: Sketchbook.ShaderOptions, zig: Sketchbook.ZigShaderOptions };
fn create(b: *Build) *Shared {
const shared = b.graph.arena.create(Shared) catch @panic("OOM");
@@ -261,6 +389,12 @@ pub const Sketchbook = struct {
web: Build.LazyPath,
/// The GLSL declaration generator (see `addGlslLayouts`).
glsl: Build.LazyPath,
+ /// Build-time tools (`spirv_strip.zig`, `reload_edit.zig`, ...).
+ tools: Build.LazyPath,
+ /// The optimize mode of executables that play scripts (`e2e`): Debug
+ /// is slow for per-pixel loops, and that is often the only reason to
+ /// build a script run differently from the rest.
+ script_optimize: std.builtin.OptimizeMode,
shared: *Shared,
pub const GlslLayouts = struct {
@@ -316,7 +450,7 @@ pub const Sketchbook = struct {
optimize: bool = true,
}) Glslc {
const b = sb.b;
- const name = std.fs.path.basename(options.source.getDisplayName());
+ const name = fileName(options.source);
const run = Build.Step.Run.create(b, b.fmt("glslc {s}", .{name}));
run.addFileArg(sb.glslc());
run.addArg(b.fmt("--target-env={s}", .{options.target_env}));
@@ -353,14 +487,16 @@ pub const Sketchbook = struct {
/// them `buffer`), and no `coherent` (WGSL's barriers make storage
/// writes visible to the workgroup anyway, so leave it out under
/// `#ifdef SKETCHBOOK_WEB`).
- pub fn addShaders(sb: Sketchbook, options: struct {
+ pub const ShaderOptions = struct {
sources: []const Build.LazyPath,
/// Uniform and vertex layouts generated from Zig types, which the
/// sources `#include` as `<Type>.glsl` (see `addGlslLayouts`).
layouts: ?struct { module: *Build.Module, types: []const []const u8 } = null,
/// More `#include` directories.
include_dirs: []const Build.LazyPath = &.{},
- }) Shaders {
+ };
+
+ pub fn addShaders(sb: Sketchbook, options: ShaderOptions) Shaders {
const b = sb.b;
const include_dirs = b.graph.arena.alloc(Build.LazyPath, options.include_dirs.len + 1) catch @panic("OOM");
@memcpy(include_dirs[0..options.include_dirs.len], options.include_dirs);
@@ -375,7 +511,7 @@ pub const Sketchbook = struct {
var native_source: std.ArrayList(u8) = .empty;
var web_source: std.ArrayList(u8) = .empty;
for (options.sources) |source| {
- const file = std.fs.path.basename(source.getDisplayName());
+ const file = fileName(source);
const name = std.mem.replaceOwned(u8, b.graph.arena, file, ".", "_") catch @panic("OOM");
const spirv = sb.addGlslc(.{ .source = source, .include_dirs = dirs }).spirv;
_ = native.addCopyFile(spirv, b.fmt("{s}.spv", .{name}));
@@ -395,6 +531,84 @@ pub const Sketchbook = struct {
.web = b.createModule(.{ .root_source_file = web.add("wgsl.zig", web_source.items) }),
};
sb.shared.web_twins.put(b.graph.arena, shaders.module, shaders.web) catch @panic("OOM");
+ var kept = options;
+ kept.sources = b.graph.arena.dupe(Build.LazyPath, options.sources) catch @panic("OOM");
+ kept.include_dirs = b.graph.arena.dupe(Build.LazyPath, options.include_dirs) catch @panic("OOM");
+ sb.shared.recipes.put(b.graph.arena, shaders.module, .{ .glsl = kept }) catch @panic("OOM");
+ return shaders;
+ }
+
+ pub const ZigShaderOptions = struct {
+ /// One shader per file, its entry point `export fn main` with a
+ /// SPIR-V calling convention (`.spirv_fragment`, `.spirv_vertex`).
+ sources: []const Build.LazyPath,
+ /// Modules the shaders import (shared uniform structs, helpers).
+ imports: []const Build.Module.Import = &.{},
+ };
+
+ /// Shaders written in Zig, as `addShaders` makes them from GLSL: the
+ /// same `Shaders` (SPIR-V module, WGSL twin swapped in for the web), so
+ /// a sketch cannot tell which language a shader came from. `fill.zig`
+ /// is declared as `fill`.
+ ///
+ /// Each source is compiled by Zig's own SPIR-V backend. The steps, and
+ /// why each one is there:
+ /// - target `spirv32-vulkan`: `spirv64` asks for physical storage
+ /// buffer pointers, which naga refuses;
+ /// - the self-hosted backend (`use_llvm = false`), ReleaseFast: through
+ /// LLVM the object comes out empty, without an error;
+ /// - `tools/spirv_strip.zig` then drops the `Aligned` memory operands
+ /// Zig puts on every OpLoad/OpStore: Vulkan accepts them, naga's
+ /// SPIR-V reader does not ("invalid operand count");
+ /// - for the web, `naga --keep-coordinate-space` translates the
+ /// stripped SPIR-V to WGSL, as for GLSL.
+ ///
+ /// What shader code can be: no table-driven `std.math` (`atan2` indexes
+ /// const tables through generic pointers, which logical addressing
+ /// forbids: call GLSL.std.450 through inline assembly), and no
+ /// `@Vector` in an `extern struct` shared with the CPU (use `[2]f32`
+ /// there and `@Vector` only when `builtin.cpu.arch.isSpirV()`; std140
+ /// wants a vec2 array stride of 16, which a `[2]f32` array lacks).
+ pub fn addZigShaders(sb: Sketchbook, options: ZigShaderOptions) Shaders {
+ const b = sb.b;
+ const spirv = b.resolveTargetQuery(.{ .cpu_arch = .spirv32, .os_tag = .vulkan });
+ const strip = b.addExecutable(.{ .name = "spirv-strip", .root_module = b.createModule(.{
+ .root_source_file = sb.tools.path(b, "spirv_strip.zig"),
+ .target = b.graph.host,
+ }) });
+ const native = b.addWriteFiles();
+ const web = b.addWriteFiles();
+ var native_source: std.ArrayList(u8) = .empty;
+ var web_source: std.ArrayList(u8) = .empty;
+ for (options.sources) |source| {
+ const name = std.fs.path.stem(fileName(source));
+ const object = b.addObject(.{
+ .name = name,
+ .root_module = b.createModule(.{ .root_source_file = source, .target = spirv, .optimize = .ReleaseFast, .imports = options.imports }),
+ .use_llvm = false,
+ });
+ const stripped = b.addRunArtifact(strip);
+ stripped.addFileArg(object.getEmittedBin());
+ const spv = stripped.addOutputFileArg(b.fmt("{s}.spv", .{name}));
+ _ = native.addCopyFile(spv, b.fmt("{s}.spv", .{name}));
+ native_source.print(b.graph.arena, "const {s}_words align(4) = @embedFile(\"{s}.spv\").*;\npub const {s}: []const u8 = &{s}_words;\n", .{ name, name, name, name }) catch @panic("OOM");
+
+ const translate = Build.Step.Run.create(b, b.fmt("naga {s}", .{fileName(source)}));
+ translate.addFileArg(sb.naga());
+ translate.addArg("--keep-coordinate-space");
+ translate.addFileArg(spv);
+ _ = web.addCopyFile(translate.addOutputFileArg(b.fmt("{s}.wgsl", .{name})), b.fmt("{s}.wgsl", .{name}));
+ web_source.print(b.graph.arena, "pub const {s}: []const u8 = @embedFile(\"{s}.wgsl\");\n", .{ name, name }) catch @panic("OOM");
+ }
+ const shaders: Shaders = .{
+ .module = b.createModule(.{ .root_source_file = native.add("spirv.zig", native_source.items) }),
+ .web = b.createModule(.{ .root_source_file = web.add("wgsl.zig", web_source.items) }),
+ };
+ sb.shared.web_twins.put(b.graph.arena, shaders.module, shaders.web) catch @panic("OOM");
+ sb.shared.recipes.put(b.graph.arena, shaders.module, .{ .zig = .{
+ .sources = b.graph.arena.dupe(Build.LazyPath, options.sources) catch @panic("OOM"),
+ .imports = b.graph.arena.dupe(Build.Module.Import, options.imports) catch @panic("OOM"),
+ } }) catch @panic("OOM");
return shaders;
}
@@ -412,7 +626,7 @@ pub const Sketchbook = struct {
}
/// A tool found on PATH when a step needs it, looked up once.
- fn program(sb: Sketchbook, slot: *?Build.LazyPath, names: []const []const u8) Build.LazyPath {
+ pub fn program(sb: Sketchbook, slot: *?Build.LazyPath, names: []const []const u8) Build.LazyPath {
if (slot.* == null) slot.* = sb.b.findProgramLazy(.{ .names = names });
return slot.*.?;
}
@@ -518,6 +732,16 @@ pub const App = struct {
/// 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.executable(app.sb.optimize);
+ }
+
+ /// The executable as scripts play it: built in `script_optimize` mode
+ /// (see `Options`), the same as `addExecutable` unless that was set.
+ pub fn addScriptExecutable(app: App) *Build.Step.Compile {
+ return app.executable(app.sb.script_optimize);
+ }
+
+ fn executable(app: App, optimize: std.builtin.OptimizeMode) *Build.Step.Compile {
return app.sb.b.addExecutable(.{
.name = app.name,
.root_module = app.wrap(
@@ -525,7 +749,7 @@ pub const App = struct {
\\pub fn main(init: std.process.Init) !void {
\\ return @import("host").main(init, @import("sketch").sketch(@import("app")));
\\}
- , app.sb.target, app.sb.optimize),
+ , app.sb.target, optimize),
});
}
@@ -747,6 +971,217 @@ pub const App = struct {
return b.addTest(.{ .root_module = module });
}
+ pub const Edit = struct {
+ /// Relative to the app's build root, as given to `b.path`: a Zig
+ /// source, a GLSL source, or a Zig shader source the app builds.
+ file: []const u8,
+ /// Must occur exactly once in `file`, or the build fails.
+ old: []const u8,
+ new: []const u8,
+ };
+
+ pub const ReloadCheck = struct {
+ run: *Build.Step.Run,
+ /// The library as written, and as edited.
+ library: *Build.Step.Compile,
+ edited: *Build.Step.Compile,
+ };
+
+ /// Checks that the app hot-reloads with its State kept: builds its
+ /// library as written, and again from a copy of its sources with
+ /// `edits` applied, then plays `script` headless through the generic
+ /// host on the first, with `{v2}` defined as the second, so the script
+ /// can `load {v2}` midway and check that State carried over (and, with
+ /// `expect-different-screenshot`, that the edit shows).
+ ///
+ /// The copy covers the directory of every source an edited file is in
+ /// (a module's root's directory holds what it imports), and every
+ /// module and shader set (`addShaders`, `addZigShaders`) built from it
+ /// is built again from the copy, so edits to Zig code, GLSL and Zig
+ /// shaders all reach the second library.
+ pub fn addReloadCheck(app: App, options: struct {
+ script: Build.LazyPath,
+ edits: []const Edit,
+ }) ReloadCheck {
+ const b = app.sb.b;
+ var remap: Remap = .{ .sb = app.sb };
+ remap.collect(app.module);
+ for (options.edits) |edit| remap.cover(edit);
+ remap.makeCopies(options.edits);
+ var edited_app = app;
+ edited_app.module = remap.remapModule(app.module);
+
+ const library = app.addLibrary();
+ const edited = edited_app.addLibrary();
+ const run = b.addRunArtifact(app.sb.host_exe);
+ run.setName(b.fmt("reload check {s}", .{options.script.getDisplayName()}));
+ run.addArgs(&.{ "--headless", "--fresh", "--script" });
+ run.addFileArg(options.script);
+ run.addArg("--state");
+ _ = run.addOutputFileArg(b.fmt("{s}-{s}.state", .{ app.name, std.fs.path.stem(options.script.getDisplayName()) }));
+ run.addArg("--define");
+ run.addPrefixedArtifactArg("v2=", edited);
+ run.addArtifactArg(library);
+ run.setCwd(b.path("."));
+ run.expectExitCode(0);
+ run.has_side_effects = true;
+ return .{ .run = run, .library = library, .edited = edited };
+ }
+
+ /// The app's module graph, with the sources under some directories
+ /// replaced by edited copies (see `addReloadCheck`).
+ const Remap = struct {
+ sb: Sketchbook,
+ /// Source directories (relative to the build root) the graph uses.
+ dirs: std.ArrayList([]const u8) = .empty,
+ /// The directories copied, and their edited copies.
+ roots: std.ArrayList([]const u8) = .empty,
+ copies: std.ArrayList(Build.LazyPath) = .empty,
+ seen: std.AutoArrayHashMapUnmanaged(*Build.Module, void) = .empty,
+ done: std.AutoArrayHashMapUnmanaged(*Build.Module, *Build.Module) = .empty,
+
+ fn arena(r: *Remap) std.mem.Allocator {
+ return r.sb.b.graph.arena;
+ }
+
+ fn ours(r: *Remap, path: Build.LazyPath) ?[]const u8 {
+ return switch (path) {
+ .src_path => |p| if (p.owner == r.sb.b) p.sub_path else null,
+ else => null,
+ };
+ }
+
+ fn note(r: *Remap, path: ?Build.LazyPath) void {
+ const sub = r.ours(path orelse return) orelse return;
+ r.dirs.append(r.arena(), std.fs.path.dirname(sub) orelse ".") catch @panic("OOM");
+ }
+
+ fn collect(r: *Remap, m: *Build.Module) void {
+ if ((r.seen.getOrPut(r.arena(), m) catch @panic("OOM")).found_existing) return;
+ if (r.sb.shared.recipes.get(m)) |recipe| switch (recipe) {
+ .glsl => |o| {
+ for (o.sources) |src| r.note(src);
+ if (o.layouts) |l| r.collect(l.module);
+ },
+ .zig => |o| {
+ for (o.sources) |src| r.note(src);
+ for (o.imports) |i| r.collect(i.module);
+ },
+ };
+ r.note(m.root_source_file);
+ for (m.import_table.values()) |i| r.collect(i);
+ }
+
+ fn under(dir: []const u8, path: []const u8) bool {
+ if (std.mem.eql(u8, dir, ".")) return true;
+ return path.len > dir.len and std.mem.startsWith(u8, path, dir) and path[dir.len] == '/';
+ }
+
+ /// Picks the outermost source directory holding `edit.file`.
+ fn cover(r: *Remap, edit: Edit) void {
+ var best: ?[]const u8 = null;
+ for (r.dirs.items) |dir| if (under(dir, edit.file) and (best == null or under(dir, best.?))) {
+ best = dir;
+ };
+ const dir = best orelse std.debug.panic("addReloadCheck: {s} is in no directory of a source the app builds", .{edit.file});
+ for (r.roots.items) |*root| {
+ if (under(root.*, dir) or std.mem.eql(u8, root.*, dir)) return;
+ if (under(dir, root.*)) {
+ root.* = dir;
+ return;
+ }
+ }
+ r.roots.append(r.arena(), dir) catch @panic("OOM");
+ }
+
+ fn makeCopies(r: *Remap, edits: []const Edit) void {
+ const b = r.sb.b;
+ const tool = b.addExecutable(.{ .name = "reload-edit", .root_module = b.createModule(.{
+ .root_source_file = r.sb.tools.path(b, "reload_edit.zig"),
+ .target = b.graph.host,
+ }) });
+ for (r.roots.items) |root| {
+ // Copied first: the copy's directory is named by its
+ // contents, so the edit below reruns whenever they change.
+ const copy = b.addWriteFiles();
+ const source = copy.addCopyDirectory(b.path(root), "", .{});
+ const run = b.addRunArtifact(tool);
+ run.setName(b.fmt("edit a copy of {s}", .{root}));
+ run.addDirectoryArg(source);
+ const out = run.addOutputDirectoryArg("src");
+ for (edits) |edit| {
+ if (!under(root, edit.file)) continue;
+ run.addArgs(&.{ if (std.mem.eql(u8, root, ".")) edit.file else edit.file[root.len + 1 ..], edit.old, edit.new });
+ }
+ r.copies.append(r.arena(), out) catch @panic("OOM");
+ }
+ }
+
+ fn remapPath(r: *Remap, original: Build.LazyPath) Build.LazyPath {
+ const sub = r.ours(original) orelse return original;
+ for (r.roots.items, r.copies.items) |root, copy| {
+ if (!under(root, sub)) continue;
+ return copy.path(r.sb.b, if (std.mem.eql(u8, root, ".")) sub else sub[root.len + 1 ..]);
+ }
+ return original;
+ }
+
+ fn paths(r: *Remap, originals: []const Build.LazyPath, changed: *bool) []const Build.LazyPath {
+ const out = r.arena().alloc(Build.LazyPath, originals.len) catch @panic("OOM");
+ for (originals, out) |o, *p| {
+ p.* = r.remapPath(o);
+ changed.* = changed.* or std.meta.activeTag(p.*) != std.meta.activeTag(o);
+ }
+ return out;
+ }
+
+ fn remapModule(r: *Remap, m: *Build.Module) *Build.Module {
+ if (r.done.get(m)) |copy| return copy;
+ r.done.put(r.arena(), m, m) catch @panic("OOM");
+ var changed = false;
+ const result = if (r.sb.shared.recipes.get(m)) |recipe| switch (recipe) {
+ .glsl => |o| blk: {
+ var e = o;
+ e.sources = r.paths(o.sources, &changed);
+ if (o.layouts) |l| {
+ e.layouts = .{ .module = r.remapModule(l.module), .types = l.types };
+ changed = changed or e.layouts.?.module != l.module;
+ }
+ break :blk if (changed) r.sb.addShaders(e).module else m;
+ },
+ .zig => |o| blk: {
+ var e = o;
+ e.sources = r.paths(o.sources, &changed);
+ const imports = r.arena().alloc(Build.Module.Import, o.imports.len) catch @panic("OOM");
+ for (o.imports, imports) |i, *out| {
+ out.* = .{ .name = i.name, .module = r.remapModule(i.module) };
+ changed = changed or out.module != i.module;
+ }
+ e.imports = imports;
+ break :blk if (changed) r.sb.addZigShaders(e).module else m;
+ },
+ } else blk: {
+ const root = if (m.root_source_file) |file| r.remapPath(file) else null;
+ if (m.root_source_file) |file| changed = std.meta.activeTag(root.?) != std.meta.activeTag(file);
+ const imports = r.arena().alloc(*Build.Module, m.import_table.count()) catch @panic("OOM");
+ for (m.import_table.values(), imports) |i, *out| {
+ out.* = r.remapModule(i);
+ changed = changed or out.* != i;
+ }
+ if (!changed) break :blk m;
+ const copy = r.arena().create(Build.Module) catch @panic("OOM");
+ copy.init(m.owner, .{ .existing = m });
+ copy.root_source_file = root;
+ copy.import_table = .empty;
+ copy.cached_graph = .{ .modules = &.{}, .names = &.{} };
+ for (m.import_table.keys(), imports) |name, i| copy.addImport(name, i);
+ break :blk copy;
+ };
+ r.done.put(r.arena(), m, result) catch @panic("OOM");
+ return result;
+ }
+ };
+
pub const StepsOptions = struct {
web: ?WebOptions = null,
/// Scripts run by the `e2e` step.
@@ -788,7 +1223,8 @@ pub const App = struct {
} 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 script_exe = if (app.sb.script_optimize == app.sb.optimize) exe else app.addScriptExecutable();
+ for (options.scripts) |script| e2e.dependOn(&app.addScript(script_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);
@@ -798,6 +1234,16 @@ pub const App = struct {
}
};
+/// A source's file name, for naming what is made from it: also for a file
+/// inside a generated directory (an edited copy, see `addReloadCheck`),
+/// whose display name would be "generated".
+fn fileName(path: Build.LazyPath) []const u8 {
+ return switch (path) {
+ .generated => |g| if (g.sub_path.len > 0) std.fs.path.basename(g.sub_path) else path.getDisplayName(),
+ else => std.fs.path.basename(path.getDisplayName()),
+ };
+}
+
/// Fills `{title}` and `{head}` in the page template.
const page_tool =
\\const std = @import("std");
diff --git a/build.zig.zon b/build.zig.zon
index 4688729..ff49d2b 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -12,6 +12,6 @@
},
},
.minimum_zig_version = "0.17.0",
- .paths = .{ "build.zig", "build.zig.zon", "src", "vendor", "web" },
+ .paths = .{ "build.zig", "build.zig.zon", "src", "tools", "vendor", "web" },
.fingerprint = 0x6d6d2e26aa60b45e,
}
diff --git a/examples/flock.zig b/examples/flock.zig
new file mode 100644
index 0000000..78df621
--- /dev/null
+++ b/examples/flock.zig
@@ -0,0 +1,56 @@
+//! The drawing layer's low levels, mixed with today's Frame methods: many
+//! triangles tessellated into two `sk.draw.Tessellation`s (L1) and emitted
+//! as two `Command.shape`s (L0), between an `f.fill` and an `f.print`.
+//! Batching like this is the sketch's own choice, and changes nothing in
+//! the picture: both hosts draw the shapes of a batch one after another.
+const std = @import("std");
+const sk = @import("sketch");
+const vec = sk.math;
+
+pub const name = "flock";
+pub const width = 640;
+pub const height = 360;
+
+const Boid = struct {
+ position: vec.Vec = .{ 0, 0 },
+ velocity: vec.Vec = .{ 1, 0 },
+};
+
+pub const State = struct {
+ rng: std.Random.Xoshiro256 = .init(7),
+ boids: sk.List(Boid, 512) = .{},
+ clock: sk.Clock = .{},
+};
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ // Dragging adds boids, where the pointer was at each move.
+ if (in.buttons & 1 != 0) for (in.events) |e| if (e.kind == .mouse_move) {
+ const r = s.rng.random();
+ s.boids.appendBounded(.{ .position = .{ e.x, e.y }, .velocity = vec.unit(r.float(f32) * 2 * std.math.pi) }) catch {};
+ };
+ for (0..s.clock.steps(in)) |_| for (s.boids.slice()) |*b| {
+ // Steer toward the centre, gently; wrap at the edges.
+ const centre: vec.Vec = .{ width / 2, height / 2 };
+ b.velocity = vec.withLength(b.velocity + vec.withLength(centre - b.position, 0.03), 2);
+ b.position += b.velocity;
+ b.position = @mod(b.position + vec.Vec{ width, height }, vec.Vec{ width, height });
+ };
+}
+
+const shape = [_]vec.Vec{ .{ 8, 0 }, .{ -8, -4 }, .{ -8, 4 } };
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ f.clear(0xffffff);
+ f.fill(.{ .x = 0, .y = height - 40, .w = width, .h = 40 }, 0xdcdcdc); // L0: a Frame method
+ var bodies: sk.draw.Tessellation = .empty; // L1: our own triangles
+ var edges: sk.draw.Tessellation = .empty;
+ for (s.boids.constSlice()) |b| {
+ const xf: vec.Affine = .place(b.position, vec.angle(b.velocity));
+ bodies.fillPolygon(f.scratch, &shape, xf) catch return;
+ edges.strokePolygon(f.scratch, &shape, 1, xf) catch return;
+ }
+ f.shape(&bodies, .gray(127));
+ // L0 itself: the command, built by hand from the same data.
+ f.emit(.{ .shape = .{ .color = .black, .points = edges.points.items, .ends = edges.ends.items, .indices = edges.indices.items } });
+ f.print(8, height - 30, 2, 0x000000, "{d} boids, drag to add", .{s.boids.len});
+}
diff --git a/examples/pen.zig b/examples/pen.zig
new file mode 100644
index 0000000..acbd236
--- /dev/null
+++ b/examples/pen.zig
@@ -0,0 +1,43 @@
+//! The drawing layer's convenience level: a ball that chases the mouse,
+//! and three spinners around it, drawn with `sk.draw` and plain-data Pens.
+//! Stepped at a fixed 60 Hz by `sk.Clock`, so a replay matches.
+const std = @import("std");
+const sk = @import("sketch");
+const vec = sk.math;
+
+pub const name = "pen";
+pub const width = 640;
+pub const height = 360;
+
+pub const State = struct {
+ position: vec.Vec = .{ width / 2, height / 2 },
+ velocity: vec.Vec = .{ 0, 0 },
+ spin: f32 = 0,
+ clock: sk.Clock = .{ .hz = 60 },
+};
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ for (0..s.clock.steps(in)) |_| {
+ const mouse: vec.Vec = .{ in.mouse_x, in.mouse_y };
+ s.velocity = vec.clampLength(s.velocity + vec.withLength(mouse - s.position, 0.2), 5);
+ s.position += s.velocity;
+ s.spin += 0.03;
+ }
+}
+
+const ball: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 };
+const spinner: sk.draw.Pen = .{ .fill = sk.Color.gray(200).alpha(160), .stroke = .black, .width = 2 };
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ f.clear(sk.Color.white);
+ sk.draw.circle(f, s.position, 24, ball);
+ for (0..3) |i| {
+ const turn = s.spin + @as(f32, @floatFromInt(i)) * 2 * std.math.pi / 3.0;
+ // Push, translate, rotate: a copy of the pen, placed.
+ const pen = spinner.transformed(.place(s.position + vec.scale(vec.unit(turn), 60), turn));
+ sk.draw.circle(f, .{ 0, 0 }, 12, pen);
+ sk.draw.line(f, .{ 0, 0 }, .{ 12, 0 }, pen);
+ sk.draw.polygon(f, &.{ .{ 18, 0 }, .{ 14, -4 }, .{ 14, 4 } }, pen);
+ }
+ f.print(8, 8, 1, 0x000000, "steps {d}", .{s.clock.count});
+}
diff --git a/src/abi.zig b/src/abi.zig
index ca1333e..03e2978 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -39,12 +39,38 @@ pub const Color = extern struct {
pub const white: Color = .{ .r = 255, .g = 255, .b = 255 };
pub const black: Color = .{ .r = 0, .g = 0, .b = 0 };
+ /// `v` in all three channels, opaque: `.gray(127)`.
+ pub fn gray(v: u8) Color {
+ return .{ .r = v, .g = v, .b = v };
+ }
pub fn hex(rgb: u24) Color {
return .{ .r = @truncate(rgb >> 16), .g = @truncate(rgb >> 8), .b = @truncate(rgb) };
}
pub fn alpha(c: Color, a: u8) Color {
return .{ .r = c.r, .g = c.g, .b = c.b, .a = a };
}
+ /// `c` with alpha `a` in 0..1, saturating: below 0 (a spent
+ /// lifespan) is transparent, above 1 opaque, NaN transparent.
+ pub fn alphaFloat(c: Color, a: f32) Color {
+ const clamped: f32 = if (a > 0) @min(a, 1) else 0;
+ return c.alpha(@intFromFloat(@round(clamped * 255)));
+ }
+};
+
+/// How 2D drawing combines with what is already there (`Command.blend`).
+/// Both are fixed-function on both hosts and match: `alpha` is source
+/// over (canvas `source-over`, SDL `BLEND`), `add` adds the colour times
+/// its alpha, and the alphas (canvas `lighter`; natively a custom SDL
+/// blend mode, since SDL's `ADD` would keep the destination's alpha in a
+/// transparent target).
+pub const BlendMode = enum(u8) { alpha, add };
+
+/// Where an image's corners land (`Command.image.corners`): any affine
+/// placement, rotated, sheared or mirrored. The fourth corner follows.
+pub const Corners = struct {
+ top_left: [2]f32,
+ top_right: [2]f32,
+ bottom_left: [2]f32,
};
/// One input event. Recordings are arrays of these on disk, so the layout is
@@ -97,6 +123,17 @@ pub const Event = extern struct {
return @bitCast(e.value);
}
+ /// A frame's tick, `dt` nanoseconds after the previous one.
+ pub fn tick(time: u64, dt: u64) Event {
+ return .{ .kind = .tick, .time = time, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) };
+ }
+ /// A tick's `dt` in nanoseconds, from the seconds it records: what
+ /// `Input.dt` is, live and replayed alike (nanoseconds do not survive
+ /// the trip through f32, so live time must come through it too).
+ pub fn tickDt(e: Event) u64 {
+ return @intFromFloat(@round(@max(0, @as(f64, e.x)) * std.time.ns_per_s));
+ }
+
comptime {
std.debug.assert(@sizeOf(Event) == 24);
}
@@ -104,6 +141,9 @@ pub const Event = extern struct {
pub const Mode = enum { live, recording, playing, paused };
+/// Mouse buttons by `Event.code`.
+pub const MouseButton = enum(u16) { left = 1, middle = 2, right = 3, _ };
+
/// A host audio stream, as last observed by the host.
pub const Stream = struct {
key: u32,
@@ -115,14 +155,25 @@ pub const Stream = struct {
/// Everything a sketch learns about the world for one call.
pub const Input = struct {
+ /// In `update`, the frame's tick time (`Event.time`: since the
+ /// recording began while recording or replaying); in `draw`, the host
+ /// clock, or the playback position.
now: u64 = 0,
- /// Nanoseconds since the previous frame.
+ /// In `update`, the frame's tick `dt` (`Event.tickDt`), the same live
+ /// and replayed; in `draw`, likewise for the frame just updated.
dt: u64 = 0,
frame: u64 = 0,
events: []const Event = &.{},
mode: Mode = .live,
/// First frame after new code, or a new layout, was loaded.
reloaded: bool = false,
+ /// In `draw`: State did not come here by `update` from what the last
+ /// `draw` saw. Set on the first frame, after a seek, step, snapshot
+ /// load, `set`, `reset`, a recording's play or record start, a sketch
+ /// command, and every reload (with `reloaded`). Pictures accumulated
+ /// in Session (a trail in an offscreen image) are stale then: redraw
+ /// them from State. `update` never sees it: it is not input.
+ jumped: bool = false,
/// First update since the program started (never after a hot reload):
/// the place to stop what should not resume from saved state, like a
/// song that was playing when the program quit.
@@ -137,6 +188,10 @@ pub const Input = struct {
/// canvas to it fills any window, a phone's included, at its own scale.
window_width: f32 = 0,
window_height: f32 = 0,
+ /// Pointer, buttons and keys follow the events fed, one frame at a time.
+ /// Restoring a snapshot (play, seek, step, load) clears them, and a
+ /// recording begins with events that restore them, so a replay starts
+ /// from the input its recording started from.
mouse_x: f32 = 0,
mouse_y: f32 = 0,
/// Held mouse buttons, bit `button - 1`.
@@ -164,6 +219,21 @@ pub const Input = struct {
}
return false;
}
+ /// Held after this frame's events (`buttons` bit `button - 1`).
+ pub fn mouseHeld(in: *const Input, button: MouseButton) bool {
+ return in.buttons & (@as(u32, 1) << @intCast(@min(@backingInt(button) -| 1, 31))) != 0;
+ }
+ /// The first press of `button` this frame, with its position (`e.x`,
+ /// `e.y`), or null. A sketch that needs every press reads `events`.
+ pub fn mousePressed(in: *const Input, button: MouseButton) ?Event {
+ for (in.events) |e| if (e.kind == .mouse_down and e.code == @backingInt(button)) return e;
+ return null;
+ }
+ /// The first release of `button` this frame, or null.
+ pub fn mouseReleased(in: *const Input, button: MouseButton) ?Event {
+ for (in.events) |e| if (e.kind == .mouse_up and e.code == @backingInt(button)) return e;
+ return null;
+ }
pub fn stream(in: *const Input, key: u32) Stream {
for (in.streams) |s| if (s.key == key) return s;
return .{ .key = key };
@@ -225,8 +295,49 @@ pub const Voice = struct {
pub const Command = union(enum) {
clear: Color,
rect: struct { dst: Rect, color: Color },
- /// `src` empty: the whole image. `tint` multiplies it.
- image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white },
+ /// Filled regions in one color, described twice over the same
+ /// `points` (canvas coordinates). As subpaths, `points[ends[i - 1] ..
+ /// ends[i]]` (from 0 for the first), which the web fills nonzero, one
+ /// fill per positively wound subpath (clockwise on screen) together
+ /// with the negatively wound ones after it, its holes. And as
+ /// triangles, `indices` into `points` three at a time, which native
+ /// draws with SDL_RenderGeometry. Each such group of subpaths and its
+ /// triangles must cover the same region, the triangles without
+ /// overlapping each other, or translucent colors blend twice natively
+ /// where the web blends once; separate groups that overlap blend
+ /// twice on both. `sketch.draw` makes shapes that keep this contract.
+ ///
+ /// `colors`, when not empty, gives each subpath its own colour
+ /// (`colors[i]` for subpath `i`, `color` past the end), so shapes of
+ /// many colours go in one command: the web fills each group in its
+ /// first subpath's colour, native gives each point its subpath's
+ /// colour, so a group (an outline and its holes) and the triangles
+ /// between them must share one.
+ ///
+ /// Antialiased on both hosts: the web's canvas does it per shape;
+ /// native takes 4x4 samples a pixel (a GPU renderer; without one,
+ /// aliased), on the canvas through a layer that a run of consecutive
+ /// shapes shares, in a target throughout (see `target`).
+ shape: struct { color: Color, points: []const [2]f32, ends: []const u32, indices: []const u32, colors: []const Color = &.{} },
+ /// `src` empty: the whole image. `tint` multiplies it: colour per
+ /// channel, alpha as a whole. `corners`, when set, places the image
+ /// (any affine: `sketch.Frame.imageAt` centres and turns it) and `dst`
+ /// is unused. Native samples nearest; the web antialiases the edges of
+ /// a turned image.
+ image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white, corners: ?Corners = null },
+ /// Where the 2D commands after it draw: an image made by
+ /// `Host.newImage` (an offscreen target, kept between frames), or
+ /// `.none` for the canvas. Each frame starts on the canvas. Switching
+ /// clears the clip. Images start transparent. Natively a target is
+ /// supersampled whole (4x4) and holds premultiplied colour, so it
+ /// shows the same picture however its commands were split across
+ /// frames, and draws as a canvas would.
+ /// A target is a Session cache, never truth: redraw it when
+ /// `Input.jumped`.
+ target: Image,
+ /// The blend for the 2D commands after it (`rect`, `shape`, `image`;
+ /// `text` and `clear` ignore it). Each frame starts with `alpha`.
+ blend: BlendMode,
/// Fixed 8px cells, `scale` times larger.
text: struct { x: f32, y: f32, scale: f32, color: Color, bytes: []const u8 },
clip: ?Rect,
@@ -556,20 +667,30 @@ pub const Context = struct {
};
/// One leaf of a reflected layout. Nested structs are flattened into dotted
-/// paths; arrays stay whole. Hosts migrate state across layout changes, and
+/// paths, and arrays and vectors into element leaves (`boids[].pos[]`, one
+/// leaf for all elements, see `dims`). Hosts migrate state across layout changes, and
/// inspect or edit it by name, from these. Stored in the state file header.
pub const Field = extern struct {
path: [*:0]const u8,
offset: u32,
size: u32,
kind: Kind,
- reserved: [3]u8 = @splat(0),
+ /// How many `[]` the path has: one per array or vector it sits in.
+ rank: u8 = 0,
+ reserved: [2]u8 = @splat(0),
/// Structural hash of the field's type: equal hashes copy byte for byte.
hash: u64,
/// Enums: "name=value" pairs separated by commas. Empty otherwise.
tags: [*:0]const u8 = "",
+ /// `rank` entries, outermost first: element count and byte stride of
+ /// each `[]` in `path`. `offset` is element 0's.
+ dims: [*]const Dim = &[_]Dim{},
+ /// `array` is a whole array or vector, kept for copying it in one piece
+ /// when its type is unchanged; its elements follow as leaves of their
+ /// own (`list[]`, `list[].x`).
pub const Kind = enum(u8) { int, uint, float, bool, @"enum", array, bytes, _ };
+ pub const Dim = extern struct { count: u32, stride: u32 };
};
pub const Layout = struct {
@@ -635,7 +756,7 @@ pub const Sketch = struct {
pub const hash: u64 = blk: {
@setEvalBranchQuota(1_000_000);
var h: u64 = 0;
- for (.{ Rect, Color, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| {
+ for (.{ Rect, Color, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| {
h = std.hash.Wyhash.hash(h, @typeName(T) ++ layout.signature(T));
}
break :blk h;
diff --git a/src/host/Console.zig b/src/host/Console.zig
index b22facb..40845f7 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -133,7 +133,7 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
const rest = words.rest();
if (eq(command, "help")) {
- self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N | seek start|end|<ms>");
+ self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N (frames) | seek start|end|<ms>");
self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit");
if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes.");
return &.{};
@@ -145,10 +145,12 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" });
} else if (eq(command, "get")) {
const path = arg orelse return error.ExpectedField;
- const leaf = host.state.layout.find(path) orelse return error.UnknownField;
var buf: [160]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
- fields.format(leaf, host.live(), &w) catch {};
+ fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
+ error.UnknownField => return error.UnknownField,
+ error.WriteFailed => {}, // shown cut off
+ };
self.print("{s} = {s}", .{ path, w.buffered() });
} else if (eq(command, "set")) {
const path = arg orelse return error.ExpectedField;
@@ -176,16 +178,17 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
h.bank.save(index);
self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index});
} else {
- try h.bank.restore(index);
+ try h.restore(index);
self.print("Loaded snapshot {d}.", .{index});
}
} else if (eq(command, "record") or eq(command, "play")) {
const index = if (arg) |a| try slot(a, 0, timeline.recording_count - 1) else self.recording;
if (eq(command, "play")) _ = try h.bank.get(index);
h.stop(now);
- if (eq(command, "record")) try h.startRecording(index, self.snapshot, now) else try h.play(index, now);
+ if (eq(command, "record")) try h.startRecording(index, self.snapshot, now, host.build) else try h.play(index, now);
self.recording = index;
self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot });
+ if (eq(command, "play")) self.warnBuild(host, h.bank.recording(index));
} else if (eq(command, "stop")) {
h.stop(now);
} else if (eq(command, "pause")) {
@@ -197,6 +200,7 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
if (h.mode == .recording) h.stop(now);
if (h.mode == .live) try h.play(self.recording, now);
const r = try h.bank.get(h.selected);
+ if (h.mode == .playing and h.cursor == 0) self.warnBuild(host, r);
if (eq(command, "step")) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition);
if (eq(value, "start")) return h.seekCount(0);
if (eq(value, "end")) return h.seekCount(r.count);
@@ -206,7 +210,12 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot;
if (!h.bank.hasSnapshot(index)) return error.EmptySnapshot;
const diff = h.bank.compare(0, index);
- self.print("Live vs snapshot {d}: {d} differing bytes; first={any}, last={any}", .{ index, diff.count, diff.first, diff.last });
+ if (diff.first) |first| {
+ var buf: [96]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ first.leaf.name(first.offset, &w) catch {};
+ self.print("Live vs snapshot {d}: {d} differing values, first {s}", .{ index, diff.count, w.buffered() });
+ } else self.print("Live vs snapshot {d}: same", .{index});
} else {
// Sketch commands edit state outside the recorded input.
h.stop(now);
@@ -237,6 +246,11 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command),
try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } });
}
+/// A replay of a recording made by other code may diverge: say so.
+fn warnBuild(self: *Console, host: *const Host, r: *const timeline.Recording) void {
+ if (r.build() != 0 and host.build != 0 and r.build() != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ.");
+}
+
fn eq(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 7ebe54a..de19b99 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -6,8 +6,9 @@ const std = @import("std");
const c = @import("c");
const abi = @import("abi");
const memory = @import("memory.zig");
-const Timeline = @import("timeline.zig").Timeline;
-const mapRecordings = @import("timeline.zig").mapRecordings;
+const playback = @import("timeline.zig");
+const Timeline = playback.Timeline;
+const mapRecordings = playback.mapRecordings;
const gfx = @import("gfx.zig");
const sound = @import("audio.zig");
const Gpu = @import("gpu.zig");
@@ -44,6 +45,8 @@ passes: ?Gpu = null,
offscreen: ?*c.SDL_Texture = null,
pointer_cursor: ?*c.SDL_Cursor = null,
images: gfx.Images,
+/// Plays the 2D commands: targets, blend, antialiased shapes.
+painter: gfx.Painter,
audio: sound.Audio,
state: memory.StateFile,
session: memory.Session,
@@ -58,6 +61,9 @@ sketch: abi.Sketch,
library: ?Library = null,
watch: ?Watch = null,
reloads: usize = 0,
+/// Identifies the running build of the sketch (a hash of its library or
+/// executable file): recordings carry it, and `play` warns on a mismatch.
+build: u64 = 0,
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []const u8 = "",
@@ -73,6 +79,9 @@ canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
reloaded: bool = true,
+/// For `Input.jumped`: state changed other than by `update` since the
+/// last `draw` (a seek, a load, a `set`...). The first frame is one.
+jumped: bool = true,
started: bool = true,
last_now: u64 = 0,
/// Saved after the next frame is drawn (scripts).
@@ -115,8 +124,10 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
std.log.warn("no GPU renderer ({s}); drawing without one", .{c.SDL_GetError()});
renderer = c.SDL_CreateRenderer(window, null) orelse return sdlError("SDL_CreateRenderer");
}
- errdefer c.SDL_DestroyRenderer(renderer);
+ // Deferred in reverse: the renderer goes first, then the device it
+ // draws through (the other order crashed in SDL_DestroyRenderer).
errdefer if (gpu) |device| c.SDL_DestroyGPUDevice(device);
+ errdefer c.SDL_DestroyRenderer(renderer);
if (!options.headless) _ = c.SDL_SetRenderVSync(renderer, 1);
// Colors carry alpha: fills blend, as they do on the web.
_ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
@@ -142,6 +153,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
.renderer = renderer.?,
.gpu = gpu,
.images = .{ .gpa = gpa, .renderer = renderer.? },
+ .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null },
.audio = .{ .gpa = gpa },
.state = state,
.session = .init(gpa),
@@ -154,6 +166,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
.frame_arena = .init(gpa),
};
self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } };
+ self.painter.images = &self.images;
if (gpu) |device| self.passes = .init(gpa, device);
if (options.profile_gpu) if (self.passes) |*g| {
g.profile = .init(gpa);
@@ -164,6 +177,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
};
self.setCanvas(info.width, info.height);
_ = c.SDL_StartTextInput(self.window);
+ self.build = fileHash(options.library orelse "/proc/self/exe");
try self.adopt(sketch);
if (options.fresh) {
self.state.header().used = 0;
@@ -177,6 +191,7 @@ pub fn deinit(self: *Host) void {
if (self.watch) |w| w.deinit();
self.audio.deinit();
if (self.passes) |*g| g.deinit(&self.images);
+ self.painter.deinit();
self.images.deinit();
if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor);
if (self.offscreen) |texture| c.SDL_DestroyTexture(texture);
@@ -229,10 +244,10 @@ pub fn frame(self: *Host, now: u64) !void {
.playing => self.update(h.tick(now)),
.paused => {},
.live, .recording => {
- try self.pending.append(self.gpa, .{ .kind = .tick, .time = now, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) });
- for (self.pending.items) |e| h.capture(e) catch |err| self.print("Recording stopped: {t}", .{err});
- self.input.now = now;
- self.input.dt = dt;
+ // One frame: what was routed since the last one, then its tick.
+ // Recorded first, so `update` sees the times a replay will.
+ try self.pending.append(self.gpa, abi.Event.tick(now, dt));
+ h.capture(self.pending.items) catch |err| self.print("Recording stopped: {t}", .{err});
self.update(self.pending.items);
},
}
@@ -240,26 +255,60 @@ pub fn frame(self: *Host, now: u64) !void {
try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position);
}
-/// Feeds events to the sketch's deterministic `update`.
+/// Feeds whole frames to the sketch's deterministic `update`, one call per
+/// frame (events up to and including a tick), live or replayed alike.
pub fn update(self: *Host, events: []const abi.Event) void {
- // Input follows the events actually fed, live or replayed.
- for (events) |e| self.input.track(e);
- if (events.len > 0 and self.timeline.mode != .live and self.timeline.mode != .recording) self.input.now = events[events.len - 1].time;
- self.input.events = events;
- self.input.mode = self.timeline.mode;
- self.input.started = self.started;
- self.started = false;
- const ctx = self.context();
- self.sketch.update(&ctx, self.live().ptr);
+ var frames = playback.frames(events);
+ while (frames.next()) |one| {
+ // Input follows the events actually fed, frame by frame.
+ for (one) |e| self.input.track(e);
+ const tick = one[one.len - 1];
+ self.input.now = tick.time;
+ self.input.dt = tick.tickDt();
+ self.input.events = one;
+ self.input.mode = self.timeline.mode;
+ self.input.started = self.started;
+ self.started = false;
+ const ctx = self.context();
+ self.sketch.update(&ctx, self.live().ptr);
+ }
self.input.events = &.{};
}
+/// After live state was restored from a snapshot: the pointer, buttons and
+/// keys tracked so far belong to other bytes, so they start over. A new
+/// recording then begins with events that bring back what is held now, so
+/// its replay starts from the same input (they are fed and recorded as the
+/// first frame's first events).
+fn restoredInput(self: *Host, now: u64) !void {
+ const h = &self.timeline;
+ if (!h.restored) return;
+ h.restored = false;
+ const was = self.input;
+ self.input.mouse_x = 0;
+ self.input.mouse_y = 0;
+ self.input.buttons = 0;
+ self.input.keys = .empty;
+ if (h.mode != .recording or h.bank.recording(h.selected).count != 0) return;
+ var seed: std.ArrayList(abi.Event) = .empty;
+ defer seed.deinit(self.gpa);
+ if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y });
+ for (0..32) |bit| if (was.buttons & (@as(u32, 1) << @intCast(bit)) != 0) {
+ try seed.append(self.gpa, .{ .kind = .mouse_down, .time = now, .x = was.mouse_x, .y = was.mouse_y, .code = @intCast(bit + 1) });
+ };
+ var keys = was.keys.iterator(.{});
+ while (keys.next()) |key| try seed.append(self.gpa, .{ .kind = .key_down, .time = now, .code = @intCast(key) });
+ try self.pending.insertSlice(self.gpa, 0, seed.items);
+}
+
fn draw(self: *Host, now: u64) !void {
const arena = self.frame_arena.allocator();
self.input.now = now;
self.input.mode = self.timeline.mode;
self.input.reloaded = self.reloaded;
+ self.input.jumped = self.jumped or self.reloaded;
self.reloaded = false;
+ self.jumped = false;
self.input.console = self.console.visible;
self.input.width = @floatFromInt(self.canvas[0]);
self.input.height = @floatFromInt(self.canvas[1]);
@@ -286,9 +335,14 @@ fn draw(self: *Host, now: u64) !void {
_ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 255);
_ = c.SDL_RenderClear(self.renderer);
self.audio.beginFrame();
+ self.painter.begin(self.offscreen, self.canvas, arena);
var lines: std.ArrayList([]const u8) = .empty;
for (self.commands.items) |command| switch (command) {
- .canvas => |size| self.setCanvas(size.w, size.h),
+ .canvas => |size| {
+ self.painter.end();
+ self.setCanvas(size.w, size.h);
+ self.painter.begin(self.offscreen, self.canvas, arena);
+ },
.cursor => |kind| self.cursor = kind,
.voice => |voice| self.audio.declare(voice),
.audio => |a| self.audio.push(a.key, a.samples, a.clear),
@@ -300,11 +354,11 @@ fn draw(self: *Host, now: u64) !void {
.download => |d| if (self.passes) |*g| g.download(d) catch |err| self.print("gpu download: {t} ({s})", .{ err, c.SDL_GetError() }),
.open_file => |o| self.openFile(o.command, o.pattern),
.run => |line| try lines.append(arena, line),
- else => gfx.draw(self.renderer, &self.images, command),
+ else => self.painter.draw(command),
};
+ self.painter.end();
self.audio.endFrame();
for (lines.items) |line| self.runLine(line, now) catch {};
- _ = c.SDL_SetRenderClipRect(self.renderer, null);
var extra: std.ArrayList(abi.Command) = .empty;
if (self.console.overlay_memory) try overlay.drawMemory(&extra, arena, self.state.layout, self.live(), self.input.width);
@@ -313,7 +367,8 @@ fn draw(self: *Host, now: u64) !void {
try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas);
}
if (self.console.visible) try self.console.draw(self, &extra, arena);
- for (extra.items) |command| gfx.draw(self.renderer, &self.images, command);
+ for (extra.items) |command| self.painter.draw(command);
+ self.painter.end();
self.applyCursor();
if (self.screenshot) |path| {
@@ -432,11 +487,25 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
const replay = self.console.execute(self, line, now) catch |err| {
// The sketch has printed its own error already.
if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
+ if (self.timeline.restored) self.jumped = true;
+ try self.restoredInput(now);
return err;
};
+ if (self.timeline.restored or movesState(line)) self.jumped = true;
+ try self.restoredInput(now);
if (self.timeline.mode == .paused) self.update(replay);
}
+/// Whether a console line that succeeded may have changed State other than
+/// through `update` (restoring a snapshot is caught apart from this).
+fn movesState(line: []const u8) bool {
+ var words = std.mem.tokenizeAny(u8, line, " \t");
+ const verb = words.next() orelse return false;
+ const still = [_][]const u8{ "help", "overlay", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" };
+ for (still) |w| if (std.mem.eql(u8, verb, w)) return false;
+ return true;
+}
+
/// Offers a line to the sketch.
pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome {
self.input.now = now;
@@ -467,6 +536,7 @@ pub fn load(self: *Host, path: []const u8) !void {
if (self.library) |*old| old.close();
self.library = library;
self.reloads += 1;
+ self.build = fileHash(path);
self.print("reload {d}: {s}", .{ self.reloads, path });
}
@@ -636,6 +706,14 @@ fn consoleKey(e: abi.Event) ?Console.Key {
};
}
+/// A hash of a file's bytes; 0 when it cannot be read.
+fn fileHash(path: []const u8) u64 {
+ const bytes = memory.mapReadOnly(path);
+ if (bytes.len == 0) return 0;
+ defer std.posix.munmap(bytes);
+ return std.hash.Wyhash.hash(0, bytes) | 1;
+}
+
fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
return environ.get("XDG_RUNTIME_DIR") orelse "/tmp";
}
diff --git a/src/host/fields.zig b/src/host/fields.zig
index ba8fc03..2e70414 100644
--- a/src/host/fields.zig
+++ b/src/host/fields.zig
@@ -2,7 +2,82 @@
//! Shared by the console, the memory overlay, scripts and the probe.
const std = @import("std");
const abi = @import("abi");
-const Leaf = @import("memory.zig").Layout.Leaf;
+const Layout = @import("memory.zig").Layout;
+const Leaf = Layout.Leaf;
+
+/// Writes what `path` names: one value for a number, bool or enum leaf,
+/// or every leaf under it for an array, a vector or a struct, in memory
+/// order (for a Zig struct not always the declared one): `{ 250, 3 }`
+/// when they are its elements, otherwise `{ .count = 12, .hz = 60 }` or
+/// `{ [0].x = 1, [1].x = 2 }`.
+/// Shows the first `max_values`, then how many more there are.
+pub fn formatPath(layout: Layout, memory: []const u8, path: []const u8, w: *std.Io.Writer) (std.Io.Writer.Error || error{UnknownField})!void {
+ if (layout.find(path)) |leaf| if (!leaf.whole()) return format(leaf, memory, w);
+ // Names under `path`, found leaf by leaf; sorted by offset afterwards.
+ const Found = struct { offset: usize, leaf: Leaf };
+ var found: [max_values]Found = undefined;
+ var count: usize = 0;
+ var total: usize = 0;
+ var plain = true;
+ var name_buf: [256]u8 = undefined;
+ for (layout.fields) |leaf| {
+ if (leaf.whole()) continue;
+ var it = leaf.elements();
+ while (it.next()) |offset| {
+ var nw: std.Io.Writer = .fixed(&name_buf);
+ leaf.name(offset, &nw) catch continue;
+ const name = nw.buffered();
+ if (!under(name, path)) continue;
+ total += 1;
+ if (!isIndex(name[path.len..])) plain = false;
+ if (count < max_values) {
+ found[count] = .{ .offset = offset, .leaf = leaf };
+ count += 1;
+ } else {
+ // Keep the lowest offsets.
+ var highest: usize = 0;
+ for (found[1..], 1..) |f, i| if (f.offset > found[highest].offset) {
+ highest = i;
+ };
+ if (offset < found[highest].offset) found[highest] = .{ .offset = offset, .leaf = leaf };
+ }
+ }
+ }
+ if (total == 0) return error.UnknownField;
+ std.mem.sortUnstable(Found, found[0..count], {}, struct {
+ fn less(_: void, a: Found, b: Found) bool {
+ return a.offset < b.offset;
+ }
+ }.less);
+ try w.writeAll("{ ");
+ for (found[0..count], 0..) |f, i| {
+ if (i > 0) try w.writeAll(", ");
+ if (!plain) {
+ var nw: std.Io.Writer = .fixed(&name_buf);
+ f.leaf.name(f.offset, &nw) catch {};
+ try w.print("{s} = ", .{nw.buffered()[path.len..]});
+ }
+ try format(f.leaf.at(f.offset), memory, w);
+ }
+ if (total > count) try w.print(", ... {d} more", .{total - count});
+ try w.writeAll(" }");
+}
+
+pub const max_values = 64;
+
+/// `name` is `path` itself or a field or element inside it.
+fn under(name: []const u8, path: []const u8) bool {
+ if (!std.mem.startsWith(u8, name, path)) return false;
+ if (name.len == path.len) return true;
+ return name[path.len] == '.' or name[path.len] == '[';
+}
+
+/// `[3]`: one index and nothing more.
+fn isIndex(suffix: []const u8) bool {
+ if (suffix.len < 3 or suffix[0] != '[' or suffix[suffix.len - 1] != ']') return false;
+ for (suffix[1 .. suffix.len - 1]) |ch| if (!std.ascii.isDigit(ch)) return false;
+ return true;
+}
pub fn format(leaf: Leaf, memory: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void {
const bytes = leaf.bytes(memory);
@@ -64,6 +139,22 @@ pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool {
return false;
}
+/// A number, bool or enum leaf's value as a float; null for other kinds.
+pub fn number(leaf: Leaf, memory: []const u8) ?f64 {
+ const bytes = leaf.bytes(memory);
+ return switch (leaf.kind) {
+ .int, .@"enum" => @floatFromInt(readInt(i64, bytes)),
+ .uint => @floatFromInt(readInt(u64, bytes)),
+ .bool => if (bytes[0] != 0) 1 else 0,
+ .float => switch (leaf.size) {
+ 4 => @as(f32, @bitCast(bytes[0..4].*)),
+ 8 => @as(f64, @bitCast(bytes[0..8].*)),
+ else => null,
+ },
+ else => null,
+ };
+}
+
pub fn readInt(comptime T: type, bytes: []const u8) T {
const n: usize = @min(bytes.len, 8);
const value = std.mem.readVarInt(u64, bytes[0..n], .little);
@@ -114,3 +205,47 @@ test "fields format, parse and compare by kind" {
try std.testing.expect(s.on);
try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana"));
}
+
+test "indexed paths reach array elements and vector lanes" {
+ const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, boids: struct { buffer: [4]struct { pos: [2]f32 = .{ 0, 0 }, mood: enum(u8) { calm = 1, wild = 2 } = .calm } = @splat(.{}), len: u32 = 0 } = .{} };
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const layout = try @import("memory.zig").Layout.copy(arena.allocator(), abi.layout.of(S, .state));
+ var s: S = .{};
+ const bytes = std.mem.asBytes(&s);
+ try std.testing.expect(matches(layout.find("pos[0]").?, bytes, "250"));
+ try std.testing.expectEqual(@as(?f64, 3), number(layout.find("pos[1]").?, bytes));
+ try set(layout.find("boids.buffer[3].pos[1]").?, bytes, "20.5");
+ try std.testing.expectEqual(@as(f32, 20.5), s.boids.buffer[3].pos[1]);
+ try set(layout.find("boids.buffer[2].mood").?, bytes, "wild");
+ try std.testing.expectEqual(.wild, s.boids.buffer[2].mood);
+ try std.testing.expect(layout.find("boids.buffer[4].mood") == null);
+ try std.testing.expect(layout.find("pos[2]") == null);
+}
+
+test "paths to vectors, arrays and structs print every value under them" {
+ const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, clock: struct { hz: f32 = 60, count: u64 = 12 } = .{}, list: struct { buffer: [3]struct { x: i32 = 1, on: bool = true } = @splat(.{}), len: u32 = 2 } = .{}, big: [100]u8 = @splat(7) };
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state));
+ var s: S = .{};
+ s.list.buffer[1].x = -4;
+ const bytes = std.mem.asBytes(&s);
+ var buf: [1024]u8 = undefined;
+ const cases = [_][2][]const u8{
+ .{ "pos", "{ 250, 3 }" },
+ .{ "pos[1]", "3" },
+ .{ "clock", "{ .count = 12, .hz = 60 }" }, // memory order
+ .{ "list.buffer[1]", "{ .x = -4, .on = true }" },
+ .{ "list.buffer", "{ [0].x = 1, [0].on = true, [1].x = -4, [1].on = true, [2].x = 1, [2].on = true }" },
+ };
+ for (cases) |case| {
+ var w: std.Io.Writer = .fixed(&buf);
+ try formatPath(layout, bytes, case[0], &w);
+ try std.testing.expectEqualStrings(case[1], w.buffered());
+ }
+ var w: std.Io.Writer = .fixed(&buf);
+ try formatPath(layout, bytes, "big", &w);
+ try std.testing.expect(std.mem.endsWith(u8, w.buffered(), "7, 7, ... 36 more }"));
+ try std.testing.expectError(error.UnknownField, formatPath(layout, bytes, "po", &w));
+}
diff --git a/src/host/gfx.zig b/src/host/gfx.zig
index 16148a6..20b4dcc 100644
--- a/src/host/gfx.zig
+++ b/src/host/gfx.zig
@@ -14,10 +14,29 @@ pub const Images = struct {
texture: ?*c.SDL_Texture = null,
w: u32 = 0,
h: u32 = 0,
+ /// Holds premultiplied colour: a target drawn into, a GPU pass's
+ /// output, or premultiplied `pixels`.
+ premultiplied: bool = false,
+ /// Made by `new`: a render target for `Command.target`.
+ target: bool = false,
+ /// Scales smoothly (GPU pass output), not nearest.
+ smooth: bool = false,
+ /// A target's supersampled self (`factor` times the size), which
+ /// 2D commands draw into; `texture` is its average, brought up to
+ /// date (`stale`) before the image is drawn.
+ big: ?*c.SDL_Texture = null,
+ factor: u32 = 1,
+ stale: bool = false,
+
+ fn release(entry: *Entry) void {
+ if (entry.texture) |t| c.SDL_DestroyTexture(t);
+ if (entry.big) |t| c.SDL_DestroyTexture(t);
+ entry.* = .{};
+ }
};
pub fn deinit(self: *Images) void {
- for (self.entries.items) |entry| if (entry.texture) |t| c.SDL_DestroyTexture(t);
+ for (self.entries.items) |*entry| entry.release();
self.entries.deinit(self.gpa);
var keys = self.paths.keyIterator();
while (keys.next()) |key| self.gpa.free(key.*);
@@ -41,10 +60,20 @@ pub const Images = struct {
return self.add(c.SDL_LoadPNG_IO(io, true));
}
+ /// A blank (transparent) image, which `Command.pixels` fills and
+ /// `Command.target` draws into: a render target, cleared now, since a
+ /// new SDL texture's contents are undefined (a canvas starts clear).
pub fn new(self: *Images, w: u32, h: u32) abi.Image {
- const texture = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_STREAMING, @intCast(w), @intCast(h));
- if (texture) |t| setup(t);
- return self.append(.{ .texture = texture, .w = w, .h = h });
+ const texture = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(w), @intCast(h));
+ if (texture) |t| {
+ setup(t);
+ const previous = c.SDL_GetRenderTarget(self.renderer);
+ _ = c.SDL_SetRenderTarget(self.renderer, t);
+ _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 0);
+ _ = c.SDL_RenderClear(self.renderer);
+ _ = c.SDL_SetRenderTarget(self.renderer, previous);
+ }
+ return self.append(.{ .texture = texture, .w = w, .h = h, .premultiplied = true, .target = texture != null });
}
/// Makes `image` show a GPU render target (GPU renderer only).
@@ -59,9 +88,8 @@ pub const Images = struct {
const texture = c.SDL_CreateTextureWithProperties(self.renderer, props) orelse return error.WrapTexture;
// Rendered output: smooth scaling, and already premultiplied.
_ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_LINEAR);
- _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND_PREMULTIPLIED);
- if (entry.texture) |old| c.SDL_DestroyTexture(old);
- entry.* = .{ .texture = texture, .w = w, .h = h };
+ entry.release();
+ entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true };
}
/// Stops showing a wrapped render target, before the target goes away.
@@ -73,8 +101,7 @@ pub const Images = struct {
pub fn free(self: *Images, image: abi.Image) void {
const entry = self.get(image) orelse return;
- if (entry.texture) |t| c.SDL_DestroyTexture(t);
- entry.* = .{};
+ entry.release();
}
pub fn size(self: *Images, image: abi.Image) [2]u32 {
@@ -104,47 +131,397 @@ pub const Images = struct {
fn setup(texture: *c.SDL_Texture) void {
_ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_NEAREST);
- _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND);
}
};
-/// Draws one graphics command. Other commands are not graphics: ignored.
-pub fn draw(renderer: *c.SDL_Renderer, images: *Images, command: abi.Command) void {
- switch (command) {
- .clear => |color| {
- if (@import("builtin").os.tag == .linux) c.sk_text_begin_frame(renderer);
- setColor(renderer, color);
- _ = c.SDL_RenderClear(renderer);
- },
- .rect => |r| {
- setColor(renderer, r.color);
- _ = c.SDL_RenderFillRect(renderer, &frect(r.dst));
- },
- .image => |img| {
- const entry = images.get(img.image);
- const texture = if (entry) |e| e.texture else null;
- const t = texture orelse return missing(renderer, img.dst);
- _ = c.SDL_SetTextureColorMod(t, img.tint.r, img.tint.g, img.tint.b);
- _ = c.SDL_SetTextureAlphaMod(t, img.tint.a);
- const src = frect(img.src);
- _ = c.SDL_RenderTexture(renderer, t, if (img.src.w > 0) &src else null, &frect(img.dst));
- },
- .text => |text| drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color),
- .clip => |clip| {
- if (clip) |r| {
- const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) };
- _ = c.SDL_SetRenderClipRect(renderer, &rect);
- } else _ = c.SDL_SetRenderClipRect(renderer, null);
- },
- .pixels => |p| {
- const entry = images.get(p.image) orelse return;
- const texture = entry.texture orelse return;
- if (p.w != entry.w or p.h != entry.h or p.rgba.len < @as(usize, p.w) * p.h * 4) return;
- _ = c.SDL_SetTextureBlendMode(texture, if (p.premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND);
- _ = c.SDL_UpdateTexture(texture, null, p.rgba.ptr, @intCast(p.w * 4));
- },
- else => {},
+/// Plays 2D commands into the renderer, keeping what they leave behind
+/// (target, blend) and the antialiasing textures. One per host; `begin`
+/// and `end` bracket a frame.
+///
+/// Antialiasing (with a GPU renderer) is supersampling, 4x4 samples a
+/// pixel, averaged by halving twice (bilinear sampling at the centre of a
+/// 2x2 block is their exact mean), so coverage resolves per sample:
+/// - On the canvas, consecutive shapes are drawn into `layer` and
+/// composited together, premultiplied, when another command comes.
+/// - A target is supersampled whole (`Entry.big`): everything drawn into
+/// it is, and it is averaged when drawn. Its picture is therefore the
+/// same however its commands were split into frames, so a trail
+/// repainted at once after a seek equals the one painted step by step.
+pub const Painter = struct {
+ renderer: *c.SDL_Renderer,
+ images: *Images,
+ /// The canvas's render target: null for the window, or the headless
+ /// host's offscreen texture.
+ canvas: ?*c.SDL_Texture = null,
+ canvas_size: [2]u32 = .{ 0, 0 },
+ /// Antialias (a GPU renderer); false draws everything aliased.
+ smooth: bool = false,
+ /// Per-vertex colours, for one frame.
+ arena: std.mem.Allocator = undefined,
+ target: abi.Image = .none,
+ blend: abi.BlendMode = .alpha,
+ layer: Layer = .{},
+ /// Half-way through averaging (2x), shared; `half_size` in its pixels.
+ half: ?*c.SDL_Texture = null,
+ half_size: [2]u32 = .{ 0, 0 },
+
+ const Layer = struct {
+ big: ?*c.SDL_Texture = null,
+ /// Room in `big`, in its pixels.
+ w: u32 = 0,
+ h: u32 = 0,
+ /// Open: shapes went into it since the last composite.
+ open: bool = false,
+ blend: abi.BlendMode = .alpha,
+ factor: u32 = 4,
+ /// What the open layer's shapes cover, in canvas pixels (x0, y0,
+ /// x1, y1); after a composite, what still holds them, cleared
+ /// when the next layer opens.
+ dirty: [4]u32 = .{ 0, 0, 0, 0 },
+ };
+
+ /// 16 samples a pixel, unless that takes more than 16 Mi of them; 4,
+ /// then; else none.
+ const max_samples = 16 << 20;
+
+ fn factorFor(size: [2]u32) u32 {
+ const pixels = @as(u64, size[0]) * size[1];
+ return if (pixels * 16 <= max_samples) 4 else if (pixels * 4 <= max_samples) 2 else 1;
+ }
+
+ pub fn deinit(p: *Painter) void {
+ if (p.layer.big) |t| c.SDL_DestroyTexture(t);
+ if (p.half) |t| c.SDL_DestroyTexture(t);
+ p.layer = .{};
+ p.half = null;
+ p.half_size = .{ 0, 0 };
+ }
+
+ pub fn begin(p: *Painter, canvas: ?*c.SDL_Texture, size: [2]u32, arena: std.mem.Allocator) void {
+ p.canvas = canvas;
+ p.canvas_size = size;
+ p.arena = arena;
+ p.target = .none;
+ p.blend = .alpha;
+ }
+
+ /// Back to the canvas, blending alpha, unclipped: where overlays draw
+ /// and screenshots read.
+ pub fn end(p: *Painter) void {
+ p.flush();
+ if (p.target != .none) {
+ p.target = .none;
+ _ = c.SDL_SetRenderTarget(p.renderer, p.canvas);
+ }
+ p.blend = .alpha;
+ _ = c.SDL_SetRenderClipRect(p.renderer, null);
+ }
+
+ /// Draws one graphics command. Other commands are not graphics: ignored.
+ pub fn draw(p: *Painter, command: abi.Command) void {
+ if (command != .shape) p.flush();
+ const renderer = p.renderer;
+ switch (command) {
+ .clear => |color| {
+ if (@import("builtin").os.tag == .linux and p.target == .none) c.sk_text_begin_frame(renderer);
+ // A target holds premultiplied colour, as a canvas cleared
+ // to a translucent colour does.
+ setColor(renderer, if (p.target == .none) color else premultiply(color));
+ _ = c.SDL_RenderClear(renderer);
+ },
+ .rect => |r| {
+ setColor(renderer, r.color);
+ _ = c.SDL_SetRenderDrawBlendMode(renderer, drawBlend(p.blend));
+ _ = c.SDL_RenderFillRect(renderer, &frect(r.dst));
+ },
+ .shape => |s| p.shape(s.color, s.points, s.ends, s.indices, s.colors),
+ .image => |img| p.drawImage(img.image, img.dst, img.src, img.tint, img.corners),
+ .text => |text| {
+ _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
+ drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color);
+ },
+ .clip => |clip| {
+ if (clip) |r| {
+ const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) };
+ _ = c.SDL_SetRenderClipRect(renderer, &rect);
+ } else _ = c.SDL_SetRenderClipRect(renderer, null);
+ },
+ .pixels => |px| {
+ const entry = p.images.get(px.image) orelse return;
+ const texture = entry.texture orelse return;
+ if (px.w != entry.w or px.h != entry.h or px.rgba.len < @as(usize, px.w) * px.h * 4) return;
+ entry.premultiplied = px.premultiplied;
+ _ = c.SDL_UpdateTexture(texture, null, px.rgba.ptr, @intCast(px.w * 4));
+ if (entry.big != null) p.spread(entry);
+ },
+ .target => |img| p.setTarget(img),
+ .blend => |mode| p.blend = mode,
+ else => {},
+ }
+ }
+
+ fn setTarget(p: *Painter, handle: abi.Image) void {
+ const texture = if (handle == .none) p.canvas else blk: {
+ const entry = p.images.get(handle) orelse return;
+ if (!entry.target or entry.texture == null) return;
+ if (entry.big == null and p.smooth) p.supersample(entry);
+ entry.stale = entry.big != null;
+ break :blk entry.big orelse entry.texture;
+ };
+ p.target = handle;
+ _ = c.SDL_SetRenderTarget(p.renderer, texture);
+ _ = c.SDL_SetRenderClipRect(p.renderer, null);
+ }
+
+ /// Gives a target its supersampled self, holding what it shows now.
+ fn supersample(p: *Painter, entry: *Images.Entry) void {
+ const factor = factorFor(.{ entry.w, entry.h });
+ if (factor == 1) return;
+ const big = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(entry.w * factor), @intCast(entry.h * factor)) orelse return;
+ _ = c.SDL_SetTextureScaleMode(big, c.SDL_SCALEMODE_LINEAR);
+ entry.big = big;
+ entry.factor = factor;
+ const f: f32 = @floatFromInt(factor);
+ const previous = c.SDL_GetRenderTarget(p.renderer);
+ _ = c.SDL_SetRenderTarget(p.renderer, big);
+ _ = c.SDL_SetRenderScale(p.renderer, f, f);
+ _ = c.SDL_SetRenderTarget(p.renderer, previous);
+ p.spread(entry);
+ }
+
+ /// Copies a target's `texture` into its supersampled self (after
+ /// `pixels` replaced it), each pixel into its samples.
+ fn spread(p: *Painter, entry: *Images.Entry) void {
+ const previous = c.SDL_GetRenderTarget(p.renderer);
+ _ = c.SDL_SetRenderTarget(p.renderer, entry.big);
+ const t = entry.texture.?;
+ _ = c.SDL_SetTextureBlendMode(t, c.SDL_BLENDMODE_NONE);
+ _ = c.SDL_SetTextureColorMod(t, 255, 255, 255);
+ _ = c.SDL_SetTextureAlphaMod(t, 255);
+ _ = c.SDL_RenderTexture(p.renderer, t, null, &.{ .x = 0, .y = 0, .w = @floatFromInt(entry.w), .h = @floatFromInt(entry.h) });
+ _ = c.SDL_SetRenderTarget(p.renderer, previous);
+ entry.stale = false;
+ }
+
+ /// Brings a target's `texture` up to date: its samples averaged.
+ fn resolve(p: *Painter, entry: *Images.Entry) void {
+ entry.stale = false;
+ const previous = c.SDL_GetRenderTarget(p.renderer);
+ p.average(entry.big.?, entry.factor, .{ 0, 0, entry.w, entry.h }, entry.texture.?, c.SDL_BLENDMODE_NONE);
+ _ = c.SDL_SetRenderTarget(p.renderer, previous);
+ }
+
+ /// Draws `box` (destination pixels) of `from`, `factor` times larger,
+ /// averaged into `to` with `blend`. Leaves `to` the render target.
+ fn average(p: *Painter, from: *c.SDL_Texture, factor: u32, box: [4]u32, to: ?*c.SDL_Texture, blend: c.SDL_BlendMode) void {
+ var source = from;
+ var k: f32 = @floatFromInt(factor);
+ if (factor == 4) half: {
+ const need: [2]u32 = .{ box[2] * 2, box[3] * 2 };
+ if (p.half == null or p.half_size[0] < need[0] or p.half_size[1] < need[1]) {
+ if (p.half) |t| c.SDL_DestroyTexture(t);
+ const size: [2]u32 = .{ @max(need[0], p.half_size[0]), @max(need[1], p.half_size[1]) };
+ p.half = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(size[0]), @intCast(size[1]));
+ p.half_size = if (p.half != null) size else .{ 0, 0 };
+ if (p.half) |t| _ = c.SDL_SetTextureScaleMode(t, c.SDL_SCALEMODE_LINEAR) else break :half;
+ }
+ _ = c.SDL_SetRenderTarget(p.renderer, p.half);
+ plain(from, c.SDL_BLENDMODE_NONE);
+ _ = c.SDL_RenderTexture(p.renderer, from, &frect(scaledBox(box, 4)), &frect(scaledBox(box, 2)));
+ source = p.half.?;
+ k = 2;
+ }
+ _ = c.SDL_SetRenderTarget(p.renderer, to);
+ plain(source, blend);
+ _ = c.SDL_RenderTexture(p.renderer, source, &frect(scaledBox(box, k)), &frect(scaledBox(box, 1)));
+ }
+
+ /// The current destination's size in its own pixels.
+ fn destinationSize(p: *Painter) [2]u32 {
+ if (p.target == .none) return p.canvas_size;
+ const entry = p.images.get(p.target) orelse return p.canvas_size;
+ return .{ entry.w, entry.h };
+ }
+
+ fn drawImage(p: *Painter, handle: abi.Image, dst: abi.Rect, src_rect: abi.Rect, tint: abi.Color, corners: ?abi.Corners) void {
+ const renderer = p.renderer;
+ const entry = p.images.get(handle);
+ const texture = if (entry) |e| e.texture else null;
+ const t = texture orelse return missing(renderer, dst);
+ const e = entry.?;
+ if (handle == p.target) return; // Drawing into itself: nothing.
+ if (e.stale) p.resolve(e);
+ // A premultiplied texture needs its colour scaled by the tint's
+ // alpha too, which SDL's alpha mod does not do.
+ const scale: u32 = if (e.premultiplied) tint.a else 255;
+ _ = c.SDL_SetTextureColorMod(t, @intCast(@as(u32, tint.r) * scale / 255), @intCast(@as(u32, tint.g) * scale / 255), @intCast(@as(u32, tint.b) * scale / 255));
+ _ = c.SDL_SetTextureAlphaMod(t, tint.a);
+ _ = c.SDL_SetTextureBlendMode(t, textureBlend(p.blend, e.premultiplied));
+ const src = frect(src_rect);
+ const srcp = if (src_rect.w > 0) &src else null;
+ if (corners) |q| {
+ const origin: c.SDL_FPoint = .{ .x = q.top_left[0], .y = q.top_left[1] };
+ const right: c.SDL_FPoint = .{ .x = q.top_right[0], .y = q.top_right[1] };
+ const down: c.SDL_FPoint = .{ .x = q.bottom_left[0], .y = q.bottom_left[1] };
+ _ = c.SDL_RenderTextureAffine(renderer, t, srcp, &origin, &right, &down);
+ } else _ = c.SDL_RenderTexture(renderer, t, srcp, &frect(dst));
+ }
+
+ /// `Command.shape`: its triangles in one geometry call, one colour for
+ /// every vertex (stride 0, nothing copied) or each subpath's. The
+ /// subpaths are for the web; native needs only the triangles.
+ fn shape(p: *Painter, color: abi.Color, points: []const [2]f32, ends: []const u32, indices: []const u32, colors: []const abi.Color) void {
+ const count = indices.len - indices.len % 3;
+ if (count == 0 or points.len == 0 or points.len > std.math.maxInt(c_int) or count > std.math.maxInt(c_int)) return;
+ for (indices[0..count]) |i| if (i >= points.len) return;
+ var one = fcolor(color);
+ var vertex_colors: []const c.SDL_FColor = (&one)[0..1];
+ var stride: c_int = 0;
+ if (colors.len > 0) {
+ const each = p.arena.alloc(c.SDL_FColor, points.len) catch return;
+ @memset(each, one);
+ var start: usize = 0;
+ for (ends, 0..) |subpath_end, i| {
+ if (i >= colors.len) break;
+ const stop = @min(subpath_end, points.len);
+ if (stop > start) @memset(each[start..stop], fcolor(colors[i]));
+ start = @max(start, stop);
+ }
+ vertex_colors = each;
+ stride = @sizeOf(c.SDL_FColor);
+ }
+ // A supersampled target takes shapes as they are; the canvas
+ // through the layer.
+ if (p.target == .none and p.smooth) {
+ const box = bounds(points, indices[0..count], p.canvas_size) orelse return;
+ if (!p.openLayer(box)) return;
+ }
+ _ = c.SDL_SetRenderDrawBlendMode(p.renderer, drawBlend(p.blend));
+ _ = c.SDL_RenderGeometryRaw(p.renderer, null, @ptrCast(points.ptr), @sizeOf([2]f32), vertex_colors.ptr, stride, null, 0, @intCast(points.len), indices.ptr, @intCast(count), @sizeOf(u32));
+ }
+
+ /// Makes the layer the render target for a shape covering `box`
+ /// (canvas pixels): the open one, if for this blend, else a new one.
+ /// False if there is no room for one (the shape is then drawn on the
+ /// canvas, aliased).
+ fn openLayer(p: *Painter, box: [4]u32) bool {
+ const l = &p.layer;
+ if (l.open and l.blend == p.blend) {
+ l.dirty = .{ @min(l.dirty[0], box[0]), @min(l.dirty[1], box[1]), @max(l.dirty[2], box[2]), @max(l.dirty[3], box[3]) };
+ return true;
+ }
+ p.flush();
+ const size = p.canvas_size;
+ const factor = factorFor(size);
+ if (factor == 1) return true;
+ const w = size[0] * factor;
+ const h = size[1] * factor;
+ if (l.big == null or l.w < w or l.h < h) {
+ if (l.big) |t| c.SDL_DestroyTexture(t);
+ l.* = .{ .w = w, .h = h };
+ l.big = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(w), @intCast(h));
+ const big = l.big orelse {
+ std.log.warn("no antialiasing layer: {s}", .{c.SDL_GetError()});
+ p.smooth = false;
+ return true;
+ };
+ _ = c.SDL_SetTextureScaleMode(big, c.SDL_SCALEMODE_LINEAR);
+ // Cleared whole once; afterwards only what a composite left.
+ _ = c.SDL_SetRenderTarget(p.renderer, big);
+ _ = c.SDL_SetRenderDrawColor(p.renderer, 0, 0, 0, 0);
+ _ = c.SDL_RenderClear(p.renderer);
+ }
+ _ = c.SDL_SetRenderTarget(p.renderer, l.big);
+ const f: f32 = @floatFromInt(factor);
+ _ = c.SDL_SetRenderScale(p.renderer, f, f);
+ if (l.dirty[2] > l.dirty[0]) {
+ // The last layer's shapes, gone: at the scale it drew them.
+ const old: f32 = @floatFromInt(l.factor);
+ _ = c.SDL_SetRenderDrawBlendMode(p.renderer, c.SDL_BLENDMODE_NONE);
+ _ = c.SDL_SetRenderDrawColor(p.renderer, 0, 0, 0, 0);
+ _ = c.SDL_RenderFillRect(p.renderer, &frect(scaledBox(l.dirty, old / f)));
+ }
+ l.factor = factor;
+ l.blend = p.blend;
+ l.open = true;
+ l.dirty = box;
+ return true;
+ }
+
+ /// Composites an open layer onto the canvas: the rect its shapes
+ /// cover, nothing else.
+ fn flush(p: *Painter) void {
+ const l = &p.layer;
+ if (!l.open) return;
+ l.open = false;
+ p.average(l.big.?, l.factor, l.dirty, p.canvas, textureBlend(l.blend, true));
+ }
+};
+
+/// A texture drawn as it is: no tint, `blend`.
+fn plain(t: *c.SDL_Texture, blend: c.SDL_BlendMode) void {
+ _ = c.SDL_SetTextureBlendMode(t, blend);
+ _ = c.SDL_SetTextureColorMod(t, 255, 255, 255);
+ _ = c.SDL_SetTextureAlphaMod(t, 255);
+}
+
+/// The pixels a shape's triangles may touch, one pixel around, clamped to
+/// the destination: null if none.
+fn bounds(points: []const [2]f32, indices: []const u32, size: [2]u32) ?[4]u32 {
+ var lo: [2]f32 = .{ std.math.inf(f32), std.math.inf(f32) };
+ var hi: [2]f32 = .{ -std.math.inf(f32), -std.math.inf(f32) };
+ for (indices) |i| for (0..2) |axis| {
+ lo[axis] = @min(lo[axis], points[i][axis]);
+ hi[axis] = @max(hi[axis], points[i][axis]);
+ };
+ var box: [4]u32 = undefined;
+ for (0..2) |axis| {
+ const limit: f32 = @floatFromInt(size[axis]);
+ const a = std.math.clamp(@floor(lo[axis]) - 1, 0, limit);
+ const b = std.math.clamp(@ceil(hi[axis]) + 1, 0, limit);
+ if (!(b > a)) return null; // off the destination, or NaN
+ box[axis] = @intFromFloat(a);
+ box[axis + 2] = @intFromFloat(b);
}
+ return box;
+}
+
+/// `box` (x0, y0, x1, y1) times `k`, as a rect.
+fn scaledBox(box: [4]u32, k: f32) abi.Rect {
+ const x: f32 = @floatFromInt(box[0]);
+ const y: f32 = @floatFromInt(box[1]);
+ return .{ .x = x * k, .y = y * k, .w = @as(f32, @floatFromInt(box[2] - box[0])) * k, .h = @as(f32, @floatFromInt(box[3] - box[1])) * k };
+}
+
+/// Adds colour times alpha, and alpha, as canvas `lighter` does (SDL's
+/// `ADD` keeps the destination's alpha).
+fn addBlend(premultiplied: bool) c.SDL_BlendMode {
+ const src: c.SDL_BlendFactor = if (premultiplied) c.SDL_BLENDFACTOR_ONE else c.SDL_BLENDFACTOR_SRC_ALPHA;
+ return c.SDL_ComposeCustomBlendMode(src, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDOPERATION_ADD, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDOPERATION_ADD);
+}
+
+/// Solid colours (straight alpha) onto the destination.
+fn drawBlend(blend: abi.BlendMode) c.SDL_BlendMode {
+ return switch (blend) {
+ .alpha => c.SDL_BLENDMODE_BLEND,
+ .add => addBlend(false),
+ };
+}
+
+fn textureBlend(blend: abi.BlendMode, premultiplied: bool) c.SDL_BlendMode {
+ return switch (blend) {
+ .alpha => if (premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND,
+ .add => addBlend(premultiplied),
+ };
+}
+
+fn fcolor(color: abi.Color) c.SDL_FColor {
+ return .{
+ .r = @as(f32, @floatFromInt(color.r)) / 255,
+ .g = @as(f32, @floatFromInt(color.g)) / 255,
+ .b = @as(f32, @floatFromInt(color.b)) / 255,
+ .a = @as(f32, @floatFromInt(color.a)) / 255,
+ };
}
/// Native shaped text on Linux, using a 13px monospace face at scale 1.
@@ -178,7 +555,13 @@ pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []
if (clipped and s != 1) _ = c.SDL_SetRenderClipRect(renderer, &clip);
}
+fn premultiply(color: abi.Color) abi.Color {
+ const a: u32 = color.a;
+ return .{ .r = @intCast((color.r * a + 127) / 255), .g = @intCast((color.g * a + 127) / 255), .b = @intCast((color.b * a + 127) / 255), .a = color.a };
+}
+
fn missing(renderer: *c.SDL_Renderer, dst: abi.Rect) void {
+ _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
setColor(renderer, .{ .r = 110, .g = 30, .b = 70 });
_ = c.SDL_RenderFillRect(renderer, &frect(dst));
drawText(renderer, dst.x + 4, dst.y + 4, 1, "missing image", .{ .r = 255, .g = 210, .b = 240 });
diff --git a/src/host/gpu.zig b/src/host/gpu.zig
index 9c77205..94b2e39 100644
--- a/src/host/gpu.zig
+++ b/src/host/gpu.zig
@@ -119,6 +119,10 @@ const Target = struct {
texture: *c.SDL_GPUTexture,
samples: u8 = 1,
msaa: ?*c.SDL_GPUTexture = null,
+ /// Not rendered into yet: undefined natively, so the first pass that
+ /// would load clears to zero (WebGPU's starting contents).
+ fresh: bool = true,
+ msaa_fresh: bool = true,
stencil_samples: u8 = 0,
stencil: ?*c.SDL_GPUTexture = null,
};
@@ -187,6 +191,12 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void {
if (pass.width == 0 or pass.height == 0 or pass.draws.len == 0 and pass.clear == null) return;
const samples = g.supportedSamples(pass.samples);
const t = try g.renderTarget(images, pass.image, pass.width, pass.height, samples, pass.stencil);
+ // Each pipeline is looked up on first use in the pass, not per draw:
+ // the lookup hashes the shaders' code. Outer null: not looked up yet;
+ // inner null: it failed (warned once).
+ const built = try g.gpa.alloc(??*c.SDL_GPUGraphicsPipeline, pass.pipelines.len);
+ defer g.gpa.free(built);
+ @memset(built, null);
const start = g.startTiming();
// Every draw's vertices go up in one copy.
@@ -210,16 +220,23 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void {
const clear = pass.clear orelse .{ 0, 0, 0, 0 };
var color: c.SDL_GPUColorTargetInfo = std.mem.zeroes(c.SDL_GPUColorTargetInfo);
color.clear_color = .{ .r = clear[0], .g = clear[1], .b = clear[2], .a = clear[3] };
- // A multisampled pass cannot load resolved pixels: it always clears.
- color.load_op = if (pass.clear != null or samples > 1) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD;
+ // `clear = null` keeps what the attachment holds, as on the web: a
+ // multisampled pass loads its multisampled attachment, which every
+ // pass therefore stores as well as resolves. A new attachment is
+ // cleared to zero instead, since Vulkan starts it undefined where
+ // WebGPU starts it zeroed.
+ const fresh = if (samples > 1) &t.msaa_fresh else &t.fresh;
+ color.load_op = if (pass.clear != null or fresh.*) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD;
+ fresh.* = false;
if (samples > 1) {
color.texture = t.msaa;
- color.store_op = c.SDL_GPU_STOREOP_RESOLVE;
+ color.store_op = c.SDL_GPU_STOREOP_RESOLVE_AND_STORE;
color.resolve_texture = t.texture;
} else {
color.texture = t.texture;
color.store_op = c.SDL_GPU_STOREOP_STORE;
}
+ t.fresh = false;
var depth: c.SDL_GPUDepthStencilTargetInfo = std.mem.zeroes(c.SDL_GPUDepthStencilTargetInfo);
if (pass.stencil) {
depth.texture = t.stencil;
@@ -231,29 +248,59 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void {
}
const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil) &depth else null) orelse return error.GpuRenderPass;
var bound: ?*c.SDL_GPUGraphicsPipeline = null;
+ // State already set in this pass, so draws that repeat it skip the call.
+ var vertex_uniforms: ?[]const u8 = null;
+ var stencil_reference: ?u8 = null;
+ var scissor: ?c.SDL_Rect = null;
+ var vertex_base: ?u32 = null;
var offset: u32 = 0;
for (pass.draws) |d| {
defer offset += @intCast(std.mem.alignForward(usize, d.vertices.len, 4));
if (d.pipeline >= pass.pipelines.len or d.vertex_count == 0) continue;
- const built = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| {
+ const slot = &built[d.pipeline];
+ if (slot.* == null) slot.* = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| blk: {
std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() });
- continue;
+ break :blk @as(?*c.SDL_GPUGraphicsPipeline, null);
};
- if (bound != built) {
- c.SDL_BindGPUGraphicsPipeline(rp, built);
- bound = built;
+ const chosen = slot.*.? orelse continue;
+ if (bound != chosen) {
+ c.SDL_BindGPUGraphicsPipeline(rp, chosen);
+ bound = chosen;
+ }
+ // Vertices at a multiple of the stride are reached from one binding
+ // at 0 by the draw's first vertex; others get a binding of their own.
+ var first: u32 = 0;
+ if (d.vertices.len > 0) {
+ const stride = pass.pipelines[d.pipeline].stride;
+ const base = if (stride > 0 and offset % stride == 0) 0 else offset;
+ if (base == 0 and stride > 0) first = offset / stride;
+ if (vertex_base != base) {
+ c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = base }, 1);
+ vertex_base = base;
+ }
}
- if (d.vertices.len > 0) c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = offset }, 1);
var bound_storage: [8]*c.SDL_GPUBuffer = undefined;
if (d.vertex_storage.len > 0) c.SDL_BindGPUVertexStorageBuffers(rp, 0, &bound_storage, g.resolve(d.vertex_storage, &bound_storage) catch continue);
if (d.fragment_storage.len > 0) c.SDL_BindGPUFragmentStorageBuffers(rp, 0, &bound_storage, g.resolve(d.fragment_storage, &bound_storage) catch continue);
- if (d.vertex_uniforms.len > 0) c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len));
+ // Pushed uniforms stay for later draws: the same bytes (sketches
+ // share one slice for a pass's viewport) need no second push.
+ if (d.vertex_uniforms.len > 0) if (vertex_uniforms == null or vertex_uniforms.?.ptr != d.vertex_uniforms.ptr or vertex_uniforms.?.len != d.vertex_uniforms.len) {
+ c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len));
+ vertex_uniforms = d.vertex_uniforms;
+ };
if (d.fragment_uniforms.len > 0) c.SDL_PushGPUFragmentUniformData(cmd, 0, d.fragment_uniforms.ptr, @intCast(d.fragment_uniforms.len));
- if (pass.stencil) c.SDL_SetGPUStencilReference(rp, d.stencil_reference);
+ if (pass.stencil and stencil_reference != d.stencil_reference) {
+ c.SDL_SetGPUStencilReference(rp, d.stencil_reference);
+ stencil_reference = d.stencil_reference;
+ }
const full: abi.Rect = .{ .w = @floatFromInt(pass.width), .h = @floatFromInt(pass.height) };
const s = d.scissor orelse full;
- c.SDL_SetGPUScissor(rp, &.{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) });
- c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, 0, 0);
+ const rect: c.SDL_Rect = .{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) };
+ if (scissor == null or !std.meta.eql(scissor.?, rect)) {
+ c.SDL_SetGPUScissor(rp, &rect);
+ scissor = rect;
+ }
+ c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, first, 0);
}
c.SDL_EndGPURenderPass(rp);
try g.submit(cmd, if (pass.label.len > 0) pass.label else "pass", start);
@@ -457,6 +504,7 @@ fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32,
if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m);
t.msaa = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, samples);
t.samples = samples;
+ t.msaa_fresh = true;
}
if (stencil and (t.stencil == null or t.stencil_samples != samples)) {
if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s);
diff --git a/src/host/gpu.zig.orig b/src/host/gpu.zig.orig
new file mode 100644
index 0000000..7854c99
--- /dev/null
+++ b/src/host/gpu.zig.orig
@@ -0,0 +1,641 @@
+//! Runs `abi.gpu` passes and dispatches with SDL_GPU: the translation from
+//! GPU work as data to a real API. Shaders and pipelines are built on first
+//! use and cached by the hash of their description; entries a sketch stops
+//! using (an edited shader, after a reload) are released after a while.
+const Gpu = @This();
+const std = @import("std");
+const c = @import("c");
+const abi = @import("abi");
+const gfx = @import("gfx.zig");
+
+pub const color_format = c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
+/// Frames an unused shader or pipeline survives.
+const keep_frames = 300;
+
+gpa: std.mem.Allocator,
+device: *c.SDL_GPUDevice,
+stencil_format: c.SDL_GPUTextureFormat,
+shaders: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUShader)) = .empty,
+pipelines: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUGraphicsPipeline)) = .empty,
+kernels: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUComputePipeline)) = .empty,
+/// Storage buffers by handle: `Buffer` n is `buffers[n - 1]`, null once freed.
+buffers: std.ArrayList(?Storage) = .empty,
+/// Uploads to storage buffers go through this, in chunks of its size.
+staging: ?*c.SDL_GPUTransferBuffer = null,
+/// Render targets per image: the resolved texture the renderer shows, and
+/// multisampled and stencil attachments as passes ask for them.
+targets: std.AutoHashMapUnmanaged(abi.Image, Target) = .empty,
+vertices: ?*c.SDL_GPUBuffer = null,
+vertex_capacity: u32 = 0,
+upload: ?*c.SDL_GPUTransferBuffer = null,
+upload_capacity: u32 = 0,
+frame: u64 = 0,
+/// Set by `--profile-gpu`: every command is timed alone (see `Profile`).
+profile: ?Profile = null,
+/// Downloads in flight, oldest first, and transfer buffers to reuse.
+downloads: std.ArrayList(Download) = .empty,
+spare: std.ArrayList(Transfer) = .empty,
+
+const Transfer = struct { buffer: *c.SDL_GPUTransferBuffer, size: u32 };
+const Download = struct { key: u32, size: u32, transfer: Transfer, fence: *c.SDL_GPUFence };
+
+/// GPU time per labelled command. Each command starts on an idle GPU and is
+/// waited for, so its time is its own: the total of a frame is what the
+/// GPU spends on it, though the waiting makes the frame itself slower.
+pub const Profile = struct {
+ entries: std.StringArrayHashMapUnmanaged(Entry) = .empty,
+ arena: std.heap.ArenaAllocator,
+
+ const Entry = struct { count: u64 = 0, total: u64 = 0, worst: u64 = 0 };
+
+ pub fn init(gpa: std.mem.Allocator) Profile {
+ return .{ .arena = .init(gpa) };
+ }
+
+ pub fn deinit(p: *Profile) void {
+ p.arena.deinit();
+ }
+
+ fn add(p: *Profile, label: []const u8, ns: u64) void {
+ const a = p.arena.allocator();
+ const entry = p.entries.getOrPut(a, label) catch return;
+ if (!entry.found_existing) {
+ entry.key_ptr.* = a.dupe(u8, label) catch "?";
+ entry.value_ptr.* = .{};
+ }
+ entry.value_ptr.count += 1;
+ entry.value_ptr.total += ns;
+ entry.value_ptr.worst = @max(entry.value_ptr.worst, ns);
+ }
+
+ pub fn report(p: *Profile, frames: u64) void {
+ std.debug.print("gpu time over {d} frames (ms)\n{s: <24} {s: >7} {s: >9} {s: >9} {s: >11}\n", .{ frames, "command", "count", "mean", "worst", "per frame" });
+ var sum: u64 = 0;
+ var it = p.entries.iterator();
+ while (it.next()) |e| {
+ const v = e.value_ptr.*;
+ sum += v.total;
+ std.debug.print("{s: <24} {d: >7} {d: >9.3} {d: >9.3} {d: >11.3}\n", .{ e.key_ptr.*, v.count, ms(v.total) / @as(f64, @floatFromInt(v.count)), ms(v.worst), ms(v.total) / @as(f64, @floatFromInt(@max(frames, 1))) });
+ }
+ std.debug.print("{s: <24} {s: >7} {s: >9} {s: >9} {d: >11.3}\n", .{ "all", "", "", "", ms(sum) / @as(f64, @floatFromInt(@max(frames, 1))) });
+ }
+
+ fn ms(ns: u64) f64 {
+ return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms;
+ }
+};
+
+/// Submits `cmd`; when profiling, waits for it and books its time from
+/// `start` (taken on an idle GPU, before recording) under `label`.
+fn submit(g: *Gpu, cmd: *c.SDL_GPUCommandBuffer, label: []const u8, start: u64) !void {
+ const p = &(g.profile orelse {
+ if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit;
+ return;
+ });
+ const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
+ defer c.SDL_ReleaseGPUFence(g.device, fence);
+ _ = c.SDL_WaitForGPUFences(g.device, true, &fence, 1);
+ p.add(label, c.SDL_GetTicksNS() - start);
+}
+
+/// When profiling: waits for the GPU to be idle, then the time to start from.
+fn startTiming(g: *Gpu) u64 {
+ if (g.profile != null) _ = c.SDL_WaitForGPUIdle(g.device);
+ return c.SDL_GetTicksNS();
+}
+
+/// The most bytes one buffer upload stages at a time.
+const staging_size = 4 << 20;
+
+fn Cached(comptime T: type) type {
+ return struct { object: *T, used: u64 };
+}
+
+const Storage = struct { buffer: *c.SDL_GPUBuffer, size: u32 };
+
+const Target = struct {
+ width: u32,
+ height: u32,
+ texture: *c.SDL_GPUTexture,
+ samples: u8 = 1,
+ msaa: ?*c.SDL_GPUTexture = null,
+ /// Not rendered into yet: undefined natively, so the first pass that
+ /// would load clears to zero (WebGPU's starting contents).
+ fresh: bool = true,
+ msaa_fresh: bool = true,
+ stencil_samples: u8 = 0,
+ stencil: ?*c.SDL_GPUTexture = null,
+};
+
+pub fn init(gpa: std.mem.Allocator, device: *c.SDL_GPUDevice) Gpu {
+ const d24 = c.SDL_GPUTextureSupportsFormat(device, c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, c.SDL_GPU_TEXTURETYPE_2D, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET);
+ return .{
+ .gpa = gpa,
+ .device = device,
+ .stencil_format = if (d24) c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT else c.SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT,
+ };
+}
+
+pub fn deinit(g: *Gpu, images: *gfx.Images) void {
+ if (g.profile) |*p| {
+ p.report(g.frame);
+ p.deinit();
+ }
+ var shaders = g.shaders.valueIterator();
+ while (shaders.next()) |s| c.SDL_ReleaseGPUShader(g.device, s.object);
+ var pipelines = g.pipelines.valueIterator();
+ while (pipelines.next()) |p| c.SDL_ReleaseGPUGraphicsPipeline(g.device, p.object);
+ var kernels = g.kernels.valueIterator();
+ while (kernels.next()) |k| c.SDL_ReleaseGPUComputePipeline(g.device, k.object);
+ for (g.buffers.items) |entry| if (entry) |b| c.SDL_ReleaseGPUBuffer(g.device, b.buffer);
+ for (g.downloads.items) |d| {
+ _ = c.SDL_WaitForGPUFences(g.device, true, &d.fence, 1);
+ c.SDL_ReleaseGPUFence(g.device, d.fence);
+ c.SDL_ReleaseGPUTransferBuffer(g.device, d.transfer.buffer);
+ }
+ for (g.spare.items) |t| c.SDL_ReleaseGPUTransferBuffer(g.device, t.buffer);
+ g.downloads.deinit(g.gpa);
+ g.spare.deinit(g.gpa);
+ if (g.staging) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b);
+ var targets = g.targets.iterator();
+ while (targets.next()) |entry| g.releaseTarget(images, entry.key_ptr.*, entry.value_ptr.*);
+ if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b);
+ if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b);
+ g.shaders.deinit(g.gpa);
+ g.pipelines.deinit(g.gpa);
+ g.kernels.deinit(g.gpa);
+ g.buffers.deinit(g.gpa);
+ g.targets.deinit(g.gpa);
+}
+
+/// Releases what nothing has used for a while.
+pub fn endFrame(g: *Gpu) void {
+ g.frame += 1;
+ inline for (.{ &g.pipelines, &g.shaders, &g.kernels }) |map| {
+ var it = map.iterator();
+ while (it.next()) |entry| {
+ if (g.frame - entry.value_ptr.used < keep_frames) continue;
+ switch (@TypeOf(map)) {
+ @TypeOf(&g.pipelines) => c.SDL_ReleaseGPUGraphicsPipeline(g.device, entry.value_ptr.object),
+ @TypeOf(&g.kernels) => c.SDL_ReleaseGPUComputePipeline(g.device, entry.value_ptr.object),
+ else => c.SDL_ReleaseGPUShader(g.device, entry.value_ptr.object),
+ }
+ map.removeByPtr(entry.key_ptr);
+ // The iterator is invalid after a removal: the rest waits a frame.
+ break;
+ }
+ }
+}
+
+pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void {
+ if (pass.width == 0 or pass.height == 0 or pass.draws.len == 0 and pass.clear == null) return;
+ const samples = g.supportedSamples(pass.samples);
+ const t = try g.renderTarget(images, pass.image, pass.width, pass.height, samples, pass.stencil);
+ // Each pipeline is looked up on first use in the pass, not per draw:
+ // the lookup hashes the shaders' code. Outer null: not looked up yet;
+ // inner null: it failed (warned once).
+ const built = try g.gpa.alloc(??*c.SDL_GPUGraphicsPipeline, pass.pipelines.len);
+ defer g.gpa.free(built);
+ @memset(built, null);
+
+ const start = g.startTiming();
+ // Every draw's vertices go up in one copy.
+ var total: u32 = 0;
+ for (pass.draws) |d| total += @intCast(std.mem.alignForward(usize, d.vertices.len, 4));
+ const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer;
+ if (total > 0) {
+ try g.reserve(total);
+ const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.upload, true) orelse return error.GpuMap);
+ var offset: usize = 0;
+ for (pass.draws) |d| {
+ @memcpy(mapped[offset..][0..d.vertices.len], d.vertices);
+ offset += std.mem.alignForward(usize, d.vertices.len, 4);
+ }
+ c.SDL_UnmapGPUTransferBuffer(g.device, g.upload);
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = g.upload, .offset = 0 }, &.{ .buffer = g.vertices, .offset = 0, .size = total }, true);
+ c.SDL_EndGPUCopyPass(copy);
+ }
+
+ const clear = pass.clear orelse .{ 0, 0, 0, 0 };
+ var color: c.SDL_GPUColorTargetInfo = std.mem.zeroes(c.SDL_GPUColorTargetInfo);
+ color.clear_color = .{ .r = clear[0], .g = clear[1], .b = clear[2], .a = clear[3] };
+ // `clear = null` keeps what the attachment holds, as on the web: a
+ // multisampled pass loads its multisampled attachment, which every
+ // pass therefore stores as well as resolves. A new attachment is
+ // cleared to zero instead, since Vulkan starts it undefined where
+ // WebGPU starts it zeroed.
+ const fresh = if (samples > 1) &t.msaa_fresh else &t.fresh;
+ color.load_op = if (pass.clear != null or fresh.*) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD;
+ fresh.* = false;
+ if (samples > 1) {
+ color.texture = t.msaa;
+ color.store_op = c.SDL_GPU_STOREOP_RESOLVE_AND_STORE;
+ color.resolve_texture = t.texture;
+ } else {
+ color.texture = t.texture;
+ color.store_op = c.SDL_GPU_STOREOP_STORE;
+ }
+ t.fresh = false;
+ var depth: c.SDL_GPUDepthStencilTargetInfo = std.mem.zeroes(c.SDL_GPUDepthStencilTargetInfo);
+ if (pass.stencil) {
+ depth.texture = t.stencil;
+ depth.load_op = c.SDL_GPU_LOADOP_DONT_CARE;
+ depth.store_op = c.SDL_GPU_STOREOP_DONT_CARE;
+ depth.stencil_load_op = c.SDL_GPU_LOADOP_CLEAR;
+ depth.stencil_store_op = c.SDL_GPU_STOREOP_DONT_CARE;
+ depth.clear_stencil = 0;
+ }
+ const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil) &depth else null) orelse return error.GpuRenderPass;
+ var bound: ?*c.SDL_GPUGraphicsPipeline = null;
+ var offset: u32 = 0;
+ for (pass.draws) |d| {
+ defer offset += @intCast(std.mem.alignForward(usize, d.vertices.len, 4));
+ if (d.pipeline >= pass.pipelines.len or d.vertex_count == 0) continue;
+ const slot = &built[d.pipeline];
+ if (slot.* == null) slot.* = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| blk: {
+ std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() });
+ break :blk @as(?*c.SDL_GPUGraphicsPipeline, null);
+ };
+ const chosen = slot.*.? orelse continue;
+ if (bound != chosen) {
+ c.SDL_BindGPUGraphicsPipeline(rp, chosen);
+ bound = chosen;
+ }
+ if (d.vertices.len > 0) c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = offset }, 1);
+ var bound_storage: [8]*c.SDL_GPUBuffer = undefined;
+ if (d.vertex_storage.len > 0) c.SDL_BindGPUVertexStorageBuffers(rp, 0, &bound_storage, g.resolve(d.vertex_storage, &bound_storage) catch continue);
+ if (d.fragment_storage.len > 0) c.SDL_BindGPUFragmentStorageBuffers(rp, 0, &bound_storage, g.resolve(d.fragment_storage, &bound_storage) catch continue);
+ if (d.vertex_uniforms.len > 0) c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len));
+ if (d.fragment_uniforms.len > 0) c.SDL_PushGPUFragmentUniformData(cmd, 0, d.fragment_uniforms.ptr, @intCast(d.fragment_uniforms.len));
+ if (pass.stencil) c.SDL_SetGPUStencilReference(rp, d.stencil_reference);
+ const full: abi.Rect = .{ .w = @floatFromInt(pass.width), .h = @floatFromInt(pass.height) };
+ const s = d.scissor orelse full;
+ c.SDL_SetGPUScissor(rp, &.{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) });
+ c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, 0, 0);
+ }
+ c.SDL_EndGPURenderPass(rp);
+ try g.submit(cmd, if (pass.label.len > 0) pass.label else "pass", start);
+}
+
+/// Runs one dispatch in a compute pass of its own.
+pub fn compute(g: *Gpu, d: abi.gpu.Dispatch) !void {
+ if (d.groups[0] == 0 or d.groups[1] == 0 or d.groups[2] == 0) return;
+ const built = try g.kernel(d.kernel);
+ const start = g.startTiming();
+ var readonly: [8]*c.SDL_GPUBuffer = undefined;
+ const readonly_count = try g.resolve(d.readonly, &readonly);
+ var readwrite: [8]*c.SDL_GPUBuffer = undefined;
+ const readwrite_count = try g.resolve(d.readwrite, &readwrite);
+ var bindings: [8]c.SDL_GPUStorageBufferReadWriteBinding = undefined;
+ for (readwrite[0..readwrite_count], bindings[0..readwrite_count]) |b, *binding| binding.* = std.mem.zeroInit(c.SDL_GPUStorageBufferReadWriteBinding, .{ .buffer = b });
+ const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer;
+ const pass = c.SDL_BeginGPUComputePass(cmd, null, 0, &bindings, readwrite_count) orelse {
+ _ = c.SDL_CancelGPUCommandBuffer(cmd);
+ return error.GpuComputePass;
+ };
+ c.SDL_BindGPUComputePipeline(pass, built);
+ if (readonly_count > 0) c.SDL_BindGPUComputeStorageBuffers(pass, 0, &readonly, readonly_count);
+ if (d.uniforms.len > 0) c.SDL_PushGPUComputeUniformData(cmd, 0, d.uniforms.ptr, @intCast(d.uniforms.len));
+ c.SDL_DispatchGPUCompute(pass, d.groups[0], d.groups[1], d.groups[2]);
+ c.SDL_EndGPUComputePass(pass);
+ try g.submit(cmd, if (d.label.len > 0) d.label else "compute", start);
+}
+
+/// A zeroed storage buffer, readable by every stage and writable by compute.
+pub fn newBuffer(g: *Gpu, size: u32) !abi.Buffer {
+ if (size == 0) return error.EmptyBuffer;
+ const usage = c.SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ | c.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ | c.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE;
+ const buffer = c.SDL_CreateGPUBuffer(g.device, &.{ .usage = usage, .size = size, .props = 0 }) orelse return error.GpuBuffer;
+ errdefer c.SDL_ReleaseGPUBuffer(g.device, buffer);
+ try g.buffers.append(g.gpa, .{ .buffer = buffer, .size = size });
+ const handle: abi.Buffer = @fromBackingInt(@intCast(g.buffers.items.len));
+ // Vulkan leaves new memory undefined; sketches get zeroes, copied from
+ // one zeroed staging block as many times as it takes.
+ const staging = try g.stagingBuffer();
+ const block: u32 = @min(size, staging_size);
+ const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, staging, true) orelse return error.GpuMap);
+ @memset(mapped[0..block], 0);
+ c.SDL_UnmapGPUTransferBuffer(g.device, staging);
+ const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer;
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ var offset: u32 = 0;
+ while (offset < size) : (offset += block) {
+ c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = staging, .offset = 0 }, &.{ .buffer = buffer, .offset = offset, .size = @min(block, size - offset) }, false);
+ }
+ c.SDL_EndGPUCopyPass(copy);
+ if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit;
+ return handle;
+}
+
+fn stagingBuffer(g: *Gpu) !*c.SDL_GPUTransferBuffer {
+ if (g.staging == null) g.staging = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = staging_size, .props = 0 }) orelse return error.GpuBuffer;
+ return g.staging.?;
+}
+
+pub fn freeBuffer(g: *Gpu, handle: abi.Buffer) void {
+ const index = @backingInt(handle);
+ if (index == 0 or index > g.buffers.items.len) return;
+ const entry = &g.buffers.items[index - 1];
+ if (entry.*) |b| c.SDL_ReleaseGPUBuffer(g.device, b.buffer);
+ entry.* = null;
+}
+
+/// Copies `bytes` into a buffer at `offset`, through the staging buffer.
+pub fn write(g: *Gpu, handle: abi.Buffer, offset: u32, bytes: []const u8) !void {
+ const target = g.storage(handle) orelse return error.UnknownBuffer;
+ if (@as(u64, offset) + bytes.len > target.size) return error.UploadOutOfBounds;
+ const staging = try g.stagingBuffer();
+ var done: usize = 0;
+ while (done < bytes.len) {
+ const chunk = bytes[done..][0..@min(staging_size, bytes.len - done)];
+ const start = g.startTiming();
+ // Cycling: a chunk still in flight keeps its own memory.
+ const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, staging, true) orelse return error.GpuMap);
+ @memcpy(mapped[0..chunk.len], chunk);
+ c.SDL_UnmapGPUTransferBuffer(g.device, staging);
+ const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer;
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = staging, .offset = 0 }, &.{ .buffer = target.buffer, .offset = offset + @as(u32, @intCast(done)), .size = @intCast(chunk.len) }, false);
+ c.SDL_EndGPUCopyPass(copy);
+ try g.submit(cmd, "upload", start);
+ done += chunk.len;
+ }
+}
+
+/// Starts copying `size` bytes of a buffer from `offset` back to the CPU;
+/// `collect` hands them over once the GPU is done, a frame or more later.
+pub fn download(g: *Gpu, d: @FieldType(abi.Command, "download")) !void {
+ const source = g.storage(d.buffer) orelse return error.UnknownBuffer;
+ if (d.size == 0 or @as(u64, d.offset) + d.size > source.size) return error.DownloadOutOfBounds;
+ const transfer = for (g.spare.items, 0..) |t, i| {
+ if (t.size >= d.size) break g.spare.swapRemove(i);
+ } else Transfer{
+ .buffer = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = d.size, .props = 0 }) orelse return error.GpuBuffer,
+ .size = d.size,
+ };
+ errdefer g.spare.append(g.gpa, transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, transfer.buffer);
+ const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer;
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ c.SDL_DownloadFromGPUBuffer(copy, &.{ .buffer = source.buffer, .offset = d.offset, .size = d.size }, &.{ .transfer_buffer = transfer.buffer, .offset = 0 });
+ c.SDL_EndGPUCopyPass(copy);
+ const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
+ g.downloads.append(g.gpa, .{ .key = d.key, .size = d.size, .transfer = transfer, .fence = fence }) catch |err| {
+ _ = c.SDL_WaitForGPUFences(g.device, true, &fence, 1);
+ c.SDL_ReleaseGPUFence(g.device, fence);
+ return err;
+ };
+}
+
+/// The downloads the GPU has finished, copied into `arena`, in the order
+/// they were asked for.
+pub fn collect(g: *Gpu, arena: std.mem.Allocator) ![]const abi.Download {
+ var done: std.ArrayList(abi.Download) = .empty;
+ while (g.downloads.items.len > 0) {
+ const d = g.downloads.items[0];
+ if (!c.SDL_QueryGPUFence(g.device, d.fence)) break;
+ _ = g.downloads.orderedRemove(0);
+ c.SDL_ReleaseGPUFence(g.device, d.fence);
+ defer g.spare.append(g.gpa, d.transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, d.transfer.buffer);
+ const mapped: [*]const u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, d.transfer.buffer, false) orelse return error.GpuMap);
+ defer c.SDL_UnmapGPUTransferBuffer(g.device, d.transfer.buffer);
+ try done.append(arena, .{ .key = d.key, .bytes = try arena.dupe(u8, mapped[0..d.size]) });
+ }
+ return done.items;
+}
+
+fn storage(g: *Gpu, handle: abi.Buffer) ?Storage {
+ const index = @backingInt(handle);
+ if (index == 0 or index > g.buffers.items.len) return null;
+ return g.buffers.items[index - 1];
+}
+
+/// The SDL buffers behind `handles`, into `out`; returns how many.
+fn resolve(g: *Gpu, handles: []const abi.Buffer, out: []*c.SDL_GPUBuffer) !u32 {
+ if (handles.len > out.len) return error.TooManyBuffers;
+ for (handles, out[0..handles.len]) |handle, *b| b.* = (g.storage(handle) orelse return error.UnknownBuffer).buffer;
+ return @intCast(handles.len);
+}
+
+fn kernel(g: *Gpu, k: abi.gpu.Kernel) !*c.SDL_GPUComputePipeline {
+ var h = std.hash.Wyhash.init(0);
+ h.update(k.code);
+ inline for (.{ k.readonly_buffers, k.readwrite_buffers, k.uniform_buffers, k.threads[0], k.threads[1], k.threads[2] }) |v| h.update(std.mem.asBytes(&@as(u32, v)));
+ const key = h.final();
+ const entry = try g.kernels.getOrPut(g.gpa, key);
+ if (!entry.found_existing) {
+ errdefer _ = g.kernels.remove(key);
+ var info: c.SDL_GPUComputePipelineCreateInfo = std.mem.zeroes(c.SDL_GPUComputePipelineCreateInfo);
+ info.code_size = k.code.len;
+ info.code = k.code.ptr;
+ info.entrypoint = "main";
+ info.format = c.SDL_GPU_SHADERFORMAT_SPIRV;
+ info.num_readonly_storage_buffers = k.readonly_buffers;
+ info.num_readwrite_storage_buffers = k.readwrite_buffers;
+ info.num_uniform_buffers = k.uniform_buffers;
+ info.threadcount_x = k.threads[0];
+ info.threadcount_y = k.threads[1];
+ info.threadcount_z = k.threads[2];
+ entry.value_ptr.object = c.SDL_CreateGPUComputePipeline(g.device, &info) orelse return error.GpuComputePipeline;
+ }
+ entry.value_ptr.used = g.frame;
+ return entry.value_ptr.object;
+}
+
+fn supportedSamples(g: *Gpu, wanted: u8) u8 {
+ var s: u8 = if (wanted >= 8) 8 else if (wanted >= 4) 4 else if (wanted >= 2) 2 else 1;
+ while (s > 1 and !c.SDL_GPUTextureSupportsSampleCount(g.device, color_format, sampleCount(s))) s /= 2;
+ return s;
+}
+
+fn sampleCount(s: u8) c.SDL_GPUSampleCount {
+ return switch (s) {
+ 8 => c.SDL_GPU_SAMPLECOUNT_8,
+ 4 => c.SDL_GPU_SAMPLECOUNT_4,
+ 2 => c.SDL_GPU_SAMPLECOUNT_2,
+ else => c.SDL_GPU_SAMPLECOUNT_1,
+ };
+}
+
+/// The image's render target, (re)created to fit the pass.
+fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32, samples: u8, stencil: bool) !*Target {
+ var entry = try g.targets.getOrPut(g.gpa, image);
+ if (entry.found_existing and (entry.value_ptr.width != w or entry.value_ptr.height != h)) {
+ g.releaseTarget(images, image, entry.value_ptr.*);
+ entry.found_existing = false;
+ }
+ if (!entry.found_existing) {
+ errdefer _ = g.targets.remove(image);
+ const resolved = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, 1);
+ errdefer c.SDL_ReleaseGPUTexture(g.device, resolved);
+ try images.wrap(image, resolved, w, h);
+ entry.value_ptr.* = .{ .width = w, .height = h, .texture = resolved };
+ }
+ const t = entry.value_ptr;
+ if (samples > 1 and (t.msaa == null or t.samples != samples)) {
+ if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m);
+ t.msaa = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, samples);
+ t.samples = samples;
+ t.msaa_fresh = true;
+ }
+ if (stencil and (t.stencil == null or t.stencil_samples != samples)) {
+ if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s);
+ t.stencil = try g.texture(w, h, g.stencil_format, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET, samples);
+ t.stencil_samples = samples;
+ }
+ return t;
+}
+
+fn releaseTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, t: Target) void {
+ images.unwrap(image);
+ c.SDL_ReleaseGPUTexture(g.device, t.texture);
+ if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m);
+ if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s);
+}
+
+/// Forgets an image's target, when the image itself is freed.
+pub fn forget(g: *Gpu, images: *gfx.Images, image: abi.Image) void {
+ const t = g.targets.fetchRemove(image) orelse return;
+ g.releaseTarget(images, image, t.value);
+}
+
+fn texture(g: *Gpu, w: u32, h: u32, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, samples: u8) !*c.SDL_GPUTexture {
+ var info: c.SDL_GPUTextureCreateInfo = std.mem.zeroes(c.SDL_GPUTextureCreateInfo);
+ info.type = c.SDL_GPU_TEXTURETYPE_2D;
+ info.format = format;
+ info.usage = usage;
+ info.width = w;
+ info.height = h;
+ info.layer_count_or_depth = 1;
+ info.num_levels = 1;
+ info.sample_count = sampleCount(samples);
+ return c.SDL_CreateGPUTexture(g.device, &info) orelse error.GpuTexture;
+}
+
+fn reserve(g: *Gpu, bytes: u32) !void {
+ if (bytes > g.vertex_capacity) {
+ const capacity = @max(bytes, g.vertex_capacity * 2, 64 * 1024);
+ if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b);
+ g.vertices = c.SDL_CreateGPUBuffer(g.device, &.{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = capacity, .props = 0 }) orelse return error.GpuBuffer;
+ g.vertex_capacity = capacity;
+ }
+ if (bytes > g.upload_capacity) {
+ const capacity = @max(bytes, g.upload_capacity * 2, 64 * 1024);
+ if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b);
+ g.upload = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = capacity, .props = 0 }) orelse return error.GpuBuffer;
+ g.upload_capacity = capacity;
+ }
+}
+
+fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage) !struct { *c.SDL_GPUShader, u64 } {
+ var h = std.hash.Wyhash.init(stage);
+ h.update(s.code);
+ h.update(std.mem.asBytes(&s.uniform_buffers));
+ h.update(std.mem.asBytes(&s.storage_buffers));
+ const key = h.final();
+ const entry = try g.shaders.getOrPut(g.gpa, key);
+ if (!entry.found_existing) {
+ errdefer _ = g.shaders.remove(key);
+ entry.value_ptr.object = c.SDL_CreateGPUShader(g.device, &.{
+ .code_size = s.code.len,
+ .code = s.code.ptr,
+ .entrypoint = "main",
+ .format = c.SDL_GPU_SHADERFORMAT_SPIRV,
+ .stage = stage,
+ .num_samplers = 0,
+ .num_storage_textures = 0,
+ .num_storage_buffers = s.storage_buffers,
+ .num_uniform_buffers = s.uniform_buffers,
+ .props = 0,
+ }) orelse return error.GpuShader;
+ }
+ entry.value_ptr.used = g.frame;
+ return .{ entry.value_ptr.object, key };
+}
+
+fn pipeline(g: *Gpu, p: abi.gpu.Pipeline, samples: u8, stencil: bool) !*c.SDL_GPUGraphicsPipeline {
+ const vertex, const vertex_key = try g.shader(p.vertex, c.SDL_GPU_SHADERSTAGE_VERTEX);
+ const fragment, const fragment_key = try g.shader(p.fragment, c.SDL_GPU_SHADERSTAGE_FRAGMENT);
+ // Field by field: no padding bytes in the key.
+ var h = std.hash.Wyhash.init(vertex_key ^ (fragment_key *% 31));
+ inline for (.{ p.stride, @backingInt(p.primitive), @backingInt(p.blend), @intFromBool(p.write_color), samples, @intFromBool(stencil) }) |v| h.update(std.mem.asBytes(&@as(u32, v)));
+ for (p.attributes) |a| inline for (.{ a.location, @backingInt(a.format), a.offset }) |v| h.update(std.mem.asBytes(&@as(u32, v)));
+ if (p.stencil) |st| inline for (.{ st.front, st.back }) |face| inline for (.{ @backingInt(face.compare), @backingInt(face.pass), @backingInt(face.fail) }) |v| h.update(std.mem.asBytes(&@as(u32, v)));
+ const key = h.final();
+ const entry = try g.pipelines.getOrPut(g.gpa, key);
+ if (!entry.found_existing) {
+ errdefer _ = g.pipelines.remove(key);
+ var attributes: [16]c.SDL_GPUVertexAttribute = undefined;
+ const count = @min(p.attributes.len, attributes.len);
+ for (p.attributes[0..count], attributes[0..count]) |a, *out| out.* = .{
+ .location = a.location,
+ .buffer_slot = 0,
+ .offset = a.offset,
+ .format = switch (a.format) {
+ .float => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT,
+ .float2 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2,
+ .float3 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3,
+ .float4 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4,
+ .ubyte4_norm => c.SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM,
+ },
+ };
+ var blend: c.SDL_GPUColorTargetBlendState = std.mem.zeroes(c.SDL_GPUColorTargetBlendState);
+ blend.enable_blend = p.blend != .none;
+ blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD;
+ blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD;
+ blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE;
+ blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE;
+ const dst: c.SDL_GPUBlendFactor = if (p.blend == .additive) c.SDL_GPU_BLENDFACTOR_ONE else c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
+ blend.dst_color_blendfactor = dst;
+ blend.dst_alpha_blendfactor = dst;
+ blend.enable_color_write_mask = true;
+ blend.color_write_mask = if (p.write_color) c.SDL_GPU_COLORCOMPONENT_R | c.SDL_GPU_COLORCOMPONENT_G | c.SDL_GPU_COLORCOMPONENT_B | c.SDL_GPU_COLORCOMPONENT_A else 0;
+ const target_description: c.SDL_GPUColorTargetDescription = .{ .format = color_format, .blend_state = blend };
+ var depth_stencil: c.SDL_GPUDepthStencilState = std.mem.zeroes(c.SDL_GPUDepthStencilState);
+ if (p.stencil) |st| {
+ depth_stencil.enable_stencil_test = true;
+ depth_stencil.compare_mask = 0xff;
+ depth_stencil.write_mask = 0xff;
+ depth_stencil.front_stencil_state = stencilFace(st.front);
+ depth_stencil.back_stencil_state = stencilFace(st.back);
+ }
+ var info: c.SDL_GPUGraphicsPipelineCreateInfo = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo);
+ info.vertex_shader = vertex;
+ info.fragment_shader = fragment;
+ info.vertex_input_state = .{
+ .vertex_buffer_descriptions = &.{ .slot = 0, .pitch = p.stride, .input_rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .instance_step_rate = 0 },
+ // No attributes: the vertex shader makes its own vertices.
+ .num_vertex_buffers = @intFromBool(count > 0),
+ .vertex_attributes = &attributes,
+ .num_vertex_attributes = @intCast(count),
+ };
+ info.primitive_type = switch (p.primitive) {
+ .triangle_list => c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST,
+ .triangle_strip => c.SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP,
+ .line_list => c.SDL_GPU_PRIMITIVETYPE_LINELIST,
+ .line_strip => c.SDL_GPU_PRIMITIVETYPE_LINESTRIP,
+ };
+ info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL;
+ info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE;
+ info.rasterizer_state.front_face = c.SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE;
+ info.multisample_state.sample_count = sampleCount(samples);
+ info.depth_stencil_state = depth_stencil;
+ info.target_info.color_target_descriptions = &target_description;
+ info.target_info.num_color_targets = 1;
+ info.target_info.depth_stencil_format = g.stencil_format;
+ info.target_info.has_depth_stencil_target = stencil;
+ entry.value_ptr.object = c.SDL_CreateGPUGraphicsPipeline(g.device, &info) orelse return error.GpuPipeline;
+ }
+ entry.value_ptr.used = g.frame;
+ return entry.value_ptr.object;
+}
+
+fn stencilFace(face: abi.gpu.StencilFace) c.SDL_GPUStencilOpState {
+ // Both enums follow SDL's order, after its INVALID.
+ return .{
+ .compare_op = @as(u32, @backingInt(face.compare)) + 1,
+ .pass_op = @as(u32, @backingInt(face.pass)) + 1,
+ .fail_op = @as(u32, @backingInt(face.fail)) + 1,
+ .depth_fail_op = c.SDL_GPU_STENCILOP_KEEP,
+ };
+}
diff --git a/src/host/memory.zig b/src/host/memory.zig
index fc44e50..5fbb88f 100644
--- a/src/host/memory.zig
+++ b/src/host/memory.zig
@@ -20,7 +20,11 @@ pub const page = std.heap.page_size_min;
/// Slot 0 is live; 1..7 are snapshots.
pub const slot_count = 8;
pub const header_len = 64 * 1024;
-pub const file_magic = "SKETCH01".*;
+/// Layouts with element leaves (`list[].x`, `StoredField` with `dims`).
+pub const file_magic = "SKETCH02".*;
+/// What hosts before element leaves wrote: arrays are whole leaves
+/// (`StoredFieldV1`). Read, and rewritten as `file_magic` on adopt.
+pub const file_magic_v1 = "SKETCH01".*;
pub const Header = extern struct {
magic: [8]u8 = file_magic,
@@ -36,7 +40,8 @@ pub const Header = extern struct {
reserved: u32 = 0,
};
-/// A leaf as stored in the file: strings are offsets into the string table.
+/// A leaf as stored in the file: strings are offsets into the string table,
+/// and so is `dims`, `rank` little-endian (count, stride) u32 pairs.
pub const StoredField = extern struct {
offset: u32,
size: u32,
@@ -46,9 +51,27 @@ pub const StoredField = extern struct {
tags_len: u16,
tags: u32,
kind: abi.Field.Kind,
+ rank: u8 = 0,
+ reserved: [2]u8 = @splat(0),
+ dims: u32 = 0,
+ reserved2: u32 = 0,
+};
+
+/// A leaf as `file_magic_v1` files store it: no element leaves.
+pub const StoredFieldV1 = extern struct {
+ offset: u32,
+ size: u32,
+ hash: u64,
+ path: u32,
+ path_len: u16,
+ tags_len: u16,
+ tags: u32,
+ kind: abi.Field.Kind,
reserved: [3]u8 = @splat(0),
};
+const Dim = abi.Field.Dim;
+
/// A layout the host owns: copied out of a sketch, or read from a file.
pub const Layout = struct {
size: usize = 0,
@@ -56,6 +79,8 @@ pub const Layout = struct {
hash: u64 = 0,
fields: []const Leaf = &.{},
+ /// A leaf with `dims` stands for all its elements (`list[].x`), at
+ /// `offset` plus index times stride per dimension. `find` resolves one.
pub const Leaf = struct {
path: []const u8,
offset: u32,
@@ -63,10 +88,38 @@ pub const Layout = struct {
kind: abi.Field.Kind,
hash: u64,
tags: []const u8,
+ dims: []const Dim = &.{},
pub fn bytes(leaf: Leaf, memory: []const u8) []const u8 {
return memory[leaf.offset..][0..leaf.size];
}
+ /// The leaf at `offset` (from `elements`), as a leaf of its own.
+ pub fn at(leaf: Leaf, offset: usize) Leaf {
+ var one = leaf;
+ one.offset = @intCast(offset);
+ one.dims = &.{};
+ return one;
+ }
+ /// A whole array, kept for copying in one piece; its elements are
+ /// leaves of their own.
+ pub fn whole(leaf: Leaf) bool {
+ return leaf.kind == .array;
+ }
+ /// Offsets of every element, first index slowest.
+ pub fn elements(leaf: Leaf) Elements {
+ return .init(leaf.offset, leaf.dims, leaf.dims, null);
+ }
+ /// Writes the path naming the element at `offset`, indices filled in.
+ pub fn name(leaf: Leaf, offset: usize, w: *std.Io.Writer) std.Io.Writer.Error!void {
+ var rest = offset - leaf.offset;
+ var parts = std.mem.splitSequence(u8, leaf.path, "[]");
+ try w.writeAll(parts.first());
+ for (leaf.dims) |d| {
+ try w.print("[{d}]", .{rest / d.stride});
+ rest %= d.stride;
+ try w.writeAll(parts.next() orelse "");
+ }
+ }
};
pub fn copy(arena: std.mem.Allocator, l: abi.Layout) !Layout {
@@ -78,37 +131,149 @@ pub const Layout = struct {
.kind = from.kind,
.hash = from.hash,
.tags = try arena.dupe(u8, std.mem.span(from.tags)),
+ .dims = try arena.dupe(Dim, from.dims[0..from.rank]),
};
return .{ .size = l.size, .alignment = l.alignment, .hash = l.hash, .fields = fields };
}
+ /// The leaf `path` names, with indices for every array it is in
+ /// (`list[3].pos[0]`), as a leaf of its own; null when there is none
+ /// or an index is out of range.
pub fn find(self: Layout, path: []const u8) ?Leaf {
+ for (self.fields) |leaf| {
+ const delta = abi.layout.match(leaf.path, leaf.dims, path) orelse continue;
+ return leaf.at(leaf.offset + delta);
+ }
+ return null;
+ }
+
+ /// The leaf whose pattern is exactly `pattern` (`list[].x`).
+ pub fn pattern(self: Layout, path: []const u8) ?Leaf {
for (self.fields) |leaf| if (std.mem.eql(u8, leaf.path, path)) return leaf;
return null;
}
};
+/// Walks element offsets of one leaf, or of the elements two layouts of a
+/// leaf share (`limit`, the smaller count per dimension), with offsets in
+/// both.
+pub const Elements = struct {
+ index: [abi.layout.max_rank]u32 = @splat(0),
+ limit: [abi.layout.max_rank]u32 = @splat(0),
+ rank: usize,
+ a: Side,
+ b: Side,
+ done: bool,
+
+ const Side = struct { base: usize, dims: []const Dim };
+
+ pub fn init(base: usize, dims: []const Dim, other_dims: []const Dim, other_base: ?usize) Elements {
+ var e: Elements = .{ .rank = dims.len, .a = .{ .base = base, .dims = dims }, .b = .{ .base = other_base orelse base, .dims = other_dims }, .done = false };
+ for (dims, other_dims, 0..) |x, y, i| {
+ e.limit[i] = @min(x.count, y.count);
+ if (e.limit[i] == 0) e.done = true;
+ }
+ return e;
+ }
+
+ fn offset(e: *const Elements, side: Side) usize {
+ var at = side.base;
+ for (side.dims, 0..) |d, i| at += @as(usize, e.index[i]) * d.stride;
+ return at;
+ }
+
+ pub fn next(e: *Elements) ?usize {
+ const pair = e.nextPair() orelse return null;
+ return pair[0];
+ }
+
+ pub fn nextPair(e: *Elements) ?[2]usize {
+ if (e.done) return null;
+ const pair: [2]usize = .{ e.offset(e.a), e.offset(e.b) };
+ var i = e.rank;
+ while (true) {
+ if (i == 0) {
+ e.done = true;
+ break;
+ }
+ i -= 1;
+ e.index[i] += 1;
+ if (e.index[i] < e.limit[i]) break;
+ e.index[i] = 0;
+ }
+ return pair;
+ }
+};
+
pub const Migration = struct { kept: usize = 0, reset: usize = 0 };
/// Copies every leaf of `from` whose path and type are unchanged into `to`,
-/// which already holds the new defaults.
+/// which already holds the new defaults. Arrays copy element by element:
+/// the elements both layouts have (the common prefix of each dimension; a
+/// shrink drops the rest, a growth keeps the new defaults), field by field
+/// inside each, enums by tag name. An array whose type is unchanged copies
+/// in one piece. Counts are of leaves, not elements.
pub fn migrate(from: Layout, old: []const u8, to: Layout, new: []u8) Migration {
var result: Migration = .{};
+ // The array copied whole most recently: its elements' leaves follow it.
+ var copied: ?[]const u8 = null;
for (to.fields) |leaf| {
- const before = from.find(leaf.path) orelse {
- result.reset += 1;
+ if (copied) |prefix| {
+ if (leaf.path.len > prefix.len and std.mem.startsWith(u8, leaf.path, prefix) and leaf.path[prefix.len] == '[') continue;
+ copied = null;
+ }
+ const before = from.pattern(leaf.path) orelse {
+ if (!leaf.whole()) result.reset += 1;
continue;
};
+ if (before.dims.len != leaf.dims.len) {
+ if (!leaf.whole()) result.reset += 1;
+ continue;
+ }
if (before.hash == leaf.hash and before.size == leaf.size) {
- @memcpy(new[leaf.offset..][0..leaf.size], before.bytes(old));
+ var it: Elements = .init(leaf.offset, leaf.dims, before.dims, before.offset);
+ while (it.nextPair()) |pair| @memcpy(new[pair[0]..][0..leaf.size], old[pair[1]..][0..leaf.size]);
+ if (leaf.whole()) copied = leaf.path;
result.kept += 1;
- } else if (before.kind == .@"enum" and leaf.kind == .@"enum" and remapEnum(before, old, leaf, new)) {
- result.kept += 1;
- } else result.reset += 1;
+ } else if (before.kind == .@"enum" and leaf.kind == .@"enum") {
+ var it: Elements = .init(leaf.offset, leaf.dims, before.dims, before.offset);
+ var any = false;
+ var seen: usize = 0;
+ while (it.nextPair()) |pair| : (seen += 1) {
+ if (remapEnum(before.at(pair[1]), old, leaf.at(pair[0]), new)) any = true;
+ }
+ if (any or seen == 0) result.kept += 1 else result.reset += 1;
+ } else if (!leaf.whole()) result.reset += 1;
}
return result;
}
+pub const Diff = struct {
+ /// Leaf values (elements counted one by one) that differ.
+ count: usize = 0,
+ first: ?Place = null,
+ last: ?Place = null,
+
+ pub const Place = struct { leaf: Layout.Leaf, offset: usize };
+};
+
+/// Compares two copies of state leaf by leaf, so padding (a Debug
+/// `@Vector`'s spare lane, the gaps between fields) never differs.
+pub fn compare(layout: Layout, a: []const u8, b: []const u8) Diff {
+ var diff: Diff = .{};
+ for (layout.fields) |leaf| {
+ if (leaf.whole()) continue;
+ var it = leaf.elements();
+ while (it.next()) |offset| {
+ if (std.mem.eql(u8, a[offset..][0..leaf.size], b[offset..][0..leaf.size])) continue;
+ diff.count += 1;
+ if (diff.first == null) diff.first = .{ .leaf = leaf, .offset = offset };
+ diff.last = .{ .leaf = leaf, .offset = offset };
+ }
+ }
+ return diff;
+}
+
/// Carries an enum over by tag name; false when its name no longer exists.
fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) bool {
const name = field_value.tagName(from.tags, field_value.readInt(i64, from.bytes(old))) orelse return false;
@@ -124,22 +289,23 @@ pub const StateFile = struct {
layout: Layout,
arena: std.heap.ArenaAllocator,
- /// Opens or creates `path`. A missing or foreign file has no layout and no
- /// used slots: the first `adopt` fills it.
+ /// Opens or creates `path`. A new (empty) file has no layout and no used
+ /// slots: the first `adopt` fills it. A file that is not a state file
+ /// this host can read is refused, never truncated: it may be someone's
+ /// work, written by another build.
pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile {
const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
errdefer _ = posix.system.close(fd);
var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) };
errdefer self.arena.deinit();
const len = try fileSize(fd);
- if (len >= header_len) {
+ if (len > 0) {
+ if (len < header_len) return error.NotAStateFile;
self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true });
- if (self.valid()) {
- self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{};
- return self;
- }
- posix.munmap(self.map);
- self.map = &.{};
+ errdefer posix.munmap(self.map);
+ try self.check();
+ self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{};
+ return self;
}
try self.resize(0);
self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
@@ -181,7 +347,18 @@ pub const StateFile = struct {
/// Makes the file hold `new`'s layout. Used slots are migrated: `defaults`
/// writes the new default values, then unchanged fields are copied over.
pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption {
- if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) return .unchanged;
+ if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) {
+ // Same type, older header: describe it again, bytes untouched.
+ if (std.mem.eql(u8, &self.header().magic, &file_magic_v1)) {
+ var kept = self.arena;
+ defer kept.deinit();
+ self.arena = .init(gpa);
+ self.layout = try Layout.copy(self.arena.allocator(), new);
+ try writeLayout(self.map[0..header_len], self.layout);
+ self.header().magic = file_magic;
+ }
+ return .unchanged;
+ }
const had_state = self.header().used & 1 != 0;
// Keep the old bytes and layout while the file is rebuilt.
@@ -202,7 +379,7 @@ pub const StateFile = struct {
const stride = std.mem.alignForward(usize, @max(new.size, 1), page);
try self.resize(stride);
const h = self.header();
- h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 };
+ h.* = .{ .magic = file_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 };
try writeLayout(self.map[0..header_len], self.layout);
var total: Migration = .{};
@@ -222,10 +399,10 @@ pub const StateFile = struct {
return .{ .migrated = total };
}
- fn valid(self: *StateFile) bool {
+ fn check(self: *StateFile) !void {
const h = self.header();
- if (!std.mem.eql(u8, &h.magic, &file_magic)) return false;
- return self.map.len >= header_len + slot_count * h.stride and h.size <= h.stride;
+ if (!std.mem.eql(u8, &h.magic, &file_magic) and !std.mem.eql(u8, &h.magic, &file_magic_v1)) return error.NotAStateFile;
+ if (self.map.len < header_len + slot_count * h.stride or h.size > h.stride) return error.CorruptStateFile;
}
fn resize(self: *StateFile, stride: usize) !void {
@@ -240,17 +417,24 @@ pub const StateFile = struct {
}
};
-/// Writes `layout`'s leaves after the `Header` at the start of `region`.
+/// Writes `layout`'s leaves after the `Header` at the start of `region`,
+/// in the current format (`StoredField`); the caller sets the magic.
fn writeLayout(region: []u8, layout: Layout) !void {
const h: *Header = @ptrCast(@alignCast(region.ptr));
const fields: [*]StoredField = @ptrCast(@alignCast(region.ptr + @sizeOf(Header)));
const strings_start = @sizeOf(Header) + layout.fields.len * @sizeOf(StoredField);
var strings: usize = 0;
for (layout.fields, 0..) |leaf, i| {
- if (strings_start + strings + leaf.path.len + leaf.tags.len > region.len) return error.LayoutTooLarge;
+ const dims_len = leaf.dims.len * @sizeOf(Dim);
+ if (strings_start + strings + leaf.path.len + leaf.tags.len + dims_len > region.len) return error.LayoutTooLarge;
const base = strings_start + strings;
@memcpy(region[base..][0..leaf.path.len], leaf.path);
@memcpy(region[base + leaf.path.len ..][0..leaf.tags.len], leaf.tags);
+ for (leaf.dims, 0..) |d, j| {
+ const at = base + leaf.path.len + leaf.tags.len + j * @sizeOf(Dim);
+ std.mem.writeInt(u32, region[at..][0..4], d.count, .little);
+ std.mem.writeInt(u32, region[at + 4 ..][0..4], d.stride, .little);
+ }
fields[i] = .{
.offset = leaf.offset,
.size = leaf.size,
@@ -260,24 +444,42 @@ fn writeLayout(region: []u8, layout: Layout) !void {
.path_len = @intCast(leaf.path.len),
.tags = @intCast(strings + leaf.path.len),
.tags_len = @intCast(leaf.tags.len),
+ .rank = @intCast(leaf.dims.len),
+ .dims = @intCast(strings + leaf.path.len + leaf.tags.len),
};
- strings += leaf.path.len + leaf.tags.len;
+ strings += leaf.path.len + leaf.tags.len + dims_len;
}
h.field_count = @intCast(layout.fields.len);
h.strings_len = @intCast(strings);
}
-/// The layout stored in a state file's header, or null if it has none.
+/// The layout stored in a state or store file's header, or null if it has
+/// none. Reads both formats, by magic: a v1 header (`file_magic_v1`,
+/// `store_layout_magic_v1`) has no element leaves, so its arrays are whole
+/// leaves only, which migrate while their type is unchanged.
pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
const h: *const Header = @ptrCast(@alignCast(map.ptr));
if (h.hash == 0 and h.field_count == 0) return null;
- const stored: [*]const StoredField = @ptrCast(@alignCast(map.ptr + @sizeOf(Header)));
- const strings_start = @sizeOf(Header) + h.field_count * @sizeOf(StoredField);
- if (strings_start + h.strings_len > header_len) return error.CorruptHeader;
+ const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1) or std.mem.eql(u8, &h.magic, &store_layout_magic_v1);
+ const stride: usize = if (v1) @sizeOf(StoredFieldV1) else @sizeOf(StoredField);
+ const strings_start = @sizeOf(Header) + @as(usize, h.field_count) * stride;
+ if (strings_start + h.strings_len > header_len or map.len < header_len) return error.CorruptHeader;
const strings = map[strings_start..][0..h.strings_len];
const leaves = try arena.alloc(Layout.Leaf, h.field_count);
- for (leaves, stored[0..h.field_count]) |*leaf, f| {
- if (f.path + f.path_len > strings.len or f.tags + f.tags_len > strings.len) return error.CorruptHeader;
+ for (leaves, 0..) |*leaf, i| {
+ const at = @sizeOf(Header) + i * stride;
+ const f: StoredField = if (v1) blk: {
+ const old: *const StoredFieldV1 = @ptrCast(@alignCast(map[at..].ptr));
+ break :blk .{ .offset = old.offset, .size = old.size, .hash = old.hash, .path = old.path, .path_len = old.path_len, .tags = old.tags, .tags_len = old.tags_len, .kind = old.kind };
+ } else @as(*const StoredField, @ptrCast(@alignCast(map[at..].ptr))).*;
+ const dims_len = @as(usize, f.rank) * @sizeOf(Dim);
+ if (f.path + f.path_len > strings.len or f.tags + f.tags_len > strings.len or f.dims + dims_len > strings.len) return error.CorruptHeader;
+ if (f.rank > abi.layout.max_rank) return error.CorruptHeader;
+ const dims = try arena.alloc(Dim, f.rank);
+ for (dims, 0..) |*d, j| {
+ const raw = strings[f.dims + j * @sizeOf(Dim) ..];
+ d.* = .{ .count = std.mem.readInt(u32, raw[0..4], .little), .stride = std.mem.readInt(u32, raw[4..8], .little) };
+ }
// Copied: the mapping moves when the file is resized.
leaf.* = .{
.path = try arena.dupe(u8, strings[f.path..][0..f.path_len]),
@@ -286,7 +488,12 @@ pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
.kind = f.kind,
.hash = f.hash,
.tags = try arena.dupe(u8, strings[f.tags..][0..f.tags_len]),
+ .dims = dims,
};
+ // Every element must lie inside the state.
+ var end: usize = @as(usize, leaf.offset) + leaf.size;
+ for (dims) |d| end += @as(usize, d.stride) * (d.count -| 1);
+ if (end > h.size) return error.CorruptHeader;
}
return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves };
}
@@ -318,7 +525,11 @@ pub fn mapReadOnly(path: []const u8) []align(page) const u8 {
pub const store_base: usize = 0x2000_0000_0000;
/// The most a store can grow to. Only reserved: pages exist as they are used.
pub const store_reserve: usize = 64 << 30;
+/// The allocator's record (`Meta`); unchanged by the layout format.
pub const store_magic = "SKSTORE1".*;
+/// The store's layout header, like `file_magic` and `file_magic_v1`.
+pub const store_layout_magic = "SKSTORE2".*;
+pub const store_layout_magic_v1 = "SKSTORE1".*;
/// The layout region is a state file header; the allocator's own record
/// follows, then the heap.
const meta_offset = header_len;
@@ -368,13 +579,15 @@ pub const StoreFile = struct {
var self: StoreFile = .{ .fd = fd, .len = 0, .layout = .{}, .arena = .init(gpa) };
errdefer self.arena.deinit();
const size: usize = @intCast(try fileSize(fd));
- if (!fresh and size >= heap_offset) {
+ if (!fresh and size > 0) {
+ // Checked before mapping, which may lengthen the file: a file
+ // that is not a store is refused untouched, never wiped.
+ var m: Meta = undefined;
+ const read = linux.pread(fd, std.mem.asBytes(&m), @sizeOf(Meta), meta_offset);
+ if (size < heap_offset or read != @sizeOf(Meta) or !std.mem.eql(u8, &m.magic, &store_magic) or m.base != store_base or m.top > size) return error.NotAStoreFile;
try self.grow(size);
- const m = self.meta();
- if (std.mem.eql(u8, &m.magic, &store_magic) and m.base == store_base and m.top <= size) {
- self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{};
- return self;
- }
+ self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{};
+ return self;
}
try self.wipe();
return self;
@@ -396,7 +609,7 @@ pub const StoreFile = struct {
try truncate(self.fd, heap_offset);
try self.grow(heap_offset);
@memset(self.region(), 0);
- self.header().* = .{ .magic = store_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
+ self.header().* = .{ .magic = store_layout_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
self.meta().* = .{};
self.layout = .{};
}
@@ -452,7 +665,7 @@ pub const StoreFile = struct {
result = .{ .migrated = migrate(old_layout, old[0..old_layout.size], self.layout, fresh[0..new.size]) };
a.rawFree(old[0..@max(old_layout.size, 1)], .fromByteUnits(@max(old_layout.alignment, 1)), @returnAddress());
}
- self.header().* = .{ .magic = store_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 };
+ self.header().* = .{ .magic = store_layout_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 };
try writeLayout(self.region(), self.layout);
m.root = @intFromPtr(fresh) - store_base;
return result;
@@ -723,3 +936,192 @@ test "a store keeps its root and what it points to across a reopen, and migrates
defer store.close();
try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V2, .store), D.v2));
}
+
+test "arrays migrate element by element: fields, enums by name, shrink and growth" {
+ const E1 = struct { x: f32 = 0, mood: enum(u8) { calm = 1, wild = 2 } = .calm };
+ const E2 = struct { added: u8 = 9, mood: enum(u8) { wild = 5, calm = 6, sleepy = 7 } = .sleepy, x: f32 = 0 };
+ const V1 = struct { list: struct { buffer: [4]E1 = @splat(.{}), len: u32 = 0 } = .{}, samples: [4]u16 = @splat(0), pos: [2]f32 = @splat(0), grid: [2][3]u8 = @splat(@splat(0)) };
+ const V2 = struct { list: struct { buffer: [2]E2 = @splat(.{}), len: u32 = 0 } = .{}, samples: [6]u16 = @splat(5), pos: @Vector(2, f32) = @splat(0), grid: [3][2]u8 = @splat(@splat(0)) };
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .state));
+ const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .state));
+ var old: V1 = .{ .samples = .{ 1, 2, 3, 4 }, .pos = .{ 3, 4 }, .grid = .{ .{ 1, 2, 3 }, .{ 4, 5, 6 } } };
+ for (&old.list.buffer, 0..) |*e, i| e.* = .{ .x = @floatFromInt(i + 1), .mood = if (i % 2 == 0) .calm else .wild };
+ old.list.len = 4;
+ var new: V2 = .{};
+ _ = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new));
+ try std.testing.expectEqual(E2{ .added = 9, .mood = .calm, .x = 1 }, new.list.buffer[0]);
+ try std.testing.expectEqual(E2{ .added = 9, .mood = .wild, .x = 2 }, new.list.buffer[1]);
+ // `len` is kept as it was: a List clamps it where it is read.
+ try std.testing.expectEqual(@as(u32, 4), new.list.len);
+ try std.testing.expectEqual([6]u16{ 1, 2, 3, 4, 5, 5 }, new.samples);
+ try std.testing.expectEqual(@as(f32, 4), new.pos[1]);
+ try std.testing.expectEqual([3][2]u8{ .{ 1, 2 }, .{ 4, 5 }, .{ 0, 0 } }, new.grid);
+
+ // Growing back: the kept elements return, new ones take defaults.
+ var back: V1 = .{};
+ _ = migrate(l2, std.mem.asBytes(&new), l1, std.mem.asBytes(&back));
+ try std.testing.expectEqual(@as(f32, 2), back.list.buffer[1].x);
+ try std.testing.expectEqual(@as(f32, 0), back.list.buffer[2].x);
+ try std.testing.expectEqual(.wild, back.list.buffer[1].mood);
+}
+
+test "an array of songs keeps its songs when a song gains a field" {
+ const Note = struct { pitch: u8 = 0, length: u8 = 1 };
+ const Song1 = struct { name: [8]u8 = @splat(0), notes: [16]Note = @splat(.{}), tempo: u16 = 120 };
+ const Song2 = struct { tempo: u16 = 120, swing: f32 = 0.5, notes: [16]Note = @splat(.{}), name: [8]u8 = @splat(0) };
+ const V1 = struct { songs: [8]Song1 = @splat(.{}), other: u32 = 0 };
+ const V2 = struct { added: u8 = 1, songs: [8]Song2 = @splat(.{}) };
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .state));
+ const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .state));
+ var old: V1 = .{};
+ for (&old.songs, 0..) |*song, i| {
+ song.name = "song 0".*;
+ song.name[7] = '0' + @as(u8, @intCast(i));
+ song.tempo = @intCast(100 + i);
+ for (&song.notes, 0..) |*n, j| n.* = .{ .pitch = @intCast(i * 16 + j), .length = 2 };
+ }
+ var new: V2 = .{};
+ const m = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new));
+ for (old.songs, new.songs) |a, b| {
+ try std.testing.expectEqualSlices(u8, &a.name, &b.name);
+ try std.testing.expectEqual(a.tempo, b.tempo);
+ try std.testing.expectEqual(@as(f32, 0.5), b.swing);
+ for (a.notes, b.notes) |x, y| try std.testing.expectEqual(x, y);
+ }
+ // songs[].notes is unchanged, so it copies whole; swing and added are new.
+ try std.testing.expectEqual(@as(usize, 2), m.reset);
+ // The same type on both sides copies in one piece.
+ var same: V1 = .{};
+ try std.testing.expectEqual(@as(usize, 2), migrate(l1, std.mem.asBytes(&old), l1, std.mem.asBytes(&same)).kept);
+ try std.testing.expectEqualDeep(old, same);
+}
+
+test "compare goes leaf by leaf: padding never differs" {
+ const S = struct { a: u8 = 1, b: u32 = 2, v: @Vector(3, f32) = .{ 1, 2, 3 }, list: [2]struct { c: u8 = 0, d: u16 = 0 } = @splat(.{}) };
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state));
+ var x: S = .{};
+ var y: S = .{};
+ const a = std.mem.asBytes(&x);
+ const b = std.mem.asBytes(&y);
+ @memcpy(b, a);
+ // Every byte no leaf covers.
+ var covered: [@sizeOf(S)]bool = @splat(false);
+ for (layout.fields) |leaf| {
+ if (leaf.whole()) continue;
+ var it = leaf.elements();
+ while (it.next()) |offset| @memset(covered[offset..][0..leaf.size], true);
+ }
+ var padding: usize = 0;
+ for (covered, 0..) |c, i| if (!c) {
+ b[i] ^= 0xff;
+ padding += 1;
+ };
+ try std.testing.expect(padding >= 4);
+ try std.testing.expectEqual(@as(usize, 0), compare(layout, a, b).count);
+ y.list[1].d = 7;
+ y.v[2] = 0;
+ const diff = compare(layout, a, b);
+ try std.testing.expectEqual(@as(usize, 2), diff.count);
+ var buf: [64]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ try diff.last.?.leaf.name(diff.last.?.offset, &w);
+ try std.testing.expectEqualStrings("list[1].d", w.buffered());
+}
+
+fn testPath(buf: []u8, tmp: anytype, name: []const u8) ![]const u8 {
+ return std.mem.print(buf, ".zig-cache/tmp/{s}/{s}", .{ &tmp.sub_path, name });
+}
+
+test "a file that is not a state file is refused, untouched" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const io = std.testing.io;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ for ([_]usize{ 100, 3 * header_len }) |len| {
+ const path = try testPath(&buf, tmp, "notes.state");
+ const text = try std.testing.allocator.alloc(u8, len);
+ defer std.testing.allocator.free(text);
+ @memset(text, 'x');
+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text });
+ try std.testing.expectError(error.NotAStateFile, StateFile.open(std.testing.allocator, path));
+ const after = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .unlimited);
+ defer std.testing.allocator.free(after);
+ try std.testing.expectEqualSlices(u8, text, after);
+ }
+}
+
+test "a state file from before element leaves (drat-meout's) keeps every value" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try testPath(&buf, tmp, "game.state");
+ const original = try std.Io.Dir.cwd().readFileAlloc(io, "test/fixtures/drat-meout-v1.state-fixture", gpa, .unlimited);
+ defer gpa.free(original);
+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = original });
+ try std.testing.expectEqualStrings(&file_magic_v1, original[0..8]);
+
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const old = (try readLayout(a, original)).?;
+ try std.testing.expect(old.find("tracker.songs") != null);
+ const h: *const Header = @ptrCast(@alignCast(original.ptr));
+ const live = original[header_len..][0..h.size];
+
+ // The layout the game had when it wrote the file, as a sketch would
+ // describe it: unchanged, so nothing migrates and the header is
+ // rewritten in the new format.
+ const same = try asSketchLayout(a, old, &.{});
+ {
+ var file = try StateFile.open(gpa, path);
+ defer file.close();
+ try std.testing.expectEqual(StateFile.Adoption.unchanged, try file.adopt(gpa, same, NoDefaults.f));
+ try std.testing.expectEqualStrings(&file_magic, &file.header().magic);
+ }
+ var file = try StateFile.open(gpa, path);
+ defer file.close();
+ try std.testing.expectEqual(old.fields.len, file.layout.fields.len);
+ try std.testing.expectEqualSlices(u8, live, file.slot(0));
+
+ // A changed layout (one field gone, one new): every other leaf keeps
+ // its value, the songs included (an unchanged array type, so whole).
+ const changed = try asSketchLayout(a, old, "scene");
+ _ = try file.adopt(gpa, changed, NoDefaults.f);
+ for (old.fields) |leaf| {
+ if (std.mem.eql(u8, leaf.path, "scene")) continue;
+ try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(file.slot(0)));
+ }
+ try std.testing.expectEqual(@as(u8, 0), file.slot(0)[h.size]);
+}
+
+const NoDefaults = struct {
+ fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {}
+};
+
+/// `l` as `abi.Layout`, without the leaf at `drop` and with a new byte
+/// leaf `added` past the end, the type hash changed accordingly.
+fn asSketchLayout(a: std.mem.Allocator, l: Layout, drop: []const u8) !abi.Layout {
+ var fields: std.ArrayList(abi.Field) = .empty;
+ for (l.fields) |leaf| {
+ if (std.mem.eql(u8, leaf.path, drop)) continue;
+ try fields.append(a, .{
+ .path = try a.dupeSentinel(u8, leaf.path, 0),
+ .offset = leaf.offset,
+ .size = leaf.size,
+ .kind = leaf.kind,
+ .hash = leaf.hash,
+ .tags = try a.dupeSentinel(u8, leaf.tags, 0),
+ });
+ }
+ if (drop.len == 0) return .{ .size = l.size, .alignment = l.alignment, .hash = l.hash, .fields = fields.items };
+ try fields.append(a, .{ .path = "added", .offset = @intCast(l.size), .size = 1, .kind = .uint, .hash = abi.layout.hash(u8) });
+ return .{ .size = l.size + 1, .alignment = l.alignment, .hash = l.hash ^ 1, .fields = fields.items };
+}
diff --git a/src/host/overlay.zig b/src/host/overlay.zig
index 919fff6..5219a83 100644
--- a/src/host/overlay.zig
+++ b/src/host/overlay.zig
@@ -16,7 +16,10 @@ fn shade(path: []const u8) abi.Color {
}
pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, state: []const u8, width: f32) !void {
- const rows = (layout.fields.len + 1) / 2;
+ // Arrays show as wholes: their element leaves (`list[].x`) are left out.
+ var top_level: usize = 0;
+ for (layout.fields) |leaf| top_level += @intFromBool(leaf.dims.len == 0);
+ const rows = (top_level + 1) / 2;
const legend_top: f32 = 24;
const hex_top = legend_top + @as(f32, @floatFromInt(rows)) * 14 + 16;
const shown = @min(state.len, shown_bytes);
@@ -26,7 +29,11 @@ pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, s
// Legend: two fixed-width columns filled down then across.
const column = (width - 60) / 2;
- for (layout.fields, 0..) |leaf, i| {
+ var row: usize = 0;
+ for (layout.fields) |leaf| {
+ if (leaf.dims.len != 0) continue;
+ const i = row;
+ row += 1;
var value: std.Io.Writer.Allocating = .init(arena);
try fields.format(leaf, state, &value.writer);
const name = if (leaf.path.len > 26) try std.fmt.allocPrint(arena, "{s}...", .{leaf.path[0..23]}) else leaf.path;
@@ -42,7 +49,7 @@ pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, s
var colors: [shown_bytes]abi.Color = @splat(.{ .r = 0x9f, .g = 0x9f, .b = 0x9f });
for (layout.fields) |leaf| {
- if (leaf.offset >= shown) continue;
+ if (leaf.offset >= shown or leaf.dims.len != 0) continue;
@memset(colors[leaf.offset..@min(shown, leaf.offset + leaf.size)], shade(leaf.path));
}
for (state[0..shown], 0..) |byte, i| {
diff --git a/src/host/probe.zig b/src/host/probe.zig
index 4a693ec..d8ed166 100644
--- a/src/host/probe.zig
+++ b/src/host/probe.zig
@@ -30,6 +30,8 @@ pub fn main(init: std.process.Init) !void {
const file = path orelse fatal("no state file given");
const map = memory.mapReadOnly(file);
if (map.len < memory.header_len) fatal("not a sketchbook state file");
+ const magic = map[0..8];
+ if (!std.mem.eql(u8, magic, &memory.file_magic) and !std.mem.eql(u8, magic, &memory.file_magic_v1)) fatal("not a sketchbook state file");
defer std.posix.munmap(map);
var arena: std.heap.ArenaAllocator = .init(init.gpa);
defer arena.deinit();
@@ -52,9 +54,29 @@ fn show(path: []const u8, layout: memory.Layout, live: []const u8) void {
var w: std.Io.Writer = .fixed(&buf);
std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash });
for (layout.fields) |leaf| {
+ // Whole arrays are shown by their elements' leaves.
+ if (leaf.whole()) continue;
w.end = 0;
- fields.format(leaf, live, &w) catch {};
- std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, leaf.path, w.buffered() });
+ if (leaf.dims.len == 0) {
+ fields.format(leaf, live, &w) catch {};
+ } else {
+ // Elements in index order, the first few.
+ var it = leaf.elements();
+ var n: usize = 0;
+ while (it.next()) |offset| : (n += 1) {
+ if (n == 8) {
+ w.writeAll(" ...") catch {};
+ break;
+ }
+ if (n > 0) w.writeAll(" ") catch {};
+ fields.format(leaf.at(offset), live, &w) catch {};
+ }
+ }
+ var name: [128]u8 = undefined;
+ var nw: std.Io.Writer = .fixed(&name);
+ nw.writeAll(leaf.path) catch {};
+ for (leaf.dims) |d| nw.print(" [{d}]", .{d.count}) catch {};
+ std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, nw.buffered(), w.buffered() });
}
}
diff --git a/src/host/root.zig b/src/host/root.zig
index 2876c0f..8cc15e1 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -59,6 +59,22 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
}
if (linked == null and options.library == null) fatal("no sketch library given (see --help)");
+ // A scripted run from fresh state works on files of its own, moved to
+ // the given path at exit: two runs of one build step (two `zig build`s
+ // at once share its output path) never share a state, store or
+ // recordings file, nor fail on the store's lock.
+ var private_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const given = options.state;
+ const private = script_path != null and options.fresh;
+ if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long");
+ defer if (private) for ([_][]const u8{ "", ".inputs", ".store" }) |suffix| {
+ var from: [std.fs.max_path_bytes + 16]u8 = undefined;
+ var to: [std.fs.max_path_bytes + 16]u8 = undefined;
+ const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue;
+ const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue;
+ _ = std.os.linux.rename(a.ptr, b.ptr);
+ };
+
sdl_heap.install();
{
var host: Host = undefined;
diff --git a/src/host/script.zig b/src/host/script.zig
index cf551cd..7818c6b 100644
--- a/src/host/script.zig
+++ b/src/host/script.zig
@@ -8,21 +8,46 @@
//! cancel what losing focus sends
//! key NAME press and release a key (`sketch.Key` names)
//! type TEXT text input, as typed into a focused field
-//! console LINE run a console command
+//! console LINE run a console command (`console get`
+//! takes no frame: it only reads)
//! frames N advance N frames without input
-//! expect FIELD VALUE compare a state field (enums by name or number)
-//! await FIELD VALUE run frames until it holds (a minute at most)
+//! expect FIELD VALUE compare a state field (enums by name or number);
+//! FIELD may index arrays and vector lanes,
+//! `boids.buffer[3].pos[0]`
+//! expect FIELD VALUE ~T numbers within T of VALUE
+//! await FIELD VALUE [~T] run frames until it holds (a minute at most)
+//! print FIELD write a field's value to stderr (a vector,
+//! array or struct: every value in it), no frame
+//! expect-snapshot N live state equals snapshot N, leaf by leaf
+//! (padding ignored), exactly
+//! expect-log TEXT a recent console line contains TEXT
+//! expect-no-log TEXT no recent console line does
//! expect-audio KEY stream KEY has received samples
//! screenshot FILE save the next frame as PNG
+//! expect-same-screenshot A B [MAX [X Y W H]]
+//! two saved PNGs match, every channel within MAX
+//! (default 0), in the rect if given (pixels)
+//! expect-different-screenshot A B [X Y W H]
+//! two saved PNGs differ somewhere (in the rect)
+//! expect-pixel FILE X Y R G B A [TOL]
+//! a saved PNG's pixel, every channel within TOL
//! load LIBRARY swap in another build of the sketch
//! reload load the watched library again
//! await-reload SECONDS run frames until a build replaces the library
//!
//! `{name}` is replaced by `--define name=value` from the command line.
+//!
+//! Each line but `frames`, `print`, `console get`, the expectations and
+//! `await-reload` is followed by one frame; `update` gets one call per
+//! frame, live or replayed, so
+//! `console play` then `frames N` replays N recorded frames at the
+//! script's 60 Hz.
const std = @import("std");
+const c = @import("c");
const abi = @import("abi");
const Host = @import("Host.zig");
const fields = @import("fields.zig");
+const memory = @import("memory.zig");
pub const frame_ns: u64 = std.time.ns_per_s / 60;
/// The most frames `await` plays: a minute.
@@ -84,28 +109,102 @@ fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []cons
std.debug.print(" console {s}: {t}\n", .{ rest, err });
return err;
};
+ if (std.mem.startsWith(u8, rest, "get ")) return;
+ } else if (eq(u8, command, "print")) {
+ const path = words.next() orelse return error.ExpectedField;
+ var buf: [4096]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
+ error.UnknownField => return error.UnknownField,
+ error.WriteFailed => {},
+ };
+ std.debug.print("{s} = {s}\n", .{ path, w.buffered() });
+ return;
} else if (eq(u8, command, "frames")) {
const count = try std.fmt.parseInt(usize, rest, 10);
for (0..count) |_| try advance(host, now);
return;
} else if (eq(u8, command, "expect") or eq(u8, command, "await")) {
const path = words.next() orelse return error.ExpectedField;
- const want = std.mem.trim(u8, words.rest(), " \t");
- const leaf = host.state.layout.find(path) orelse return error.UnknownField;
+ const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t"));
+ // Looked up again after each frame: a reload may move the field.
+ _ = host.state.layout.find(path) orelse return error.UnknownField;
// `await` plays frames until the field holds the value, for up to a
// minute: for waits whose length is the sketch's business.
if (eq(u8, command, "await")) {
var waited: usize = 0;
- while (!fields.matches(leaf, host.live(), want) and waited < await_limit) : (waited += 1) try advance(host, now);
+ while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now);
}
- if (!fields.matches(leaf, host.live(), want)) {
+ if (!holds(host, path, want, tolerance)) {
var buf: [128]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
- fields.format(leaf, host.live(), &w) catch {};
- std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() });
+ fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) {
+ error.UnknownField => w.writeAll("no such field") catch {},
+ error.WriteFailed => {},
+ };
+ if (tolerance) |t| {
+ std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() });
+ } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() });
+ return error.ExpectationFailed;
+ }
+ return;
+ } else if (eq(u8, command, "expect-snapshot")) {
+ const index = std.fmt.parseInt(usize, rest, 10) catch return error.InvalidSlot;
+ if (!host.timeline.bank.hasSnapshot(index)) return error.EmptySnapshot;
+ if (!same(host, index)) return error.ExpectationFailed;
+ return;
+ } else if (eq(u8, command, "expect-log") or eq(u8, command, "expect-no-log")) {
+ var found = false;
+ for (&host.console.lines) |*l| {
+ if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true;
+ }
+ if (found != eq(u8, command, "expect-log")) {
+ std.debug.print(" console log:\n", .{});
+ for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]});
return error.ExpectationFailed;
}
return;
+ } else if (eq(u8, command, "expect-same-screenshot") or eq(u8, command, "expect-different-screenshot")) {
+ const a = words.next() orelse return error.ExpectedFile;
+ const b = words.next() orelse return error.ExpectedFile;
+ const want_same = eq(u8, command, "expect-same-screenshot");
+ const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0;
+ var rect: ?[4]usize = null;
+ if (words.next()) |x| {
+ var r: [4]usize = undefined;
+ r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect;
+ for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect;
+ rect = r;
+ }
+ const diff = try comparePng(arena, a, b, max, rect);
+ if ((diff.count == 0) != want_same) {
+ if (want_same) {
+ std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] });
+ } else std.debug.print(" {s} and {s} are the same\n", .{ a, b });
+ return error.ExpectationFailed;
+ }
+ return;
+ } else if (eq(u8, command, "expect-pixel")) {
+ const file = words.next() orelse return error.ExpectedFile;
+ var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 };
+ var x: usize = 0;
+ var y: usize = 0;
+ for (0..7) |i| {
+ const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel;
+ if (i < 2) {
+ (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel;
+ } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel;
+ }
+ const tol = n[4];
+ const surface = try loadPng(arena, file);
+ defer c.SDL_DestroySurface(surface);
+ if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot;
+ const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4];
+ for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) {
+ std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] });
+ return error.ExpectationFailed;
+ };
+ return;
} else if (eq(u8, command, "expect-audio")) {
const key = try std.fmt.parseInt(u32, rest, 10);
if (host.input.stream(key).pushed == 0) return error.ExpectationFailed;
@@ -144,6 +243,89 @@ fn held(host: *const Host) u8 {
return abi.Event.withModifiers(mods);
}
+/// "VALUE" or "VALUE ~TOLERANCE".
+fn expected(text: []const u8) !struct { []const u8, ?f64 } {
+ const tilde = std.mem.lastIndexOfScalar(u8, text, '~') orelse return .{ text, null };
+ const tolerance = std.fmt.parseFloat(f64, std.mem.trim(u8, text[tilde + 1 ..], " \t")) catch return error.InvalidTolerance;
+ return .{ std.mem.trim(u8, text[0..tilde], " \t"), tolerance };
+}
+
+fn holds(host: *Host, path: []const u8, want: []const u8, tolerance: ?f64) bool {
+ const leaf = host.state.layout.find(path) orelse return false;
+ const t = tolerance orelse return fields.matches(leaf, host.live(), want);
+ const value = fields.number(leaf, host.live()) orelse return false;
+ const target = std.fmt.parseFloat(f64, want) catch return false;
+ return @abs(value - target) <= t;
+}
+
+/// Live state against snapshot `index`, leaf by leaf; prints the first few
+/// differences.
+fn same(host: *Host, index: usize) bool {
+ const layout = host.state.layout;
+ const live = host.live();
+ const saved = host.timeline.bank.slot(index);
+ var count: usize = 0;
+ for (layout.fields) |leaf| {
+ if (leaf.whole()) continue;
+ var it = leaf.elements();
+ while (it.next()) |offset| {
+ if (std.mem.eql(u8, live[offset..][0..leaf.size], saved[offset..][0..leaf.size])) continue;
+ count += 1;
+ if (count > 5) continue;
+ var buf: [256]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ leaf.name(offset, &w) catch {};
+ w.writeAll(": live ") catch {};
+ fields.format(leaf.at(offset), live, &w) catch {};
+ w.print(", snapshot {d} ", .{index}) catch {};
+ fields.format(leaf.at(offset), saved, &w) catch {};
+ std.debug.print(" {s}\n", .{w.buffered()});
+ }
+ }
+ if (count > 5) std.debug.print(" ... {d} differing values in all\n", .{count});
+ return count == 0;
+}
+
+const PngDiff = struct { count: usize = 0, first: [2]usize = .{ 0, 0 } };
+
+/// Pixels whose channels differ by more than `max`; a size mismatch
+/// counts every pixel.
+fn comparePng(arena: std.mem.Allocator, a: []const u8, b: []const u8, max: u8, rect: ?[4]usize) !PngDiff {
+ const sa = try loadPng(arena, a);
+ defer c.SDL_DestroySurface(sa);
+ const sb = try loadPng(arena, b);
+ defer c.SDL_DestroySurface(sb);
+ if (sa.*.w != sb.*.w or sa.*.h != sb.*.h) return .{ .count = @intCast(@max(sa.*.w * sa.*.h, sb.*.w * sb.*.h, 1)) };
+ var diff: PngDiff = .{};
+ const w: usize = @intCast(sa.*.w);
+ const h: usize = @intCast(sa.*.h);
+ const r = rect orelse [4]usize{ 0, 0, w, h };
+ for (@min(r[1], h)..@min(r[1] + r[3], h)) |y| {
+ const ra: [*]const u8 = @as([*]const u8, @ptrCast(sa.*.pixels.?)) + y * @as(usize, @intCast(sa.*.pitch));
+ const rb: [*]const u8 = @as([*]const u8, @ptrCast(sb.*.pixels.?)) + y * @as(usize, @intCast(sb.*.pitch));
+ for (@min(r[0], w)..@min(r[0] + r[2], w)) |x| {
+ const differs = for (0..4) |i| {
+ const p = ra[x * 4 + i];
+ const q = rb[x * 4 + i];
+ if (@max(p, q) - @min(p, q) > max) break true;
+ } else false;
+ if (!differs) continue;
+ if (diff.count == 0) diff.first = .{ x, y };
+ diff.count += 1;
+ }
+ }
+ return diff;
+}
+
+fn loadPng(arena: std.mem.Allocator, path: []const u8) !*c.SDL_Surface {
+ const loaded = c.SDL_LoadPNG((try arena.dupeSentinel(u8, path, 0)).ptr) orelse {
+ std.debug.print(" {s}: {s}\n", .{ path, c.SDL_GetError() });
+ return error.ScreenshotUnreadable;
+ };
+ defer c.SDL_DestroySurface(loaded);
+ return c.SDL_ConvertSurface(loaded, c.SDL_PIXELFORMAT_RGBA32) orelse error.ScreenshotUnreadable;
+}
+
fn advance(host: *Host, now: *u64) !void {
try host.frame(now.*);
now.* += frame_ns;
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index cd65478..8a5448a 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -3,6 +3,11 @@
//!
//! Playback is host state, not sketch state: wall clocks, modes and cursors
//! must not contaminate byte comparisons between two runs of a sketch.
+//!
+//! Recordings are frames: each frame's events, then its `tick`. Playback,
+//! seek and step only ever stop between frames, and `frames` cuts a run of
+//! events into them, so `update` sees exactly the frames it saw live, one
+//! call each.
const std = @import("std");
const posix = std.posix;
const abi = @import("abi");
@@ -19,13 +24,52 @@ pub const Recording = extern struct {
count: u32,
snapshot: u32,
magic: u32,
- reserved: [3]u32,
+ /// The build that recorded it (`build`, two halves), 0 when unknown.
+ build_low: u32,
+ build_high: u32,
+ reserved: u32,
events: [capacity]abi.Event,
slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8,
pub fn slice(r: *const Recording) []const abi.Event {
return r.events[0..r.count];
}
+ pub fn build(r: *const Recording) u64 {
+ return @as(u64, r.build_high) << 32 | r.build_low;
+ }
+ /// Events up to the end of the last whole frame.
+ pub fn whole(r: *const Recording) usize {
+ return frameStart(r.slice(), r.count);
+ }
+};
+
+/// The largest frame boundary at or before `index`: 0, or just after a tick.
+pub fn frameStart(events: []const abi.Event, index: usize) usize {
+ var i = @min(index, events.len);
+ while (i > 0 and events[i - 1].kind != .tick) i -= 1;
+ return i;
+}
+
+/// Cuts events into frames, each ending with its tick. Events after the
+/// last tick (a frame not finished) are never returned.
+pub fn frames(events: []const abi.Event) Frames {
+ return .{ .events = events };
+}
+
+pub const Frames = struct {
+ events: []const abi.Event,
+ start: usize = 0,
+
+ pub fn next(f: *Frames) ?[]const abi.Event {
+ var i = f.start;
+ while (i < f.events.len) : (i += 1) {
+ if (f.events[i].kind != .tick) continue;
+ const frame = f.events[f.start .. i + 1];
+ f.start = i + 1;
+ return frame;
+ }
+ return null;
+ }
};
comptime {
@@ -65,16 +109,9 @@ pub const Bank = struct {
if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording;
return r;
}
- pub const Diff = struct { count: usize = 0, first: ?usize = null, last: ?usize = null };
- pub fn compare(self: Bank, a: usize, b: usize) Diff {
- var diff: Diff = .{};
- for (self.slot(a), self.slot(b), 0..) |x, y, i| {
- if (x == y) continue;
- diff.count += 1;
- if (diff.first == null) diff.first = i;
- diff.last = i;
- }
- return diff;
+ /// Leaf by leaf (`memory.compare`): padding never differs.
+ pub fn compare(self: Bank, a: usize, b: usize) memory.Diff {
+ return memory.compare(self.state.layout, self.slot(a), self.slot(b));
}
};
@@ -85,37 +122,55 @@ pub const Timeline = struct {
cursor: usize = 0,
position: u64 = 0,
clock: u64 = 0,
+ /// Set whenever live state is restored from a snapshot, for the host
+ /// to reset the input state that went with the old bytes.
+ restored: bool = false,
+
+ /// Restores a snapshot into live state.
+ pub fn restore(self: *Timeline, index: usize) !void {
+ try self.bank.restore(index);
+ self.restored = true;
+ }
- pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64) !void {
+ /// `build` identifies the code recording (0: unknown); `play` warns
+ /// when it differs.
+ pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64, build: u64) !void {
// An unused snapshot captures the current state; an existing one is
// restored, so several recordings can branch from exactly those bytes.
if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot);
- try self.bank.restore(snapshot);
+ try self.restore(snapshot);
const r = self.bank.recording(index);
@memset(std.mem.asBytes(r)[0..32], 0);
r.magic = recording_magic;
r.snapshot = @intCast(snapshot);
+ r.build_low = @truncate(build);
+ r.build_high = @truncate(build >> 32);
self.selected = index;
self.cursor = 0;
self.position = 0;
self.clock = now;
self.mode = .recording;
}
- pub fn capture(self: *Timeline, event: abi.Event) !void {
+ /// Records one frame (its events, then its tick) and rewrites their
+ /// times as recorded, so live `update` sees exactly what a replay will.
+ /// A frame that does not fit ends the recording before it.
+ pub fn capture(self: *Timeline, frame: []abi.Event) !void {
if (self.mode != .recording) return;
const r = self.bank.recording(self.selected);
- if (r.count == capacity) {
+ if (frame.len > capacity - r.count) {
self.mode = .live;
return error.RecordingFull;
}
- var e = event;
- // Queued events can predate the start command. Keep insertion order and
- // nondecreasing times, including several events at the same timestamp.
- e.time = @max(e.time -| self.clock, r.duration);
- r.events[r.count] = e;
- r.count += 1;
- r.duration = e.time;
- self.position = e.time;
+ for (frame) |*e| {
+ // Queued events can predate the start command. Keep insertion
+ // order and nondecreasing times, including several events at the
+ // same timestamp.
+ e.time = @max(e.time -| self.clock, r.duration);
+ r.events[r.count] = e.*;
+ r.count += 1;
+ r.duration = e.time;
+ }
+ self.position = r.duration;
self.cursor = r.count;
}
pub fn stop(self: *Timeline, now: u64) void {
@@ -128,7 +183,7 @@ pub const Timeline = struct {
}
pub fn play(self: *Timeline, index: usize, now: u64) !void {
const r = try self.bank.get(index);
- try self.bank.restore(r.snapshot);
+ try self.restore(r.snapshot);
self.selected = index;
self.cursor = 0;
self.position = 0;
@@ -143,53 +198,61 @@ pub const Timeline = struct {
self.mode = .playing;
}
}
- /// The recorded events due by `now`. Feed them to the same `update` that
- /// live input goes through.
+ /// The recorded frames due by `now`: whole frames, whose ticks are due
+ /// (a frame's input comes before its tick, so input alone is never
+ /// due). Feed them to the same `update` that live input goes through.
pub fn tick(self: *Timeline, now: u64) []const abi.Event {
if (self.mode != .playing) return &.{};
const r = self.bank.recording(self.selected);
self.position = @min(r.duration, self.position +| (now -| self.clock));
self.clock = now;
const start = self.cursor;
- while (self.cursor < r.count and r.events[self.cursor].time <= self.position) self.cursor += 1;
+ var i = self.cursor;
+ while (i < r.count and r.events[i].time <= self.position) : (i += 1) {
+ if (r.events[i].kind == .tick) self.cursor = i + 1;
+ }
if (self.position == r.duration) self.mode = .paused;
return r.events[start..self.cursor];
}
- /// Restores the snapshot and returns the first `count` events to replay,
- /// so seeking backwards works too.
+ /// Restores the snapshot and returns the frames that make up the first
+ /// `count` events (rounded down to a whole frame) to replay, so seeking
+ /// backwards works too.
pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event {
const r = try self.bank.get(self.selected);
- try self.bank.restore(r.snapshot);
- self.cursor = @min(count, r.count);
+ try self.restore(r.snapshot);
+ self.cursor = frameStart(r.slice(), count);
self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time;
self.mode = .paused;
return r.events[0..self.cursor];
}
+ /// To the last frame whose tick is at or before `time`.
pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event {
const r = try self.bank.get(self.selected);
const position = @min(time, r.duration);
var count: usize = 0;
- while (count < r.count and r.events[count].time <= position) count += 1;
+ for (r.slice(), 0..) |e, i| {
+ if (e.time > position) break;
+ if (e.kind == .tick) count = i + 1;
+ }
const events = try self.seekCount(count);
self.position = position;
return events;
}
- /// Moves by `steps` input events, passing over frame ticks.
+ /// Moves by `steps` frames, forwards or back.
pub fn step(self: *Timeline, steps: i64) ![]const abi.Event {
const r = try self.bank.get(self.selected);
- var cursor = self.cursor;
+ const events = r.slice();
+ var cursor = frameStart(events, self.cursor);
var remaining = @abs(steps);
while (remaining > 0) : (remaining -= 1) {
if (steps > 0) {
- while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1;
- if (cursor == r.count) break;
+ const end = r.whole();
+ if (cursor == end) break;
cursor += 1;
- // Include the frame's tick so time-driven sketches advance too.
- while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1;
+ while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1;
} else {
- while (cursor > 0 and r.events[cursor - 1].kind == .tick) cursor -= 1;
if (cursor == 0) break;
- cursor -= 1;
+ cursor = frameStart(events, cursor - 1);
}
}
return self.seekCount(cursor);
@@ -206,3 +269,76 @@ pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 {
};
return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true });
}
+
+test "frames are whole: input waits for its tick, live and in playback" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ // A bank on plain memory: one slot of 8 bytes, snapshot 1 used.
+ var file: memory.StateFile = undefined;
+ file.map = try a.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.slot_count * memory.page);
+ @memset(file.map, 0);
+ file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 0b11, .field_count = 0, .strings_len = 0 };
+ file.layout = .{};
+ const inputs = try a.alignedAlloc(u8, .fromByteUnits(memory.page), recording_len);
+ @memset(inputs, 0);
+ var t: Timeline = .{ .bank = .{ .state = &file, .inputs = inputs } };
+ // Frame k: a move at 10k ms, its tick at 10k + 5 ms; then a move with
+ // no tick (a frame cut off).
+ try t.startRecording(0, 1, 1000, 7);
+ try std.testing.expect(t.restored);
+ for (0..4) |k| {
+ var frame = [_]abi.Event{
+ .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) },
+ abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667),
+ };
+ try t.capture(&frame);
+ // Live update sees the recorded times.
+ try std.testing.expectEqual(@as(u64, k * 10_000_000 + 5_000_000), frame[1].time);
+ }
+ const r = t.bank.recording(0);
+ r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 };
+ r.count += 1;
+ t.stop(1000 + 41_000_000);
+ try std.testing.expectEqual(@as(u64, 7), r.build());
+
+ try t.play(0, 0);
+ var delivered: usize = 0;
+ // Every moment between 0 and the end, 1 ms apart.
+ var now: u64 = 0;
+ while (t.mode == .playing) : (now += 1_000_000) {
+ const events = t.tick(now);
+ if (events.len == 0) continue;
+ try std.testing.expectEqual(abi.Event.Kind.tick, events[events.len - 1].kind);
+ var it = frames(events);
+ while (it.next()) |frame| {
+ try std.testing.expectEqual(@as(usize, 2), frame.len);
+ delivered += 1;
+ }
+ }
+ try std.testing.expectEqual(@as(usize, 4), delivered);
+ try std.testing.expectEqual(@as(usize, 8), t.cursor);
+
+ // A seek between a frame's input and its tick stops before the frame.
+ try std.testing.expectEqual(@as(usize, 4), (try t.seekTime(22_000_000)).len);
+ try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(r.count)).len);
+ try std.testing.expectEqual(@as(usize, 6), (try t.step(-1)).len);
+ try std.testing.expectEqual(@as(usize, 8), (try t.step(5)).len);
+ try std.testing.expectEqual(@as(usize, 2), (try t.step(-3)).len);
+ // The cut-off frame is never fed.
+ var it = frames(r.slice());
+ var n: usize = 0;
+ while (it.next()) |_| n += 1;
+ try std.testing.expectEqual(@as(usize, 4), n);
+}
+
+test "a tick's dt reads back the same live and replayed" {
+ // E4: nanoseconds do not survive f32 seconds; both sides read the f32.
+ for ([_]u64{ 16_666_667, 16_666_666, 15_000_001, 33_333_333, 0, 1 }) |dt| {
+ const live = abi.Event.tick(5, dt);
+ var recorded = live;
+ recorded.time = 0;
+ try std.testing.expectEqual(live.tickDt(), recorded.tickDt());
+ try std.testing.expect(@abs(@as(i64, @intCast(live.tickDt())) - @as(i64, @intCast(dt))) < 8);
+ }
+}
diff --git a/src/layout.zig b/src/layout.zig
index 5c97ca1..3fb381b 100644
--- a/src/layout.zig
+++ b/src/layout.zig
@@ -1,9 +1,16 @@
//! Comptime reflection of a sketch's memory into `abi.Layout`.
//!
-//! Structs are flattened into dotted leaf paths; everything else (arrays,
-//! optionals, unions) is one leaf. Each leaf carries a structural hash of its
-//! type, so a host can tell, across a reload, which bytes still mean the same
-//! thing.
+//! Structs are flattened into dotted leaf paths, and arrays and vectors into
+//! element leaves: `boids: [64]Boid` gives one leaf `boids[].pos[]` for every
+//! boid's every lane, with each `[]`'s count and stride in `dims`, rather
+//! than 128 leaves. Each array also stays as a whole (`boids`, kind
+//! `array`), which a host copies in one piece while its type is unchanged.
+//! Optionals, unions and packed structs are one leaf. Each leaf carries a
+//! structural hash of its type, so a host can tell, across a reload, which
+//! bytes still mean the same thing. Padding is in no leaf.
+//!
+//! A concrete path names indices (`boids[3].pos[1]`); `match` resolves one
+//! against a leaf's pattern at lookup time.
//!
//! What each kind of sketch memory may hold:
//! - State is saved to disk and snapshotted: no pointers, and no host
@@ -26,7 +33,7 @@ pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout {
.session => {},
}
const Leaves = struct {
- const list = flatten(T, "", 0);
+ const list = flatten(T, "", 0, &.{});
const fields: [list.len]abi.Field = list[0..list.len].*;
};
break :blk .{
@@ -38,25 +45,50 @@ pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout {
};
}
-fn flatten(comptime T: type, comptime prefix: []const u8, comptime base: usize) []const abi.Field {
+pub const Dim = abi.Field.Dim;
+/// The most arrays a leaf may sit in.
+pub const max_rank = 8;
+
+fn flatten(comptime T: type, comptime prefix: []const u8, comptime base: usize, comptime dims: []const Dim) []const abi.Field {
comptime {
- if (@typeInfo(T) != .@"struct") return &.{leaf(T, if (prefix.len == 0) "value" else prefix, base)};
- var leaves: []const abi.Field = &.{};
- const s = @typeInfo(T).@"struct";
- for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| {
- if (attrs.@"comptime" or @sizeOf(F) == 0) continue;
- const path = if (prefix.len == 0) name else prefix ++ "." ++ name;
- const offset = base + @offsetOf(T, name);
- leaves = leaves ++ if (@typeInfo(F) == .@"struct" and @typeInfo(F).@"struct".backing_integer == null)
- flatten(F, path, offset)
- else
- &[_]abi.Field{leaf(F, path, offset)};
+ const here = if (prefix.len == 0) "value" else prefix;
+ switch (@typeInfo(T)) {
+ .@"struct" => |s| if (s.backing_integer == null) {
+ var leaves: []const abi.Field = &.{};
+ for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| {
+ if (attrs.@"comptime" or @sizeOf(F) == 0) continue;
+ const path = if (prefix.len == 0) name else prefix ++ "." ++ name;
+ leaves = leaves ++ flatten(F, path, base + @offsetOf(T, name), dims);
+ }
+ return leaves;
+ },
+ .array => |a| return elements(T, a.child, a.len, here, base, dims),
+ .vector => |v| if (lanes(v.child)) return elements(T, v.child, v.len, here, base, dims),
+ else => {},
}
- return leaves;
+ return &.{leaf(T, here, base, dims)};
+ }
+}
+
+/// The whole array, then its elements' leaves.
+fn elements(comptime T: type, comptime Child: type, comptime len: usize, comptime path: []const u8, comptime base: usize, comptime dims: []const Dim) []const abi.Field {
+ comptime {
+ if (dims.len == max_rank) @compileError("arrays nested deeper than " ++ std.fmt.comptimePrint("{d}", .{max_rank}) ++ " in sketch memory: " ++ path);
+ const whole = &[_]abi.Field{leaf(T, path, base, dims)};
+ if (@sizeOf(Child) == 0) return whole;
+ return whole ++ flatten(Child, path ++ "[]", base, dims ++ &[_]Dim{.{ .count = len, .stride = @sizeOf(Child) }});
}
}
-fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize) abi.Field {
+/// Vector lanes are addressable bytes only for whole-byte numbers.
+fn lanes(comptime Child: type) bool {
+ return switch (@typeInfo(Child)) {
+ .int, .float => @bitSizeOf(Child) == 8 * @sizeOf(Child),
+ else => false,
+ };
+}
+
+fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize, comptime dims: []const Dim) abi.Field {
comptime {
const kind: abi.Field.Kind = switch (@typeInfo(T)) {
.int => |i| if (i.signedness == .signed) .int else .uint,
@@ -64,8 +96,10 @@ fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize) abi
.bool => .bool,
.@"enum" => .@"enum",
.array => .array,
+ .vector => |v| if (lanes(v.child)) .array else .bytes,
else => .bytes,
};
+ const stored = dims[0..dims.len].*;
return .{
.path = std.fmt.comptimePrint("{s}", .{path}),
.offset = offset,
@@ -73,10 +107,54 @@ fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize) abi
.kind = kind,
.hash = hash(T),
.tags = if (kind == .@"enum") tags(T) else "",
+ .rank = dims.len,
+ .dims = &stored,
};
}
}
+/// The byte offset of `path`, which names indices (`list[3].pos[1]`), from
+/// a leaf's own offset, when it is an element of the leaf with `pattern`
+/// (`list[].pos[]`) and `dims`; null when it is not, or out of range.
+pub fn match(pattern: []const u8, dims: []const Dim, path: []const u8) ?usize {
+ var p: usize = 0;
+ var q: usize = 0;
+ var d: usize = 0;
+ var offset: usize = 0;
+ while (p < pattern.len) {
+ if (pattern[p] == '[' and p + 1 < pattern.len and pattern[p + 1] == ']') {
+ if (q >= path.len or path[q] != '[') return null;
+ const start = q + 1;
+ q = start;
+ while (q < path.len and std.ascii.isDigit(path[q])) q += 1;
+ if (q == start or q >= path.len or path[q] != ']' or d >= dims.len) return null;
+ const index = std.fmt.parseInt(u32, path[start..q], 10) catch return null;
+ if (index >= dims[d].count) return null;
+ offset += @as(usize, index) * dims[d].stride;
+ d += 1;
+ q += 1;
+ p += 2;
+ } else {
+ if (q >= path.len or path[q] != pattern[p]) return null;
+ p += 1;
+ q += 1;
+ }
+ }
+ return if (q == path.len) offset else null;
+}
+
+pub const Resolved = struct { field: abi.Field, offset: usize };
+
+/// The field `path` names, indices resolved: for readers of a sketch's own
+/// reflected layout (the web host's `sk_field`).
+pub fn resolve(fields: []const abi.Field, path: []const u8) ?Resolved {
+ for (fields) |f| {
+ const delta = match(std.mem.span(f.path), f.dims[0..f.rank], path) orelse continue;
+ return .{ .field = f, .offset = f.offset + delta };
+ }
+ return null;
+}
+
fn check(comptime T: type, comptime memory: []const u8, comptime path: []const u8, comptime pointers: bool) void {
comptime {
if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError(memory ++ " cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session.");
@@ -146,17 +224,44 @@ pub fn signature(comptime T: type) []const u8 {
}
}
-test "leaves flatten structs, keep arrays whole and reject nothing pointer-free" {
+test "leaves flatten structs, and arrays into element leaves" {
const Inner = extern struct { a: u8 = 0, b: enum(u8) { x, y = 5 } = .x };
const S = extern struct { inner: Inner = .{}, list: [4]f32 = @splat(0), flag: bool = false };
const l = of(S, .state);
const fields = l.fields;
- try std.testing.expectEqual(4, fields.len);
+ try std.testing.expectEqual(5, fields.len);
try std.testing.expectEqualStrings("inner.a", std.mem.span(fields[0].path));
try std.testing.expectEqualStrings("inner.b", std.mem.span(fields[1].path));
try std.testing.expectEqualStrings("x=0,y=5", std.mem.span(fields[1].tags));
try std.testing.expectEqual(abi.Field.Kind.array, fields[2].kind);
+ try std.testing.expectEqualStrings("list", std.mem.span(fields[2].path));
try std.testing.expectEqual(@as(u32, 4), fields[2].offset);
+ try std.testing.expectEqualStrings("list[]", std.mem.span(fields[3].path));
+ try std.testing.expectEqual(abi.Field.Kind.float, fields[3].kind);
+ try std.testing.expectEqual(@as(u8, 1), fields[3].rank);
+ try std.testing.expectEqual(Dim{ .count = 4, .stride = 4 }, fields[3].dims[0]);
try std.testing.expect(hash([4]f32) != hash([5]f32));
try std.testing.expect(hash(enum(u8) { a }) != hash(enum(u8) { a, b }));
}
+
+test "vector lanes and nested array elements resolve by index" {
+ const Boid = struct { pos: @Vector(2, f32) = @splat(0), mood: enum(u8) { calm = 1, wild = 2 } = .calm };
+ const S = struct { boids: struct { buffer: [8]Boid = @splat(.{}), len: u32 = 0 } = .{}, grid: [3][2]u16 = @splat(@splat(0)), mask: @Vector(4, bool) = @splat(false) };
+ var s: S = .{};
+ s.boids.buffer[3].pos[1] = 7.5;
+ s.grid[2][1] = 9;
+ const fields = of(S, .state).fields;
+ const bytes = std.mem.asBytes(&s);
+ const pos = resolve(fields, "boids.buffer[3].pos[1]").?;
+ try std.testing.expectEqualStrings("boids.buffer[].pos[]", std.mem.span(pos.field.path));
+ try std.testing.expectEqual(@as(f32, 7.5), @as(f32, @bitCast(bytes[pos.offset..][0..4].*)));
+ const cell = resolve(fields, "grid[2][1]").?;
+ try std.testing.expectEqual(@as(u16, 9), std.mem.readInt(u16, bytes[cell.offset..][0..2], .little));
+ try std.testing.expect(resolve(fields, "boids.buffer[8].pos[0]") == null);
+ try std.testing.expect(resolve(fields, "boids.buffer[1].pos[2]") == null);
+ try std.testing.expect(resolve(fields, "boids.buffer[].pos[0]") == null);
+ try std.testing.expect(resolve(fields, "boids.buffer[1]x") == null);
+ try std.testing.expectEqual(abi.Field.Kind.@"enum", resolve(fields, "boids.buffer[0].mood").?.field.kind);
+ try std.testing.expectEqual(abi.Field.Kind.bytes, resolve(fields, "mask").?.field.kind);
+ try std.testing.expectEqual(abi.Field.Kind.array, resolve(fields, "boids.buffer[2].pos").?.field.kind);
+}
diff --git a/src/math/noise.zig b/src/math/noise.zig
new file mode 100644
index 0000000..07764cf
--- /dev/null
+++ b/src/math/noise.zig
@@ -0,0 +1,157 @@
+//! Noise, without a table: see `noise`.
+const std = @import("std");
+
+/// Smooth noise in 0..1, like Processing's and p5's `noise()`: four octaves
+/// of gradient noise, each at twice the frequency and half the weight of the
+/// one before, around 0.5. Neighbouring inputs give neighbouring values; one
+/// unit is roughly one bump. Pass 0 for unused axes (`noise(seed, t, 0, 0)`
+/// is 1D noise).
+///
+/// Its spread is Processing's: standard deviation about 0.11 (0.12 in 1D),
+/// almost all of it within 0.1..0.9, so `noise → angle` turns all the way
+/// round as in the book. Each octave is shifted by an irrational offset,
+/// so integer inputs are not special (plain Perlin noise is 0 at every
+/// lattice point). The mean is 0.5 (Processing's is about 0.47).
+///
+/// No table and no state: the lattice gradients come from hashing the
+/// integer coordinates with `seed`, so the seed can be a State field and
+/// changing it is free. Only f32 arithmetic and integer hashing, no
+/// library calls, so the bits are the same on every target (native and
+/// wasm32, Debug and release; tested). Coordinates are clamped to ±1e9.
+pub fn noise(seed: u32, x: f32, y: f32, z: f32) f32 {
+ var sum: f32 = 0;
+ var weight: f32 = 0.5;
+ var frequency: f32 = 1;
+ for (octave_offsets, 0..) |o, octave| {
+ const s = seed +% @as(u32, @intCast(octave)) *% 0x9e3779b9;
+ sum += weight * gradient(s, x * frequency + o[0], y * frequency + o[1], z * frequency + o[2]);
+ weight *= 0.5;
+ frequency *= 2;
+ }
+ // One octave of 3D gradient noise has a deviation of about 0.2; the
+ // octaves together about 0.16, scaled here to Processing's 0.11.
+ return std.math.clamp(0.5 + 0.7 * sum, 0, 1);
+}
+
+/// Fractions of multiples of the golden ratio (and of the plastic number,
+/// for z): far from every lattice point and from each other.
+const octave_offsets = [4][3]f32{
+ .{ 0.6180340, 0.3819660, 0.7548777 },
+ .{ 0.2360680, 0.7639320, 0.5097553 },
+ .{ 0.8541020, 0.1458980, 0.2646330 },
+ .{ 0.4721360, 0.5278640, 0.0195106 },
+};
+
+/// Ken Perlin's improved noise at one octave, about -1..1, with the
+/// permutation table replaced by a hash.
+fn gradient(seed: u32, x: f32, y: f32, z: f32) f32 {
+ const fx = @floor(std.math.clamp(x, -1e9, 1e9));
+ const fy = @floor(std.math.clamp(y, -1e9, 1e9));
+ const fz = @floor(std.math.clamp(z, -1e9, 1e9));
+ const ix: u32 = @bitCast(@as(i32, @intFromFloat(fx)));
+ const iy: u32 = @bitCast(@as(i32, @intFromFloat(fy)));
+ const iz: u32 = @bitCast(@as(i32, @intFromFloat(fz)));
+ const dx = clampUnit(x - fx);
+ const dy = clampUnit(y - fy);
+ const dz = clampUnit(z - fz);
+ const u = fade(dx);
+ const v = fade(dy);
+ const w = fade(dz);
+ const x0 = lerp(grad(lattice(seed, ix, iy, iz), dx, dy, dz), grad(lattice(seed, ix +% 1, iy, iz), dx - 1, dy, dz), u);
+ const x1 = lerp(grad(lattice(seed, ix, iy +% 1, iz), dx, dy - 1, dz), grad(lattice(seed, ix +% 1, iy +% 1, iz), dx - 1, dy - 1, dz), u);
+ const x2 = lerp(grad(lattice(seed, ix, iy, iz +% 1), dx, dy, dz - 1), grad(lattice(seed, ix +% 1, iy, iz +% 1), dx - 1, dy, dz - 1), u);
+ const x3 = lerp(grad(lattice(seed, ix, iy +% 1, iz +% 1), dx, dy - 1, dz - 1), grad(lattice(seed, ix +% 1, iy +% 1, iz +% 1), dx - 1, dy - 1, dz - 1), u);
+ return lerp(lerp(x0, x1, v), lerp(x2, x3, v), w);
+}
+
+/// Past ±2^24 a float has no fraction left, and rounding may give 1.
+fn clampUnit(t: f32) f32 {
+ return @min(@max(t, 0), 1);
+}
+
+fn fade(t: f32) f32 {
+ return t * t * t * (t * (t * 6 - 15) + 10);
+}
+
+fn lerp(a: f32, b: f32, t: f32) f32 {
+ return a + t * (b - a);
+}
+
+/// A well-mixed 32-bit hash of a lattice point (lowbias32's finalizer).
+fn lattice(seed: u32, x: u32, y: u32, z: u32) u32 {
+ var h = seed ^ (x *% 0x8da6b343) ^ (y *% 0xd8163841) ^ (z *% 0xcb1ab31f);
+ h ^= h >> 16;
+ h *%= 0x7feb352d;
+ h ^= h >> 15;
+ h *%= 0x846ca68b;
+ h ^= h >> 16;
+ return h;
+}
+
+/// One of Perlin's 12 edge gradients (4 of them twice), dotted with the
+/// offset.
+fn grad(hash: u32, x: f32, y: f32, z: f32) f32 {
+ const h = hash >> 28;
+ const u = if (h < 8) x else y;
+ const v = if (h < 4) y else if (h == 12 or h == 14) x else z;
+ return (if (h & 1 == 0) u else -u) + (if (h & 2 == 0) v else -v);
+}
+
+/// Golden values, as bits: the test runs on native targets and, through
+/// `zig build test`, on wasm32-wasi too, so a change in either shows.
+const noise_goldens = [_]struct { seed: u32, p: [3]f32, bits: u32 }{
+ .{ .seed = 0, .p = .{ 0, 0, 0 }, .bits = 0x3f14f2bf },
+ .{ .seed = 0, .p = .{ 0.5, 0, 0 }, .bits = 0x3ef55b7e },
+ .{ .seed = 1, .p = .{ 0.3, 0.7, 0 }, .bits = 0x3f01da7c },
+ .{ .seed = 7, .p = .{ 12.25, -3.5, 0.125 }, .bits = 0x3efb37d9 },
+ .{ .seed = 42, .p = .{ 1000.1, 2000.2, 3.3 }, .bits = 0x3f142994 },
+ .{ .seed = 0xdeadbeef, .p = .{ -0.01, 5.5, 99.9 }, .bits = 0x3edcff5c },
+};
+
+test "noise is smooth, in 0..1, and the same bits everywhere" {
+ var lo: f32 = 1;
+ var hi: f32 = 0;
+ var previous = noise(3, 0, 0, 1.5);
+ for (1..4000) |i| {
+ const t = @as(f32, @floatFromInt(i)) * 0.01;
+ const n = noise(3, t, t * 0.5, 1.5);
+ try std.testing.expect(n >= 0 and n <= 1);
+ try std.testing.expect(@abs(n - previous) < 0.1);
+ lo = @min(lo, n);
+ hi = @max(hi, n);
+ previous = n;
+ }
+ try std.testing.expect(hi - lo > 0.5);
+ try std.testing.expect(noise(1, 0.3, 0.7, 0) != noise(2, 0.3, 0.7, 0));
+ for (noise_goldens) |g| {
+ const n = noise(g.seed, g.p[0], g.p[1], g.p[2]);
+ std.testing.expectEqual(g.bits, @as(u32, @bitCast(n))) catch |err| {
+ std.debug.print("noise({d}, {d}, {d}, {d}) = {d} (0x{x})\n", .{ g.seed, g.p[0], g.p[1], g.p[2], n, @as(u32, @bitCast(n)) });
+ return err;
+ };
+ }
+}
+
+test "noise has Processing's spread, and lattice points are not special" {
+ // Processing's noise() on this grid (flow_field's, 0.1 apart, z = 0):
+ // deviation 0.111, range 0.08..0.81, over 50 seeds.
+ var sum: f64 = 0;
+ var squares: f64 = 0;
+ var count: f64 = 0;
+ for (0..50) |seed| for (0..32) |i| for (0..18) |j| {
+ const v: f64 = noise(@intCast(seed), @as(f32, @floatFromInt(i)) * 0.1, @as(f32, @floatFromInt(j)) * 0.1, 0);
+ sum += v;
+ squares += v * v;
+ count += 1;
+ };
+ const mean = sum / count;
+ const deviation = @sqrt(squares / count - mean * mean);
+ try std.testing.expect(@abs(mean - 0.5) < 0.02);
+ try std.testing.expect(deviation > 0.095 and deviation < 0.13);
+ var at_half: u32 = 0;
+ for (0..100) |i| {
+ const v = noise(9, @floatFromInt(i), @floatFromInt(i * 7 % 13), 0);
+ if (v == 0.5) at_half += 1;
+ }
+ try std.testing.expectEqual(@as(u32, 0), at_half);
+}
diff --git a/src/vector/geom.zig b/src/math/root.zig
index b80c55a..f9f2ffe 100644
--- a/src/vector/geom.zig
+++ b/src/math/root.zig
@@ -1,6 +1,11 @@
-//! 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.
+//! Points, vectors, affine transforms, cubic Béziers and noise: the one
+//! geometry module, `sk.math` in sketches and `vector.geom` in the vector
+//! library. Pure functions over `@Vector(2, f32)`, so `+`, `-`, `*` and
+//! `+=` work on points directly, as on a shader's `vec2`.
+//!
+//! In the vector library every path is a list of cubics, lines included, as
+//! in manim: one shape of data makes morphing and partial drawing plain
+//! arithmetic.
const std = @import("std");
pub const Vec = @Vector(2, f32);
@@ -31,6 +36,32 @@ pub fn normalize(a: Vec) Vec {
const l = length(a);
return if (l > 0) a / splat(l) else a;
}
+/// `a` times `k`: Zig does not broadcast a scalar over a vector.
+pub fn scale(a: Vec, k: f32) Vec {
+ return a * splat(k);
+}
+pub fn distance(a: Vec, b: Vec) f32 {
+ return length(b - a);
+}
+/// `a` in the same direction, `len` long; zero stays zero. PVector's `setMag`.
+pub fn withLength(a: Vec, len: f32) Vec {
+ return scale(normalize(a), len);
+}
+/// `a`, shortened to `max` if longer. PVector's `limit`.
+pub fn clampLength(a: Vec, max: f32) Vec {
+ const l2 = dot(a, a);
+ return if (l2 > max * max) scale(a, max / @sqrt(l2)) else a;
+}
+/// The direction of `a` in radians, from +x toward +y (clockwise on a
+/// y-down screen). PVector's `heading`. Not for shader code: `atan2` is
+/// table-driven, which SPIR-V's logical addressing forbids.
+pub fn angle(a: Vec) f32 {
+ return std.math.atan2(a[1], a[0]);
+}
+/// The unit vector at `radians`. PVector's `fromAngle`.
+pub fn unit(radians: f32) Vec {
+ return .{ @cos(radians), @sin(radians) };
+}
/// `[a c e; b d f]`, SVG's `matrix(a b c d e f)`.
pub const Affine = struct {
@@ -54,6 +85,14 @@ pub const Affine = struct {
const s = @sin(radians);
return .{ .a = c, .b = s, .c = -s, .d = c };
}
+ /// Moves the origin to `at`, turned by `radians`: Processing's
+ /// `translate(at); rotate(radians)`.
+ pub fn place(at: Vec, radians: f32) Affine {
+ var m = rotate(radians);
+ m.e = at[0];
+ m.f = at[1];
+ return m;
+ }
pub fn skew(x: f32, y: f32) Affine {
return .{ .b = @tan(y), .c = @tan(x) };
}
@@ -81,6 +120,11 @@ pub const Affine = struct {
pub fn scaleFactor(m: Affine) f32 {
return @sqrt(@abs(m.determinant()));
}
+ /// How much the transform stretches lengths at most, nearly: the
+ /// longer of its two axes.
+ pub fn maxScale(m: Affine) f32 {
+ return @max(@sqrt(m.a * m.a + m.b * m.b), @sqrt(m.c * m.c + m.d * m.d));
+ }
pub fn invert(m: Affine) Affine {
const det = m.determinant();
if (det == 0) return .{};
@@ -204,19 +248,33 @@ pub fn arc(out: *std.ArrayList(Cubic), gpa: std.mem.Allocator, p0: Vec, radii: V
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 theta = start;
var from = p0;
for (0..pieces) |i| {
- const next = angle + step;
- const a: Vec = .{ @cos(angle), @sin(angle) };
+ const next = theta + step;
+ const a: Vec = .{ @cos(theta), @sin(theta) };
const b: Vec = .{ @cos(next), @sin(next) };
const to = if (i + 1 == pieces) p1 else m.apply(b);
try out.append(gpa, .{ from, m.apply(a + perp(a) * splat(-k)), m.apply(b - perp(b) * splat(-k)), to });
from = to;
- angle = next;
+ theta = next;
}
}
+pub const noise = @import("noise.zig").noise;
+
+/// A float in `lo..hi`: Processing's `random(lo, hi)`. `r` is any
+/// `std.Random` (keep a concrete `std.Random.Xoshiro256` in State and pass
+/// `s.rng.random()`); this only saves spelling out the lerp.
+pub fn uniform(r: std.Random, lo: f32, hi: f32) f32 {
+ return std.math.lerp(lo, hi, r.float(f32));
+}
+
+/// A unit vector in a uniformly random direction: `PVector.random2D()`.
+pub fn randomUnit(r: std.Random) Vec {
+ return unit(uniform(r, 0, std.math.tau));
+}
+
test "affine composition and inversion round trip" {
const m = Affine.translate(10, 5).mul(.rotate(0.7)).mul(.scale(2, 3));
const p = vec(3, -4);
@@ -237,3 +295,33 @@ test "a half-circle arc stays on the circle" {
// Sweep flag 1 in y-down space goes through negative y.
try std.testing.expect(eval(cubics.items[0], 1)[1] < -9.9);
}
+
+test "vector helpers" {
+ const v = vec(3, 4);
+ try std.testing.expectEqual(@as(f32, 5), length(v));
+ try std.testing.expectEqual(vec(6, 8), scale(v, 2));
+ try std.testing.expectEqual(@as(f32, 5), distance(.{ 0, 0 }, v));
+ try std.testing.expectApproxEqAbs(@as(f32, 10), length(withLength(v, 10)), 1e-5);
+ try std.testing.expectEqual(vec(0, 0), withLength(.{ 0, 0 }, 3));
+ try std.testing.expectApproxEqAbs(@as(f32, 2.5), length(clampLength(v, 2.5)), 1e-5);
+ try std.testing.expectEqual(v, clampLength(v, 7));
+ try std.testing.expectApproxEqAbs(@as(f32, std.math.pi / 2.0), angle(.{ 0, 1 }), 1e-6);
+ const u = unit(angle(v));
+ try std.testing.expectApproxEqAbs(@as(f32, 0.6), u[0], 1e-6);
+ const p = Affine.place(.{ 10, 20 }, std.math.pi / 2.0).apply(.{ 1, 0 });
+ try std.testing.expectApproxEqAbs(@as(f32, 10), p[0], 1e-5);
+ try std.testing.expectApproxEqAbs(@as(f32, 21), p[1], 1e-5);
+}
+
+test "uniform stays in range and randomUnit is unit length" {
+ var prng: std.Random.Xoshiro256 = .init(3);
+ for (0..1000) |_| {
+ const x = uniform(prng.random(), -2, 5);
+ try std.testing.expect(x >= -2 and x < 5);
+ try std.testing.expectApproxEqAbs(@as(f32, 1), length(randomUnit(prng.random())), 1e-5);
+ }
+}
+
+test {
+ _ = @import("noise.zig");
+}
diff --git a/src/sketch/clock.zig b/src/sketch/clock.zig
new file mode 100644
index 0000000..e64e2a8
--- /dev/null
+++ b/src/sketch/clock.zig
@@ -0,0 +1,127 @@
+//! A fixed-step clock: how many steps of `1 / hz` seconds the frame's ticks
+//! owe. Keep it in State, so it migrates and replays with the rest.
+const std = @import("std");
+const abi = @import("abi");
+
+/// `for (0..s.clock.steps(in)) |_| step(s);` in `update`.
+///
+/// It reads only the `tick` events in `in.events`, never the host's clock,
+/// so a replay gives the same steps. The steps of each tick are counted on
+/// their own, so an update with N ticks gives exactly the steps of N
+/// updates with one tick each (the host feeds one tick per update anyway).
+/// A tick owes at most `max_steps`: after a stall the simulation slows down
+/// instead of trying to catch up forever; the rest of that debt is dropped.
+/// `set clock.hz 30` from the console is slow motion.
+///
+/// Time is counted in integer nanoseconds, from `Event.tickDt`, so it adds
+/// up the same everywhere. Two allowances keep a clock at the display's
+/// rate from juddering (0 steps one frame, 2 the next):
+/// - a tick within `slack` of a whole number of steps counts as exactly
+/// that many (a 60 Hz frame is 16 666 666 ns, a step at 60 Hz
+/// 16 666 667 ns: 60 frames are 60 steps, not 59);
+/// - a step is taken once `owed` is within `slack` of it, so `owed` may
+/// end a little below zero, and a frame that comes a little early still
+/// steps.
+/// `slack` is an eighth of a step (2 ms at 60 Hz), which covers the jitter
+/// of a live frame clock.
+pub const Clock = struct {
+ hz: f32 = 60,
+ /// Nanoseconds received and not yet stepped; down to `-slack` after
+ /// an early step.
+ owed: i64 = 0,
+ /// Steps taken since the clock was made: a frame counter for the
+ /// simulation (Processing's `frameCount`).
+ count: u64 = 0,
+
+ pub const max_steps = 8;
+
+ /// Steps to take now; adds them to `count`.
+ pub fn steps(c: *Clock, in: *const abi.Input) u32 {
+ var n: u32 = 0;
+ for (in.events) |e| if (e.kind == .tick) {
+ n += c.tick(e.tickDt());
+ };
+ return n;
+ }
+
+ /// The steps one tick of `dt` nanoseconds owes: the per-event form, for
+ /// an update that handles its events in order (`c.tick(e.tickDt())`).
+ pub fn tick(c: *Clock, dt: u64) u32 {
+ const step = c.stepNs();
+ if (step == 0 or dt == 0) return 0;
+ const slack = @divTrunc(step, 8);
+ var t: i64 = @intCast(@min(dt, std.time.ns_per_hour));
+ const whole = @divTrunc(t + @divTrunc(step, 2), step) * step;
+ if (whole > 0 and @abs(t - whole) <= slack) t = whole;
+ c.owed = @max(c.owed, -slack) + t;
+ var n: u32 = 0;
+ while (c.owed >= step - slack and n < max_steps) : (n += 1) c.owed -= step;
+ if (n == max_steps and c.owed > 0) c.owed = @rem(c.owed, step);
+ c.count += n;
+ return n;
+ }
+
+ /// One step in nanoseconds; 0 when `hz` is not a positive rate.
+ pub fn stepNs(c: *const Clock) i64 {
+ if (!(c.hz > 1e-3) or !(c.hz < 1e9)) return 0;
+ return @intFromFloat(@round(std.time.ns_per_s / @as(f64, c.hz)));
+ }
+};
+
+fn tickEvent(dt_ns: u64) abi.Event {
+ return abi.Event.tick(0, dt_ns);
+}
+
+test "N updates of one tick each step exactly as one update of N ticks" {
+ var events: [600]abi.Event = undefined;
+ var prng: std.Random.Xoshiro256 = .init(1);
+ for (&events) |*e| e.* = tickEvent(prng.random().uintLessThan(u64, 50_000_000));
+ events[300] = tickEvent(2 * std.time.ns_per_s); // a stall: capped
+ var one: Clock = .{};
+ var per: [events.len]u32 = undefined;
+ for (&events, &per) |*e, *n| n.* = one.steps(&.{ .events = e[0..1] });
+ var all: Clock = .{};
+ const total = all.steps(&.{ .events = &events });
+ var sum: u32 = 0;
+ for (per) |n| sum += n;
+ try std.testing.expectEqual(sum, total);
+ try std.testing.expectEqual(std.mem.toBytes(one), std.mem.toBytes(all));
+ try std.testing.expectEqual(@as(u32, Clock.max_steps), per[300]);
+ try std.testing.expectEqual(@as(u64, total), all.count);
+}
+
+test "sixty script frames are sixty steps at 60 Hz, one each" {
+ var c: Clock = .{};
+ // What the host and scripts send: ns_per_s / 60, through the f32 tick.
+ const events = [_]abi.Event{ .{ .kind = .mouse_move, .x = 5 }, tickEvent(std.time.ns_per_s / 60) };
+ for (0..6000) |_| try std.testing.expectEqual(@as(u32, 1), c.steps(&.{ .events = &events }));
+ try std.testing.expectEqual(@as(u64, 6000), c.count);
+ c.hz = 0;
+ try std.testing.expectEqual(@as(u32, 0), c.steps(&.{ .events = &events }));
+}
+
+test "a jittery 60 Hz frame clock gives one step a frame; slower rates divide evenly" {
+ var prng: std.Random.Xoshiro256 = .init(7);
+ var c: Clock = .{};
+ var half: Clock = .{ .hz = 30 };
+ var halves: u32 = 0;
+ // Frames shown at vsync, each measured up to 1.5 ms late.
+ var last: u64 = 0;
+ for (0..1200) |i| {
+ const shown = (i + 1) * std.time.ns_per_s / 60 + prng.random().uintLessThan(u64, 1_500_000);
+ const dt = shown - last;
+ last = shown;
+ try std.testing.expectEqual(@as(u32, 1), c.tick(dt));
+ const h = half.tick(dt);
+ try std.testing.expectEqual(@as(u32, @intFromBool(i % 2 == 1)), h);
+ halves += h;
+ }
+ try std.testing.expectEqual(@as(u32, 600), halves);
+ // A dropped frame is two steps.
+ try std.testing.expectEqual(@as(u32, 2), c.tick(33_333_333));
+ // 144 Hz on a 60 Hz display: 2.4 steps a frame on average, exactly.
+ var fast: Clock = .{ .hz = 144 };
+ var n: u32 = 0;
+ for (0..600) |_| n += fast.tick(16_666_667);
+ try std.testing.expect(n >= 1439 and n <= 1441);
+}
diff --git a/src/sketch/derived.zig b/src/sketch/derived.zig
new file mode 100644
index 0000000..c42a322
--- /dev/null
+++ b/src/sketch/derived.zig
@@ -0,0 +1,56 @@
+//! Data computed from State, kept out of it.
+const std = @import("std");
+const abi = @import("abi");
+
+/// A `T` computed in `draw` from a few State fields, kept in Session: the
+/// segments of a Koch curve from its generation, an L-system's sentence,
+/// a tessellation too big to redo every frame. State keeps what `update`
+/// changes (the generation, one byte), so snapshots and replays stay
+/// small; this keeps what follows from it, however big it grows.
+///
+/// `key` says what the value was built from: pass the State fields it
+/// depends on, as a number (`s.generation`) or a hash. `stale` is true when
+/// the key differs, and on the first frame after a reload, since new code
+/// may compute it differently; then rebuild `value`. A seek or a replay
+/// changes the key like an update does, so what is drawn always follows
+/// State, and the timeline needs nothing more.
+///
+/// pub const Session = struct { curve: sk.Derived(std.ArrayList(Segment)) = .{ .value = .empty } };
+/// if (ss.curve.stale(s.generation, f.in)) try koch(&ss.curve.value, f.session, s.generation);
+///
+/// After a failed rebuild call `forget`, so the next frame tries again.
+pub fn Derived(comptime T: type) type {
+ return struct {
+ const Self = @This();
+
+ value: T,
+ /// The key `value` was built for; null before the first build or
+ /// after `forget`.
+ key: ?u64 = null,
+
+ /// True when `value` must be rebuilt for `key`; it is then taken
+ /// as built for `key`.
+ pub fn stale(d: *Self, key: u64, in: *const abi.Input) bool {
+ if (d.key == key and !in.reloaded) return false;
+ d.key = key;
+ return true;
+ }
+
+ /// The next `stale` is true whatever its key.
+ pub fn forget(d: *Self) void {
+ d.key = null;
+ }
+ };
+}
+
+test "stale when the key changes, after a reload, and after forget" {
+ var d: Derived(u32) = .{ .value = 0 };
+ const live: abi.Input = .{};
+ try std.testing.expect(d.stale(3, &live));
+ try std.testing.expect(!d.stale(3, &live));
+ try std.testing.expect(d.stale(4, &live));
+ try std.testing.expect(d.stale(4, &.{ .reloaded = true }));
+ try std.testing.expect(!d.stale(4, &live));
+ d.forget();
+ try std.testing.expect(d.stale(4, &live));
+}
diff --git a/src/sketch/draw.zig b/src/sketch/draw.zig
new file mode 100644
index 0000000..c151ab2
--- /dev/null
+++ b/src/sketch/draw.zig
@@ -0,0 +1,1024 @@
+//! Circles, lines and polygons, filled and stroked, as `Command.shape`s.
+//!
+//! Two levels, both plain functions with no state of their own:
+//!
+//! - **L1, tessellation.** A `Tessellation` is a caller-owned value: points,
+//! subpath ends and triangle indices, appended to by `fillCircle`,
+//! `strokeCircle`, `fillPolygon`, `strokePolygon`, `strokePolyline` and
+//! `strokeLine` with the caller's allocator, each under an `Affine`. Emit
+//! it with `f.shape(&t, color)`, batch many shapes into one, inspect it,
+//! or upload its triangles to a GPU pass of your own.
+//! - **L2, a Pen.** `Pen` is plain data (fill, stroke, width, transform);
+//! `circle`, `line` and `polygon` tessellate into `f.scratch` and emit one
+//! shape for the fill and one for the stroke. On out-of-memory they log
+//! and drop the shape, as `Frame.emit` does.
+//!
+//! What a shape guarantees, so both hosts draw the same pixels: its
+//! triangles are disjoint and positively wound (clockwise on a y-down
+//! screen, after the transform, mirrored or not), and its subpaths cover
+//! exactly their union: one positively wound outline, followed by its
+//! holes wound the other way (a ring's inside). The web fills each such
+//! group as one nonzero path, native draws the triangles, so each shape
+//! blends once on both. Shapes batched into one `Tessellation` are drawn
+//! one after another by both hosts, so where they overlap translucent
+//! colours blend twice on both. The one known difference: a stroke that
+//! overlaps itself (a self-crossing polyline, or segments shorter than the
+//! stroke is wide at an acute turn) blends twice natively where it
+//! overlaps, and once on the web.
+//!
+//! Curves are flattened to within `tolerance` canvas pixels, measured after
+//! the transform, so a circle scaled up gets more segments. Native shapes
+//! are not antialiased (like `rect`); the web canvas antialiases edges.
+const std = @import("std");
+const abi = @import("abi");
+const math = @import("math");
+const root = @import("root.zig");
+
+const Allocator = std.mem.Allocator;
+const Vec = math.Vec;
+const Affine = math.Affine;
+const Color = abi.Color;
+const splat = math.splat;
+
+/// How a stroke turns a corner (Processing's `strokeJoin`).
+pub const Join = enum { miter, round, bevel };
+/// How an open stroke ends (Processing's `strokeCap`).
+pub const Cap = enum { butt, round, square };
+
+/// A stroke's shape, for `strokePath`.
+pub const Stroke = struct {
+ width: f32 = 1,
+ join: Join = .miter,
+ cap: Cap = .butt,
+ /// Joined back to the first point, with no caps.
+ closed: bool = false,
+ /// Mitered corners reach at most this many half-widths from the
+ /// vertex, and are bevelled beyond.
+ miter_limit: f32 = miter_limit,
+};
+
+/// How far, in canvas pixels, a flattened circle may stray from the true
+/// one.
+pub const tolerance: f32 = 0.25;
+/// A stroke's outer corner is mitered up to this many half-widths from the
+/// vertex, and bevelled beyond (SVG's default).
+pub const miter_limit: f32 = 4;
+
+pub const Error = Allocator.Error;
+
+/// Shapes as data: `points` in canvas coordinates, the subpaths
+/// `points[ends[i - 1] .. ends[i]]`, and triangles, `indices` into `points`
+/// three at a time. The fields of `Command.shape`; see the module comment
+/// for what the functions here guarantee about them.
+pub const Tessellation = struct {
+ points: std.ArrayList([2]f32) = .empty,
+ ends: std.ArrayList(u32) = .empty,
+ indices: std.ArrayList(u32) = .empty,
+
+ pub const empty: Tessellation = .{};
+
+ pub fn deinit(t: *Tessellation, gpa: Allocator) void {
+ t.points.deinit(gpa);
+ t.ends.deinit(gpa);
+ t.indices.deinit(gpa);
+ t.* = .empty;
+ }
+
+ pub fn clearRetainingCapacity(t: *Tessellation) void {
+ t.points.clearRetainingCapacity();
+ t.ends.clearRetainingCapacity();
+ t.indices.clearRetainingCapacity();
+ }
+
+ /// The triangles as a flat vertex list (three points each), for a GPU
+ /// pass of your own.
+ pub fn triangles(t: *const Tessellation, gpa: Allocator) Error![][2]f32 {
+ const out = try gpa.alloc([2]f32, t.indices.items.len);
+ for (out, t.indices.items) |*v, i| v.* = t.points.items[i];
+ return out;
+ }
+
+ // -- The append API: the pieces the shape functions are made of. --
+
+ /// Appends a point already in canvas coordinates; returns its index.
+ pub fn appendPoint(t: *Tessellation, gpa: Allocator, p: Vec) Error!u32 {
+ const index: u32 = @intCast(t.points.items.len);
+ try t.points.append(gpa, .{ p[0], p[1] });
+ return index;
+ }
+
+ /// Ends the current subpath at the last point appended.
+ pub fn endSubpath(t: *Tessellation, gpa: Allocator) Error!void {
+ try t.ends.append(gpa, @intCast(t.points.items.len));
+ }
+
+ /// Appends the triangle `a`, `b`, `c` (point indices), wound
+ /// positively whatever order they come in. A triangle with no area is
+ /// left out.
+ pub fn appendTriangle(t: *Tessellation, gpa: Allocator, a: u32, b: u32, c: u32) Error!void {
+ const pa = vec(t.points.items[a]);
+ const area = math.cross(vec(t.points.items[b]) - pa, vec(t.points.items[c]) - pa);
+ if (area == 0 or std.math.isNan(area)) return;
+ try t.indices.appendSlice(gpa, if (area > 0) &.{ a, b, c } else &.{ a, c, b });
+ }
+
+ // -- Shapes --
+
+ /// A disc of `radius` around `center`.
+ pub fn fillCircle(t: *Tessellation, gpa: Allocator, center: Vec, radius: f32, xf: Affine) Error!void {
+ if (!(radius > 0)) return;
+ const mark = t.begin();
+ const n = circleSegments(radius, xf);
+ const first = try t.ring(gpa, center, radius, n, xf);
+ try t.endSubpath(gpa);
+ for (1..n - 1) |i| try t.appendTriangle(gpa, first, first + @as(u32, @intCast(i)), first + @as(u32, @intCast(i + 1)));
+ t.finish(mark);
+ }
+
+ /// A ring `width` wide centred on the circle of `radius`: a disc when
+ /// the width reaches the centre.
+ pub fn strokeCircle(t: *Tessellation, gpa: Allocator, center: Vec, radius: f32, width: f32, xf: Affine) Error!void {
+ const hw = width / 2;
+ if (!(hw > 0) or !(radius >= 0)) return;
+ if (radius - hw <= 0) return t.fillCircle(gpa, center, radius + hw, xf);
+ const mark = t.begin();
+ const n = circleSegments(radius + hw, xf);
+ const outer = try t.ring(gpa, center, radius + hw, n, xf);
+ try t.endSubpath(gpa);
+ // The hole, wound the other way: the same angles, backwards.
+ const inner: u32 = @intCast(t.points.items.len);
+ for (0..n) |k| _ = try t.appendPoint(gpa, xf.apply(center + math.scale(math.unit(angleOf(n - 1 - k, n)), radius - hw)));
+ try t.endSubpath(gpa);
+ for (0..n) |k| {
+ const o0 = outer + @as(u32, @intCast(k));
+ const o1 = outer + @as(u32, @intCast((k + 1) % n));
+ const in_0 = inner + @as(u32, @intCast(n - 1 - k));
+ const in_1 = inner + @as(u32, @intCast((2 * n - 2 - k) % n));
+ try t.appendTriangle(gpa, o0, o1, in_1);
+ try t.appendTriangle(gpa, o0, in_1, in_0);
+ }
+ t.finish(mark);
+ }
+
+ /// The inside of a simple polygon, convex or not (ear clipping), in
+ /// either winding. A polygon that crosses itself is filled as a fan
+ /// where clipping finds no ear, which may not match the web.
+ pub fn fillPolygon(t: *Tessellation, gpa: Allocator, points: []const Vec, xf: Affine) Error!void {
+ if (points.len < 3) return;
+ const mark = t.begin();
+ const first: u32 = @intCast(t.points.items.len);
+ for (points) |p| _ = try t.appendPoint(gpa, xf.apply(p));
+ // Repeated points (a closing copy of the first, say) clip badly.
+ var n: u32 = @intCast(points.len);
+ while (n > 1 and std.meta.eql(t.points.items[first + n - 1], t.points.items[first])) n -= 1;
+ t.points.shrinkRetainingCapacity(first + n);
+ try t.endSubpath(gpa);
+ if (n >= 3) try t.clip(gpa, first, n);
+ t.finish(mark);
+ }
+
+ /// The outline of a closed polygon, `width` wide, with mitered corners
+ /// (bevelled past `miter_limit`): `strokePath` with `.closed = true`.
+ pub fn strokePolygon(t: *Tessellation, gpa: Allocator, points: []const Vec, width: f32, xf: Affine) Error!void {
+ return t.stroke(gpa, points, .{ .width = width, .closed = true }, xf);
+ }
+
+ /// A line through `points`, `width` wide, with mitered corners (bevelled
+ /// past `miter_limit`) and square-cut ends: `strokePath` with the
+ /// defaults.
+ pub fn strokePolyline(t: *Tessellation, gpa: Allocator, points: []const Vec, width: f32, xf: Affine) Error!void {
+ return t.stroke(gpa, points, .{ .width = width }, xf);
+ }
+
+ /// A line through `points`, open or closed, with the joins and caps
+ /// `style` asks for. Its triangles stay disjoint as everywhere here: a
+ /// round join is the circular segment beyond the bevel, a round cap the
+ /// half disc beyond the end, a square cap a butt cap moved out by half
+ /// the width. A zero-length open path is a dot (round or square caps)
+ /// or nothing (butt), as in SVG.
+ pub fn strokePath(t: *Tessellation, gpa: Allocator, points: []const Vec, style: Stroke, xf: Affine) Error!void {
+ return t.stroke(gpa, points, style, xf);
+ }
+
+ /// The rect's area.
+ pub fn fillRect(t: *Tessellation, gpa: Allocator, r: math.Rect, xf: Affine) Error!void {
+ if (!(r.w > 0) or !(r.h > 0)) return;
+ const mark = t.begin();
+ const first: u32 = @intCast(t.points.items.len);
+ for (rectCorners(r)) |p| _ = try t.appendPoint(gpa, xf.apply(p));
+ try t.endSubpath(gpa);
+ try t.appendTriangle(gpa, first, first + 1, first + 2);
+ try t.appendTriangle(gpa, first, first + 2, first + 3);
+ t.finish(mark);
+ }
+
+ /// The rect's outline, `width` wide, centred on its edge, with mitered
+ /// corners (Processing's `rect` with `noFill`).
+ pub fn strokeRect(t: *Tessellation, gpa: Allocator, r: math.Rect, width: f32, xf: Affine) Error!void {
+ if (!(r.w > 0) or !(r.h > 0)) return;
+ const cs = rectCorners(r);
+ return t.stroke(gpa, &cs, .{ .width = width, .closed = true }, xf);
+ }
+
+ /// The segment from `a` to `b`, `width` wide, with round ends; a dot
+ /// when `a` is `b`.
+ pub fn strokeLine(t: *Tessellation, gpa: Allocator, a: Vec, b: Vec, width: f32, xf: Affine) Error!void {
+ const hw = width / 2;
+ if (!(hw > 0)) return;
+ const d = b - a;
+ if (math.length(d) == 0) return t.fillCircle(gpa, a, hw, xf);
+ const mark = t.begin();
+ // A convex stadium: half a circle around each end.
+ const half = @max(circleSegments(hw, xf) / 2, 2);
+ const heading = math.angle(d);
+ const first: u32 = @intCast(t.points.items.len);
+ for ([_]Vec{ b, a }, 0..) |end, side| {
+ const start = heading - std.math.pi / 2.0 + @as(f32, @floatFromInt(side)) * std.math.pi;
+ for (0..half + 1) |k| {
+ const theta = start + std.math.pi * @as(f32, @floatFromInt(k)) / @as(f32, @floatFromInt(half));
+ _ = try t.appendPoint(gpa, xf.apply(end + math.scale(math.unit(theta), hw)));
+ }
+ }
+ try t.endSubpath(gpa);
+ const count: u32 = 2 * (half + 1);
+ for (1..count - 1) |i| try t.appendTriangle(gpa, first, first + @as(u32, @intCast(i)), first + @as(u32, @intCast(i + 1)));
+ t.finish(mark);
+ }
+
+ // -- Internals --
+
+ const Mark = struct { points: u32, ends: u32 };
+
+ fn begin(t: *const Tessellation) Mark {
+ return .{ .points = @intCast(t.points.items.len), .ends = @intCast(t.ends.items.len) };
+ }
+
+ /// Winds the subpaths added since `mark` positively: if the one that
+ /// encloses most area runs the wrong way (a mirroring transform, or
+ /// points given counterclockwise), every one of them is reversed, which
+ /// keeps holes holes. Triangles keep their geometry, so their indices
+ /// are remapped.
+ fn finish(t: *Tessellation, mark: Mark) void {
+ var largest: f32 = 0;
+ var start = mark.points;
+ for (t.ends.items[mark.ends..]) |end| {
+ const a = signedArea(t.points.items[start..end]);
+ if (@abs(a) > @abs(largest)) largest = a;
+ start = end;
+ }
+ if (largest >= 0) return;
+ start = mark.points;
+ for (t.ends.items[mark.ends..]) |end| {
+ std.mem.reverse([2]f32, t.points.items[start..end]);
+ start = end;
+ }
+ // Indices that point into this shape's subpaths follow the flip.
+ for (t.indices.items) |*i| {
+ if (i.* < mark.points) continue;
+ var s = mark.points;
+ for (t.ends.items[mark.ends..]) |end| {
+ if (i.* < end) {
+ i.* = end - 1 - (i.* - s);
+ break;
+ }
+ s = end;
+ }
+ }
+ }
+
+ /// `n` points around a circle, at increasing angles; returns the first.
+ fn ring(t: *Tessellation, gpa: Allocator, center: Vec, radius: f32, n: u32, xf: Affine) Error!u32 {
+ const first: u32 = @intCast(t.points.items.len);
+ try t.points.ensureUnusedCapacity(gpa, n);
+ for (0..n) |k| _ = try t.appendPoint(gpa, xf.apply(center + math.scale(math.unit(angleOf(k, n)), radius)));
+ return first;
+ }
+
+ /// Triangulates the polygon `points[first..][0..n]` by ear clipping
+ /// (a fan when it is convex).
+ fn clip(t: *Tessellation, gpa: Allocator, first: u32, n: u32) Error!void {
+ const pts = t.points.items[first..][0..n];
+ const sign: f32 = if (signedArea(pts) >= 0) 1 else -1;
+ const P = struct {
+ fn at(all: []const [2]f32, i: u32) Vec {
+ return vec(all[i]);
+ }
+ };
+ var convex = true;
+ for (0..n) |i| {
+ const a = P.at(pts, @intCast(i));
+ const b = P.at(pts, @intCast((i + 1) % n));
+ const c = P.at(pts, @intCast((i + 2) % n));
+ if (sign * math.cross(b - a, c - b) < 0) convex = false;
+ }
+ if (convex) {
+ for (1..n - 1) |i| try t.appendTriangle(gpa, first, first + @as(u32, @intCast(i)), first + @as(u32, @intCast(i + 1)));
+ return;
+ }
+ const remaining = try gpa.alloc(u32, n);
+ defer gpa.free(remaining);
+ for (remaining, 0..) |*r, i| r.* = @intCast(i);
+ var len: usize = n;
+ var guard: usize = 0;
+ var i: usize = 0;
+ while (len > 3) {
+ const ia = remaining[(i + len - 1) % len];
+ const ib = remaining[i % len];
+ const ic = remaining[(i + 1) % len];
+ const a = P.at(pts, ia);
+ const b = P.at(pts, ib);
+ const c = P.at(pts, ic);
+ const turn = sign * math.cross(b - a, c - b);
+ var ear = turn > 0;
+ if (ear) for (remaining[0..len]) |j| {
+ if (j == ia or j == ib or j == ic) continue;
+ const p = P.at(pts, j);
+ if (@reduce(.And, p == a) or @reduce(.And, p == b) or @reduce(.And, p == c)) continue;
+ if (inTriangle(p, a, b, c, sign)) {
+ ear = false;
+ break;
+ }
+ };
+ // A straight or zero-length corner is cut without a triangle.
+ if (ear or turn == 0 or guard > len) {
+ if (turn != 0) try t.appendTriangle(gpa, first + ia, first + ib, first + ic);
+ const at = i % len;
+ std.mem.copyForwards(u32, remaining[at .. len - 1], remaining[at + 1 .. len]);
+ len -= 1;
+ guard = 0;
+ if (at < i) i -= 1;
+ i %= len;
+ } else {
+ i = (i + 1) % len;
+ guard += 1;
+ }
+ }
+ try t.appendTriangle(gpa, first + remaining[0], first + remaining[1], first + remaining[2]);
+ }
+
+ const Joint = struct {
+ /// The inner corners meet at one point (`inner`), and the bodies are
+ /// cut back to it: disjoint. Otherwise the bodies overlap on the
+ /// inner side, around the vertex.
+ clean: bool,
+ /// Which side (+1 along the segment normal, -1 against it) is outer.
+ outer: f32,
+ inner: Vec,
+ miter: ?Vec,
+ vertex: Vec,
+ };
+
+ const Body = struct { start: [2]Vec, end: [2]Vec };
+
+ /// Points appended on an arc, between two corners already in the
+ /// outline: `count` of them from `first`, starting next to `from`.
+ const Arc = struct { first: u32 = 0, count: u32 = 0, from: u32 = 0 };
+
+ /// The arc around `center` from `center + from` turning by `sweep`
+ /// radians, its end points left out (they are corners already).
+ fn appendArc(t: *Tessellation, gpa: Allocator, center: Vec, from: Vec, sweep: f32, from_index: u32, xf: Affine) Error!Arc {
+ const radius = math.length(from);
+ const whole: f32 = @floatFromInt(circleSegments(radius, xf));
+ const pieces: u32 = @intFromFloat(@max(1, @ceil(@abs(sweep) / std.math.tau * whole)));
+ const arc: Arc = .{ .first = @intCast(t.points.items.len), .count = pieces - 1, .from = from_index };
+ for (1..pieces) |i| {
+ const theta = sweep * @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(pieces));
+ const c = @cos(theta);
+ const s = @sin(theta);
+ _ = try t.appendPoint(gpa, xf.apply(center + Vec{ from[0] * c - from[1] * s, from[0] * s + from[1] * c }));
+ }
+ return arc;
+ }
+
+ /// The circular segment between an arc and its chord, as a fan from
+ /// the arc's first corner to `to`.
+ fn fanArc(t: *Tessellation, gpa: Allocator, arc: Arc, to: u32) Error!void {
+ var previous = arc.first;
+ if (arc.count == 0) return;
+ for (1..arc.count) |i| {
+ const next = arc.first + @as(u32, @intCast(i));
+ try t.appendTriangle(gpa, arc.from, previous, next);
+ previous = next;
+ }
+ try t.appendTriangle(gpa, arc.from, previous, to);
+ }
+
+ fn stroke(t: *Tessellation, gpa: Allocator, input: []const Vec, style: Stroke, xf: Affine) Error!void {
+ const hw = style.width / 2;
+ if (!(hw > 0) or input.len == 0) return;
+ // Consecutive repeats make no direction.
+ const pts = try gpa.alloc(Vec, input.len);
+ defer gpa.free(pts);
+ var n: usize = 0;
+ for (input) |p| {
+ if (n > 0 and @reduce(.And, p == pts[n - 1])) continue;
+ pts[n] = p;
+ n += 1;
+ }
+ if (style.closed) while (n > 1 and @reduce(.And, pts[n - 1] == pts[0])) {
+ n -= 1;
+ };
+ if (n < 2) {
+ // A zero-length open path: a dot where its caps have area (SVG).
+ if (style.closed) return;
+ return switch (style.cap) {
+ .butt => {},
+ .round => t.fillCircle(gpa, pts[0], hw, xf),
+ .square => t.fillPolygon(gpa, &.{ pts[0] + Vec{ -hw, -hw }, pts[0] + Vec{ hw, -hw }, pts[0] + Vec{ hw, hw }, pts[0] + Vec{ -hw, hw } }, xf),
+ };
+ }
+ if (n == 2 and style.closed) {
+ var open = style;
+ open.closed = false;
+ open.cap = .butt;
+ return t.stroke(gpa, pts[0..2], open, xf);
+ }
+ const closed = style.closed;
+ if (!closed and style.cap == .square) {
+ // Square caps are butt caps half a width further out.
+ pts[0] -= math.withLength(pts[1] - pts[0], hw);
+ pts[n - 1] += math.withLength(pts[n - 1] - pts[n - 2], hw);
+ }
+ const segments = if (closed) n else n - 1;
+ const joints = if (closed) n else n - 2;
+
+ const dirs = try gpa.alloc(Vec, segments);
+ defer gpa.free(dirs);
+ const lens = try gpa.alloc(f32, segments);
+ defer gpa.free(lens);
+ for (dirs, lens, 0..) |*d, *l, i| {
+ const v = pts[(i + 1) % n] - pts[i];
+ l.* = math.length(v);
+ d.* = v / splat(l.*);
+ }
+ const bodies = try gpa.alloc(Body, segments);
+ defer gpa.free(bodies);
+ for (bodies, dirs, 0..) |*body, d, i| {
+ const nrm = math.scale(math.perp(d), hw);
+ body.* = .{ .start = .{ pts[i] + nrm, pts[i] - nrm }, .end = .{ pts[(i + 1) % n] + nrm, pts[(i + 1) % n] - nrm } };
+ }
+ const limit = @max(style.miter_limit, 1);
+ const js = try gpa.alloc(Joint, joints);
+ defer gpa.free(js);
+ for (js, 0..) |*j, k| {
+ // Joint k joins segment a = k (open: k) to b = k + 1.
+ const a = if (closed) (k + segments - 1) % segments else k;
+ const b = (a + 1) % segments;
+ const v = pts[(a + 1) % n];
+ const na = math.perp(dirs[a]);
+ const nb = math.perp(dirs[b]);
+ const turn = math.cross(dirs[a], dirs[b]);
+ const outer: f32 = if (turn > 0) 1 else -1;
+ const cos1 = 1 + math.dot(na, nb);
+ // How far back along each segment the inner corners meet.
+ const back = if (cos1 > 1e-6) hw * @abs(turn) / cos1 else std.math.inf(f32);
+ const budget_a = if (closed or a > 0) lens[a] / 2 else lens[a];
+ const budget_b = if (closed or b + 1 < segments) lens[b] / 2 else lens[b];
+ const miter_vec = if (cos1 > 1e-6) math.scale(na + nb, hw / cos1) else splat(0);
+ const mitered = style.join == .miter and cos1 >= 2 / (limit * limit) and @abs(turn) > 1e-6;
+ j.* = .{
+ .clean = back <= budget_a and back <= budget_b,
+ .outer = outer,
+ .inner = v - math.scale(miter_vec, outer),
+ .miter = if (mitered) v + math.scale(miter_vec, outer) else null,
+ .vertex = v,
+ };
+ const side: usize = if (outer > 0) 1 else 0; // the inner side's corner index
+ if (j.clean) {
+ bodies[a].end[side] = j.inner;
+ bodies[b].start[side] = j.inner;
+ }
+ }
+
+ const mark = t.begin();
+ // Corner indices per body: [start+, end+, end-, start-].
+ const corners = try gpa.alloc([4]u32, segments);
+ defer gpa.free(corners);
+ const joint_points = try gpa.alloc([2]?u32, joints); // miter, pivot
+ defer gpa.free(joint_points);
+ for (joint_points) |*jp| jp.* = .{ null, null };
+ const arcs = try gpa.alloc(Arc, joints);
+ defer gpa.free(arcs);
+ @memset(arcs, .{});
+ var caps: [2]Arc = .{ .{}, .{} }; // end, start
+ const round_join = style.join == .round;
+
+ // The `+` side forward, then the `-` side backward: one outline
+ // when open, two loops (outer and inner) when closed. A clean inner
+ // corner is one point shared by the bodies on either side of it.
+ for ([_]f32{ 1, -1 }) |side| {
+ const c: usize = if (side > 0) 0 else 1;
+ const loop_start: u32 = @intCast(t.points.items.len);
+ var previous: ?u32 = null;
+ for (0..segments) |s_| {
+ const s = if (side > 0) s_ else segments - 1 - s_;
+ const body = bodies[s];
+ const first_corner = xf.apply(if (side > 0) body.start[c] else body.end[c]);
+ const last_corner = xf.apply(if (side > 0) body.end[c] else body.start[c]);
+ const fi = if (previous != null and std.meta.eql(t.points.items[previous.?], xy(first_corner))) previous.? else try t.appendPoint(gpa, first_corner);
+ const closing = closed and s_ + 1 == segments and std.meta.eql(t.points.items[loop_start], xy(last_corner));
+ const li = if (closing) loop_start else try t.appendPoint(gpa, last_corner);
+ if (side > 0) {
+ corners[s][0] = fi;
+ corners[s][1] = li;
+ } else {
+ corners[s][2] = fi;
+ corners[s][3] = li;
+ }
+ previous = li;
+ // The joint after this body, in travel order.
+ const has_joint = if (side > 0) (closed or s + 1 < segments) else (closed or s > 0);
+ if (!has_joint) continue;
+ const k = if (side > 0) (if (closed) (s + 1) % segments else s) else (if (closed) s else s - 1);
+ const j = js[k];
+ if (j.outer == side) {
+ if (j.miter) |m| joint_points[k][0] = try t.appendPoint(gpa, xf.apply(m));
+ if (round_join) {
+ // From this body's corner to the next body's, around the vertex.
+ const next = if (side > 0) (s + 1) % segments else (s + segments - 1) % segments;
+ const from = (if (side > 0) body.end[c] else body.start[c]) - j.vertex;
+ const to = (if (side > 0) bodies[next].start[c] else bodies[next].end[c]) - j.vertex;
+ const sweep = std.math.atan2(math.cross(from, to), math.dot(from, to));
+ arcs[k] = try t.appendArc(gpa, j.vertex, from, sweep, li, xf);
+ }
+ } else if (!j.clean) {
+ joint_points[k][1] = try t.appendPoint(gpa, xf.apply(j.vertex));
+ }
+ }
+ if (!closed and style.cap == .round) {
+ // Half a turn from this side's last corner to the other side's.
+ const at = if (side > 0) pts[n - 1] else pts[0];
+ const corner = if (side > 0) bodies[segments - 1].end[0] else bodies[0].start[1];
+ caps[c] = try t.appendArc(gpa, at, corner - at, std.math.pi, previous.?, xf);
+ previous = null;
+ }
+ if (closed) try t.endSubpath(gpa);
+ }
+ if (!closed) try t.endSubpath(gpa);
+
+ for (corners) |cs| {
+ try t.appendTriangle(gpa, cs[0], cs[1], cs[2]);
+ try t.appendTriangle(gpa, cs[0], cs[2], cs[3]);
+ }
+ for (js, joint_points, arcs, 0..) |j, jp, arc, k| {
+ const a = if (closed) (k + segments - 1) % segments else k;
+ const b = (a + 1) % segments;
+ const outer_end = if (j.outer > 0) corners[a][1] else corners[a][2];
+ const outer_start = if (j.outer > 0) corners[b][0] else corners[b][3];
+ const inner = if (j.clean) (if (j.outer > 0) corners[a][2] else corners[a][1]) else jp[1].?;
+ try t.appendTriangle(gpa, inner, outer_end, outer_start);
+ if (jp[0]) |m| try t.appendTriangle(gpa, outer_end, m, outer_start);
+ if (round_join) try t.fanArc(gpa, arc, if (arc.from == outer_end) outer_start else outer_end);
+ }
+ if (!closed and style.cap == .round) {
+ try t.fanArc(gpa, caps[0], corners[segments - 1][2]);
+ try t.fanArc(gpa, caps[1], corners[0][0]);
+ }
+ t.finish(mark);
+ }
+};
+
+fn vec(p: [2]f32) Vec {
+ return .{ p[0], p[1] };
+}
+
+fn xy(p: Vec) [2]f32 {
+ return .{ p[0], p[1] };
+}
+
+fn rectCorners(r: math.Rect) [4]Vec {
+ return .{ .{ r.x, r.y }, .{ r.x + r.w, r.y }, .{ r.x + r.w, r.y + r.h }, .{ r.x, r.y + r.h } };
+}
+
+fn angleOf(k: usize, n: u32) f32 {
+ return 2 * std.math.pi * @as(f32, @floatFromInt(k)) / @as(f32, @floatFromInt(n));
+}
+
+/// Twice nothing: the shoelace sum, positive for clockwise on a y-down
+/// screen.
+fn signedArea(points: []const [2]f32) f32 {
+ var sum: f32 = 0;
+ for (points, 0..) |p, i| {
+ const q = points[(i + 1) % points.len];
+ sum += p[0] * q[1] - q[0] * p[1];
+ }
+ return sum / 2;
+}
+
+fn inTriangle(p: Vec, a: Vec, b: Vec, c: Vec, sign: f32) bool {
+ return sign * math.cross(b - a, p - a) >= 0 and sign * math.cross(c - b, p - b) >= 0 and sign * math.cross(a - c, p - c) >= 0;
+}
+
+/// Segments for a whole circle of `radius` under `xf`, so that no point of
+/// the polygon is more than `tolerance` canvas pixels inside the circle.
+pub fn circleSegments(radius: f32, xf: Affine) u32 {
+ const r = radius * xf.maxScale();
+ if (!(r > tolerance)) return 8;
+ const n = @ceil(std.math.pi / std.math.acos(1 - tolerance / r));
+ return @intFromFloat(std.math.clamp(n, 8, 1024));
+}
+
+// ---------------------------------------------------------------------------
+// L2: a Pen
+
+/// How `circle`, `line`, `polyline`, `polygon`, `rect` and `point` draw:
+/// plain data, so it can be a `const`, a State field, or a copy changed
+/// for one call. `transformed` is Processing's push-translate-rotate; the
+/// copy going out of scope is the pop. `fill = null` is `noFill()`,
+/// `stroke = null` is `noStroke()`.
+pub const Pen = struct {
+ fill: ?Color = null,
+ stroke: ?Color = null,
+ /// The stroke's width, in the pen's (transformed) units.
+ width: f32 = 1,
+ /// Corners of `polyline`, `polygon` and `rect` strokes.
+ join: Join = .miter,
+ /// Ends of `line` and `polyline`; a `point` is round with `.round`,
+ /// square otherwise. Processing's defaults, both.
+ cap: Cap = .round,
+ xf: Affine = .identity,
+
+ /// This pen, drawing in a space placed by `m` inside its own.
+ pub fn transformed(p: Pen, m: Affine) Pen {
+ var q = p;
+ q.xf = p.xf.mul(m);
+ return q;
+ }
+
+ /// The stroke shape `strokePath` takes, for a path open or `closed`.
+ pub fn outline(p: Pen, closed: bool) Stroke {
+ return .{ .width = p.width, .join = p.join, .cap = p.cap, .closed = closed };
+ }
+};
+
+/// A circle of `radius` around `center`: the fill, then the stroke over it,
+/// centred on the edge.
+pub fn circle(f: *root.Frame, center: Vec, radius: f32, pen: Pen) void {
+ if (pen.fill) |color| {
+ var t: Tessellation = .empty;
+ t.fillCircle(f.scratch, center, radius, pen.xf) catch return dropped(f);
+ f.shape(&t, color);
+ }
+ if (pen.stroke) |color| {
+ var t: Tessellation = .empty;
+ t.strokeCircle(f.scratch, center, radius, pen.width, pen.xf) catch return dropped(f);
+ f.shape(&t, color);
+ }
+}
+
+/// A segment from `a` to `b` in the stroke colour, with the pen's caps.
+pub fn line(f: *root.Frame, a: Vec, b: Vec, pen: Pen) void {
+ const color = pen.stroke orelse return;
+ var t: Tessellation = .empty;
+ const done = if (pen.cap == .round)
+ t.strokeLine(f.scratch, a, b, pen.width, pen.xf)
+ else
+ t.strokePath(f.scratch, &.{ a, b }, pen.outline(false), pen.xf);
+ done catch return dropped(f);
+ f.shape(&t, color);
+}
+
+/// An open path through `points`: Processing's `beginShape()` ...
+/// `endShape()`. The fill, if any, is the polygon the points close (as
+/// Processing fills it), then the stroke along the open path, with the
+/// pen's joins and caps.
+pub fn polyline(f: *root.Frame, points: []const Vec, pen: Pen) void {
+ path(f, points, pen, false);
+}
+
+/// A closed polygon (simple: convex or not): the fill, then the stroke,
+/// with the pen's joins. `endShape(CLOSE)`.
+pub fn polygon(f: *root.Frame, points: []const Vec, pen: Pen) void {
+ path(f, points, pen, true);
+}
+
+/// A rect: the fill, then the stroke centred on its edge.
+pub fn rect(f: *root.Frame, r: math.Rect, pen: Pen) void {
+ const cs = rectCorners(r);
+ if (r.w > 0 and r.h > 0) path(f, &cs, pen, true);
+}
+
+/// A dot `pen.width` across in the stroke colour, round or square by the
+/// pen's cap: Processing's `point`.
+pub fn point(f: *root.Frame, at: Vec, pen: Pen) void {
+ const color = pen.stroke orelse return;
+ var t: Tessellation = .empty;
+ const done = if (pen.cap == .round)
+ t.fillCircle(f.scratch, at, pen.width / 2, pen.xf)
+ else
+ t.fillRect(f.scratch, .{ .x = at[0] - pen.width / 2, .y = at[1] - pen.width / 2, .w = pen.width, .h = pen.width }, pen.xf);
+ done catch return dropped(f);
+ f.shape(&t, color);
+}
+
+fn path(f: *root.Frame, points: []const Vec, pen: Pen, closed: bool) void {
+ if (pen.fill) |color| {
+ var t: Tessellation = .empty;
+ t.fillPolygon(f.scratch, points, pen.xf) catch return dropped(f);
+ f.shape(&t, color);
+ }
+ if (pen.stroke) |color| {
+ var t: Tessellation = .empty;
+ t.strokePath(f.scratch, points, pen.outline(closed), pen.xf) catch return dropped(f);
+ f.shape(&t, color);
+ }
+}
+
+fn dropped(f: *root.Frame) void {
+ f.host.log("out of scratch memory: shape dropped");
+}
+
+// ---------------------------------------------------------------------------
+// Tests: every shape keeps the contract.
+
+const testing = std.testing;
+
+/// Checks the contract: indices in range, every triangle positively
+/// wound, no two triangles overlapping (beyond touching), the triangles'
+/// area equal to the subpaths' nonzero area, and subpath ends in order.
+fn expectValid(t: *const Tessellation) !void {
+ return expectShape(t, .{});
+}
+
+/// `expectValid` with knobs: `disjoint = false` allows triangles to
+/// overlap, for the documented exceptions, and then checks only that
+/// triangles and subpaths cover the same region (no holes on the web).
+fn expectShape(t: *const Tessellation, options: struct { disjoint: bool = true }) !void {
+ const pts = t.points.items;
+ try testing.expect(t.indices.items.len % 3 == 0);
+ var previous: u32 = 0;
+ for (t.ends.items) |e| {
+ try testing.expect(e >= previous and e <= pts.len);
+ previous = e;
+ }
+ try testing.expectEqual(@as(usize, previous), pts.len);
+ var total: f64 = 0;
+ const tris = t.indices.items;
+ var i: usize = 0;
+ while (i < tris.len) : (i += 3) {
+ for (tris[i..][0..3]) |k| try testing.expect(k < pts.len);
+ const a = vec(pts[tris[i]]);
+ const b = vec(pts[tris[i + 1]]);
+ const c = vec(pts[tris[i + 2]]);
+ const area = math.cross(b - a, c - a) / 2;
+ try testing.expect(area > 0);
+ total += area;
+ }
+ // Disjoint: sampled, since exact polygon intersection is a lot of code
+ // for a test. Every sample point lies in at most one triangle's
+ // interior, and in one exactly when the subpaths' winding is nonzero.
+ var lo: Vec = splat(std.math.inf(f32));
+ var hi: Vec = splat(-std.math.inf(f32));
+ for (pts) |p| {
+ lo = @min(lo, vec(p));
+ hi = @max(hi, vec(p));
+ }
+ const steps = 160;
+ for (0..steps) |yi| for (0..steps) |xi| {
+ // Off-grid offsets, so samples rarely land on an edge.
+ const fx = (@as(f32, @floatFromInt(xi)) + 0.3711) / steps;
+ const fy = (@as(f32, @floatFromInt(yi)) + 0.6173) / steps;
+ const p = lo + (hi - lo) * Vec{ fx, fy };
+ var inside: u32 = 0;
+ i = 0;
+ while (i < tris.len) : (i += 3) {
+ const a = vec(pts[tris[i]]);
+ const b = vec(pts[tris[i + 1]]);
+ const c = vec(pts[tris[i + 2]]);
+ if (strictlyInside(p, a, b, c)) inside += 1;
+ }
+ if (options.disjoint) try testing.expect(inside <= 1);
+ const wind = winding(t, p);
+ if (inside >= 1) try testing.expect(wind != 0);
+ if (wind != 0 and inside == 0) try testing.expect(onAnyEdge(t, p));
+ };
+ // And the areas agree: the triangles tile the filled region.
+ var region: f64 = 0;
+ var start: u32 = 0;
+ for (t.ends.items) |e| {
+ region += signedArea(pts[start..e]);
+ start = e;
+ }
+ if (options.disjoint) try testing.expectApproxEqRel(region, total, 1e-3);
+}
+
+fn strictlyInside(p: Vec, a: Vec, b: Vec, c: Vec) bool {
+ const eps = 1e-4;
+ return math.cross(b - a, p - a) > eps and math.cross(c - b, p - b) > eps and math.cross(a - c, p - c) > eps;
+}
+
+fn onAnyEdge(t: *const Tessellation, p: Vec) bool {
+ const tris = t.indices.items;
+ var i: usize = 0;
+ while (i < tris.len) : (i += 3) {
+ for (0..3) |e| {
+ const a = vec(t.points.items[tris[i + e]]);
+ const b = vec(t.points.items[tris[i + (e + 1) % 3]]);
+ const ab = b - a;
+ const l2 = math.dot(ab, ab);
+ if (l2 == 0) continue;
+ const u = std.math.clamp(math.dot(p - a, ab) / l2, 0, 1);
+ if (math.length(a + math.scale(ab, u) - p) < 1e-2) return true;
+ }
+ }
+ return false;
+}
+
+/// The subpaths' winding number around `p`.
+fn winding(t: *const Tessellation, p: Vec) i32 {
+ var w: i32 = 0;
+ var start: u32 = 0;
+ for (t.ends.items) |e| {
+ const ring_pts = t.points.items[start..e];
+ for (ring_pts, 0..) |a_, k| {
+ const a = vec(a_);
+ const b = vec(ring_pts[(k + 1) % ring_pts.len]);
+ if (a[1] <= p[1]) {
+ if (b[1] > p[1] and math.cross(b - a, p - a) > 0) w += 1;
+ } else {
+ if (b[1] <= p[1] and math.cross(b - a, p - a) < 0) w -= 1;
+ }
+ }
+ start = e;
+ }
+ return w;
+}
+
+test "circles: positive, disjoint, and as many segments as the scale needs" {
+ const gpa = testing.allocator;
+ var t: Tessellation = .empty;
+ defer t.deinit(gpa);
+ try t.fillCircle(gpa, .{ 50, 40 }, 20, .identity);
+ try expectValid(&t);
+ try testing.expectEqual(@as(usize, 1), t.ends.items.len);
+ const n = t.points.items.len;
+ try testing.expectEqual(@as(usize, 3 * (n - 2)), t.indices.items.len);
+ try testing.expect(circleSegments(20, .scale(4, 4)) > circleSegments(20, .identity));
+ try testing.expectEqual(circleSegments(80, .identity), circleSegments(20, .scale(4, 4)));
+
+ t.clearRetainingCapacity();
+ try t.strokeCircle(gpa, .{ 0, 0 }, 30, 6, .identity);
+ try expectValid(&t);
+ try testing.expectEqual(@as(usize, 2), t.ends.items.len);
+ try testing.expectEqual(@as(usize, 3 * t.points.items.len), t.indices.items.len);
+
+ // A mirroring transform still winds positively.
+ t.clearRetainingCapacity();
+ try t.strokeCircle(gpa, .{ 10, 0 }, 30, 6, Affine.scale(-1, 1).mul(.rotate(0.3)));
+ try expectValid(&t);
+ t.clearRetainingCapacity();
+ try t.fillCircle(gpa, .{ 10, 0 }, 3, .scale(1, -2));
+ try expectValid(&t);
+}
+
+test "polygons: convex, concave, either winding, mirrored" {
+ const gpa = testing.allocator;
+ var t: Tessellation = .empty;
+ defer t.deinit(gpa);
+ const triangle = [_]Vec{ .{ 20, 0 }, .{ -10, -8 }, .{ -10, 8 } };
+ const arrow = [_]Vec{ .{ 0, 0 }, .{ 60, 0 }, .{ 60, 60 }, .{ 30, 20 }, .{ 0, 60 } };
+ const star = blk: {
+ var s: [10]Vec = undefined;
+ for (&s, 0..) |*p, i| p.* = math.scale(math.unit(@as(f32, @floatFromInt(i)) * std.math.pi / 5.0), if (i % 2 == 0) 50 else 20);
+ break :blk s;
+ };
+ var backwards = arrow;
+ std.mem.reverse(Vec, &backwards);
+ for ([_][]const Vec{ &triangle, &arrow, &backwards, &star }) |shape| {
+ for ([_]Affine{ .identity, .place(.{ 100, 50 }, 1.1), .scale(-2, 1) }) |xf| {
+ t.clearRetainingCapacity();
+ try t.fillPolygon(gpa, shape, xf);
+ try expectValid(&t);
+ try testing.expectEqual(3 * (shape.len - 2), t.indices.items.len);
+ t.clearRetainingCapacity();
+ try t.strokePolygon(gpa, shape, 3, xf);
+ try expectValid(&t);
+ }
+ }
+}
+
+test "strokes: lines with round ends, acute zig-zags without overlap" {
+ const gpa = testing.allocator;
+ var t: Tessellation = .empty;
+ defer t.deinit(gpa);
+ try t.strokeLine(gpa, .{ 10, 10 }, .{ 200, 60 }, 9, .identity);
+ try expectValid(&t);
+ t.clearRetainingCapacity();
+ try t.strokeLine(gpa, .{ 10, 10 }, .{ 10, 10 }, 4, .identity);
+ try expectValid(&t);
+ t.clearRetainingCapacity();
+ try t.strokeLine(gpa, .{ 0, 0.5 }, .{ 100, 0.5 }, 1, .identity);
+ try expectValid(&t);
+
+ const zigzag = [_]Vec{ .{ 20, 200 }, .{ 70, 60 }, .{ 120, 200 }, .{ 170, 60 }, .{ 220, 200 }, .{ 240, 190 } };
+ for ([_]f32{ 2, 12, 30 }) |w| {
+ t.clearRetainingCapacity();
+ try t.strokePolyline(gpa, &zigzag, w, .identity);
+ try expectValid(&t);
+ t.clearRetainingCapacity();
+ try t.strokePolyline(gpa, &zigzag, w, .scale(-1, 1));
+ try expectValid(&t);
+ }
+ // Segments shorter than an acute turn needs: the bodies overlap (the
+ // documented exception), but the web's outline still has no holes.
+ const tight = [_]Vec{ .{ 0, 100 }, .{ 10, 0 }, .{ 20, 100 }, .{ 25, 95 }, .{ 30, 100 } };
+ t.clearRetainingCapacity();
+ try t.strokePolyline(gpa, &tight, 16, .identity);
+ try expectShape(&t, .{ .disjoint = false });
+ t.clearRetainingCapacity();
+ try t.strokePolygon(gpa, &tight, 16, .identity);
+ try expectShape(&t, .{ .disjoint = false });
+ // Straight runs and repeated points.
+ const straight = [_]Vec{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 0 }, .{ 20, 0 }, .{ 30, 10 } };
+ t.clearRetainingCapacity();
+ try t.strokePolyline(gpa, &straight, 4, .identity);
+ try expectValid(&t);
+ // A square's outline: a ring with a hole.
+ const square = [_]Vec{ .{ 0, 0 }, .{ 50, 0 }, .{ 50, 50 }, .{ 0, 50 } };
+ t.clearRetainingCapacity();
+ try t.strokePolygon(gpa, &square, 6, .identity);
+ try expectValid(&t);
+ try testing.expectEqual(@as(usize, 2), t.ends.items.len);
+}
+
+test "nothing to draw draws nothing" {
+ const gpa = testing.allocator;
+ var t: Tessellation = .empty;
+ defer t.deinit(gpa);
+ try t.fillCircle(gpa, .{ 0, 0 }, 0, .identity);
+ try t.strokeCircle(gpa, .{ 0, 0 }, 10, 0, .identity);
+ try t.fillPolygon(gpa, &.{ .{ 0, 0 }, .{ 1, 1 } }, .identity);
+ try t.strokePolyline(gpa, &.{.{ 0, 0 }}, 3, .identity);
+ try testing.expectEqual(@as(usize, 0), t.points.items.len + t.indices.items.len + t.ends.items.len);
+}
+
+test "joins and caps: every combination keeps the contract" {
+ const gpa = testing.allocator;
+ var t: Tessellation = .empty;
+ defer t.deinit(gpa);
+ const zigzag = [_]Vec{ .{ 20, 200 }, .{ 70, 60 }, .{ 120, 200 }, .{ 170, 60 }, .{ 220, 200 }, .{ 240, 190 } };
+ const path_like = [_]Vec{ .{ -20, 180 }, .{ 150, 40 }, .{ 450, 300 }, .{ 660, 180 } };
+ const square = [_]Vec{ .{ 0, 0 }, .{ 50, 0 }, .{ 50, 50 }, .{ 0, 50 } };
+ for ([_]Join{ .miter, .round, .bevel }) |join| for ([_]Cap{ .butt, .round, .square }) |cap| {
+ for ([_]f32{ 2, 12, 30 }) |w| for ([_]Affine{ .identity, .scale(-1, 1), .place(.{ 30, 40 }, 0.7) }) |xf| {
+ t.clearRetainingCapacity();
+ try t.strokePath(gpa, &zigzag, .{ .width = w, .join = join, .cap = cap }, xf);
+ try expectValid(&t);
+ t.clearRetainingCapacity();
+ try t.strokePath(gpa, &square, .{ .width = w, .join = join, .closed = true }, xf);
+ try expectValid(&t);
+ };
+ t.clearRetainingCapacity();
+ try t.strokePath(gpa, &path_like, .{ .width = 40, .join = join, .cap = cap }, .identity);
+ try expectValid(&t);
+ };
+ // Round caps and joins add area: a round-capped segment is the stadium.
+ t.clearRetainingCapacity();
+ try t.strokePath(gpa, &.{ .{ 10, 10 }, .{ 110, 10 } }, .{ .width = 20, .cap = .round }, .identity);
+ try expectValid(&t);
+ const stadium = triangleArea(&t);
+ try testing.expectApproxEqRel(@as(f32, 100 * 20 + std.math.pi * 100), stadium, 0.01);
+ t.clearRetainingCapacity();
+ try t.strokePath(gpa, &.{ .{ 10, 10 }, .{ 110, 10 } }, .{ .width = 20, .cap = .square }, .identity);
+ try testing.expectApproxEqRel(@as(f32, 120 * 20), triangleArea(&t), 1e-4);
+ // A zero-length path is a dot with round or square caps.
+ t.clearRetainingCapacity();
+ try t.strokePath(gpa, &.{ .{ 5, 5 }, .{ 5, 5 } }, .{ .width = 4, .cap = .square }, .identity);
+ try testing.expectApproxEqRel(@as(f32, 16), triangleArea(&t), 1e-4);
+ t.clearRetainingCapacity();
+ try t.strokePath(gpa, &.{.{ 5, 5 }}, .{ .width = 4 }, .identity);
+ try testing.expectEqual(@as(usize, 0), t.indices.items.len);
+}
+
+test "rects: filled and stroked, many in one tessellation" {
+ const gpa = testing.allocator;
+ var t: Tessellation = .empty;
+ defer t.deinit(gpa);
+ try t.fillRect(gpa, .{ .x = 10, .y = 20, .w = 30, .h = 40 }, .identity);
+ try expectValid(&t);
+ try testing.expectApproxEqRel(@as(f32, 1200), triangleArea(&t), 1e-5);
+ t.clearRetainingCapacity();
+ try t.strokeRect(gpa, .{ .x = 10, .y = 20, .w = 30, .h = 40 }, 2, .identity);
+ try expectValid(&t);
+ try testing.expectApproxEqRel(@as(f32, 32 * 42 - 28 * 38), triangleArea(&t), 1e-4);
+ t.clearRetainingCapacity();
+ for (0..4) |i| {
+ const x: f32 = @floatFromInt(i * 40);
+ try t.strokeRect(gpa, .{ .x = x, .y = 0, .w = 30, .h = 30 }, 1, .identity);
+ }
+ try testing.expectEqual(@as(usize, 8), t.ends.items.len);
+ try t.fillRect(gpa, .{ .x = 0, .y = 0, .w = 0, .h = 5 }, .identity);
+ try testing.expectEqual(@as(usize, 8), t.ends.items.len);
+}
+
+fn triangleArea(t: *const Tessellation) f32 {
+ var sum: f32 = 0;
+ var i: usize = 0;
+ while (i < t.indices.items.len) : (i += 3) {
+ const a = vec(t.points.items[t.indices.items[i]]);
+ const b = vec(t.points.items[t.indices.items[i + 1]]);
+ const c = vec(t.points.items[t.indices.items[i + 2]]);
+ sum += math.cross(b - a, c - a) / 2;
+ }
+ return sum;
+}
diff --git a/src/sketch/list.zig b/src/sketch/list.zig
new file mode 100644
index 0000000..8040a5d
--- /dev/null
+++ b/src/sketch/list.zig
@@ -0,0 +1,109 @@
+//! A list with its capacity in its type: plain data, so it can live in
+//! State (no pointers) and migrate there element by element.
+const std = @import("std");
+
+/// `buffer` and `len` are public fields, so the host's console and scripts
+/// reach elements by path (`boids.buffer[3].pos[0]`, `boids.len`).
+///
+/// Every method clamps `len` to the capacity: after a reload that shrinks
+/// the capacity, a saved `len` may be larger than the new buffer, and the
+/// list then holds `capacity` elements rather than indexing out of bounds.
+/// The names and errors are std's (`ArrayList`'s bounded methods).
+pub fn List(comptime T: type, comptime cap: u32) type {
+ return struct {
+ const Self = @This();
+ pub const capacity = cap;
+
+ buffer: [cap]T = default_buffer,
+ len: u32 = 0,
+
+ /// T's own defaults when it has them for every field, zeroes for
+ /// numbers, the first tag for enums; otherwise undefined. Never
+ /// `std.mem.zeroes`, which fails on enums with no 0 tag.
+ const default_buffer: [cap]T = if (defaultOf(T)) |d| @splat(d) else undefined;
+
+ pub fn slice(l: *Self) []T {
+ return l.buffer[0..l.count()];
+ }
+ pub fn constSlice(l: *const Self) []const T {
+ return l.buffer[0..l.count()];
+ }
+ /// `len`, clamped to the capacity.
+ pub fn count(l: *const Self) u32 {
+ return @min(l.len, cap);
+ }
+ pub fn appendBounded(l: *Self, item: T) error{OutOfMemory}!void {
+ const n = l.count();
+ if (n == cap) return error.OutOfMemory;
+ l.buffer[n] = item;
+ l.len = n + 1;
+ }
+ /// Removes the element at `i`, keeping the order of the rest.
+ pub fn orderedRemove(l: *Self, i: u32) T {
+ const n = l.count();
+ const item = l.buffer[i];
+ std.mem.copyForwards(T, l.buffer[i .. n - 1], l.buffer[i + 1 .. n]);
+ l.len = n - 1;
+ return item;
+ }
+ /// Removes the element at `i`, moving the last one into its place.
+ pub fn swapRemove(l: *Self, i: u32) T {
+ const n = l.count();
+ const item = l.buffer[i];
+ l.buffer[i] = l.buffer[n - 1];
+ l.len = n - 1;
+ return item;
+ }
+ pub fn clear(l: *Self) void {
+ l.len = 0;
+ }
+ };
+}
+
+fn defaultOf(comptime T: type) ?T {
+ return switch (@typeInfo(T)) {
+ .int, .float, .vector => std.mem.zeroes(T),
+ .bool => false,
+ .optional => null,
+ .array => |a| if (defaultOf(a.child)) |d| @splat(d) else null,
+ .@"enum" => |e| if (e.mode == .exhaustive) @field(T, e.field_names[0]) else @enumFromInt(0),
+ .@"struct" => |s| {
+ for (s.field_attrs) |attrs| if (attrs.default_value_ptr == null) return null;
+ return .{};
+ },
+ else => null,
+ };
+}
+
+test "append, remove, clamp after a capacity shrink" {
+ const Kind = enum(u8) { a = 1, b = 2 };
+ const Item = struct { kind: Kind = .b, x: f32 = 1 };
+ var l: List(Item, 4) = .{};
+ try std.testing.expectEqual(Kind.b, l.buffer[3].kind);
+ for (0..4) |i| try l.appendBounded(.{ .x = @floatFromInt(i) });
+ try std.testing.expectError(error.OutOfMemory, l.appendBounded(.{}));
+ try std.testing.expectEqual(@as(f32, 1), l.orderedRemove(1).x);
+ try std.testing.expectEqual(@as(f32, 2), l.constSlice()[1].x);
+ try std.testing.expectEqual(@as(f32, 0), l.swapRemove(0).x);
+ try std.testing.expectEqual(@as(f32, 3), l.slice()[0].x);
+ try std.testing.expectEqual(@as(usize, 2), l.slice().len);
+ // A saved len from a bigger list.
+ l.len = 10;
+ try std.testing.expectEqual(@as(usize, 4), l.constSlice().len);
+ try std.testing.expectError(error.OutOfMemory, l.appendBounded(.{}));
+ _ = l.swapRemove(0);
+ try std.testing.expectEqual(@as(u32, 3), l.len);
+}
+
+test "defaults for element types without struct defaults" {
+ const E = enum(u8) { one = 1, two = 2 };
+ const a: List(E, 3) = .{};
+ try std.testing.expectEqual(E.one, a.buffer[2]);
+ const b: List(f32, 3) = .{};
+ try std.testing.expectEqual(@as(f32, 0), b.buffer[1]);
+ const c: List(@Vector(2, f32), 2) = .{};
+ try std.testing.expectEqual(@as(f32, 0), c.buffer[1][0]);
+ const NoDefault = struct { x: f32 };
+ const d: List(NoDefault, 2) = .{};
+ try std.testing.expectEqual(@as(u32, 0), d.len);
+}
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index 94ce617..33c9ba7 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -22,10 +22,23 @@
//! see `shape`.
const std = @import("std");
pub const abi = @import("abi");
-pub const shape = @import("shape.zig");
+/// Duck-typed points, rects and colors (named `shapes` inside this file,
+/// where `Frame.shape` is the method).
+pub const shape = shapes;
+const shapes = @import("shape.zig");
pub const Key = abi.Key;
pub const Camera = @import("camera.zig").Camera;
pub const tween = @import("tween.zig");
+/// Vectors (`@Vector(2, f32)`), affine transforms, Béziers and noise: the
+/// geometry module the `vector` library uses too.
+pub const math = @import("math");
+/// Circles, lines and polygons as `Command.shape`s: a `Tessellation` to
+/// build yourself (L1), or a `Pen` and `circle`/`line`/`polygon` (L2).
+pub const draw = @import("draw.zig");
+pub const Clock = @import("clock.zig").Clock;
+pub const List = @import("list.zig").List;
+/// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload).
+pub const Derived = @import("derived.zig").Derived;
pub const web = @import("web.zig");
const request = @import("request.zig");
pub const Request = request.Request;
@@ -36,12 +49,14 @@ pub const Color = abi.Color;
pub const Event = abi.Event;
pub const Input = abi.Input;
pub const Mode = abi.Mode;
+pub const MouseButton = abi.MouseButton;
pub const Host = abi.Host;
pub const Image = abi.Image;
pub const Audio = abi.Audio;
pub const Buffer = abi.Buffer;
pub const Cursor = abi.Cursor;
pub const Voice = abi.Voice;
+pub const BlendMode = abi.BlendMode;
/// What `draw` receives: input, host services, memory by lifetime and the
/// command list. Commands may be built from anything: the methods copy what
@@ -71,35 +86,91 @@ pub const Frame = struct {
return f.scratch.dupe(T, items) catch &.{};
}
+ /// Colour parameters take anything `shape.color` does (`0x202020`,
+ /// `sk.Color.gray(220)`, `.{ .r = 1, .g = 0, .b = 0 }`), and the
+ /// `Color` constants by name: `f.clear(.white)`.
pub fn clear(f: *Frame, color: anytype) void {
- f.emit(.{ .clear = shape.color(color) });
+ f.emit(.{ .clear = paint(color) });
}
pub fn fill(f: *Frame, r: anytype, color: anytype) void {
- f.emit(.{ .rect = .{ .dst = shape.rect(r), .color = shape.color(color) } });
+ f.emit(.{ .rect = .{ .dst = shapes.rect(r), .color = paint(color) } });
}
/// `options` may set `.src` (a rect within the image) and `.tint` (a color).
pub fn image(f: *Frame, img: Image, dst: anytype, options: anytype) void {
const O = @TypeOf(options);
f.emit(.{ .image = .{
.image = img,
- .dst = shape.rect(dst),
- .src = if (@hasField(O, "src")) shape.rect(options.src) else .{},
- .tint = if (@hasField(O, "tint")) shape.color(options.tint) else .white,
+ .dst = shapes.rect(dst),
+ .src = if (@hasField(O, "src")) shapes.rect(options.src) else .{},
+ .tint = if (@hasField(O, "tint")) paint(options.tint) else .white,
} });
}
+ /// Processing's `imageMode(CENTER)` under a transform: the image (or
+ /// `src` within it) centred on `xf`'s origin, along its axes, at
+ /// `size` (default: the image's, or `src`'s). `.place(at, radians)`
+ /// turns it, `.translate(x, y)` only moves it. Nothing is drawn while
+ /// the size is unknown (an image the web is still loading).
+ pub fn imageAt(f: *Frame, img: Image, xf: math.Affine, options: struct { src: Rect = .{}, size: ?[2]f32 = null, tint: Color = .white }) void {
+ const wh: [2]f32 = options.size orelse if (options.src.w > 0) .{ options.src.w, options.src.h } else blk: {
+ const px = f.host.imageSize(img);
+ break :blk .{ @floatFromInt(px[0]), @floatFromInt(px[1]) };
+ };
+ if (wh[0] == 0 or wh[1] == 0) return;
+ const hw = wh[0] / 2;
+ const hh = wh[1] / 2;
+ f.emit(.{ .image = .{
+ .image = img,
+ .dst = .{ .x = -hw, .y = -hh, .w = wh[0], .h = wh[1] },
+ .src = options.src,
+ .tint = options.tint,
+ .corners = .{
+ .top_left = xf.apply(.{ -hw, -hh }),
+ .top_right = xf.apply(.{ hw, -hh }),
+ .bottom_left = xf.apply(.{ -hw, hh }),
+ },
+ } });
+ }
+ /// Draws the 2D commands after it into `img` (made by
+ /// `host.newImage`), until `f.target(.none)` or the frame ends. The
+ /// image keeps what was drawn, across frames: a canvas that is never
+ /// cleared. It is a Session cache, so repaint it from State when
+ /// `f.in.jumped`.
+ pub fn target(f: *Frame, img: Image) void {
+ f.emit(.{ .target = img });
+ }
+ /// How the 2D commands after it blend, until the next `blend` or the
+ /// frame ends (which goes back to `.alpha`).
+ pub fn blend(f: *Frame, mode: BlendMode) void {
+ f.emit(.{ .blend = mode });
+ }
pub fn text(f: *Frame, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = shape.color(color), .bytes = f.keep(u8, bytes) } });
+ f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes) } });
}
pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = shape.color(color), .bytes = f.format(fmt, args) } });
+ f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.format(fmt, args) } });
}
/// Formats into scratch memory.
pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 {
return f.scratch.print(fmt, args) catch "?";
}
+ /// Fills `t`'s region in `color` (see `draw`). Its slices are not
+ /// copied: `t` must live until the frame is drawn (scratch memory, or
+ /// a session value not cleared before then).
+ pub fn shape(f: *Frame, t: *const draw.Tessellation, color: Color) void {
+ if (t.indices.items.len == 0) return;
+ f.emit(.{ .shape = .{ .color = color, .points = t.points.items, .ends = t.ends.items, .indices = t.indices.items } });
+ }
+ /// `t` with a colour per subpath: `colors[i]` for subpath `i` (one per
+ /// `t.ends` item; a stroked circle has two, its outline and its hole,
+ /// which must share one). Many shapes of many colours in one command,
+ /// like fading particles. Neither slice is copied (see `shape`).
+ pub fn shapeColors(f: *Frame, t: *const draw.Tessellation, colors: []const Color) void {
+ if (t.indices.items.len == 0) return;
+ f.emit(.{ .shape = .{ .color = if (colors.len > 0) colors[colors.len - 1] else .white, .points = t.points.items, .ends = t.ends.items, .indices = t.indices.items, .colors = colors } });
+ }
/// A rect, or `null` to stop clipping.
pub fn clip(f: *Frame, r: anytype) void {
- f.emit(.{ .clip = if (@TypeOf(r) == @TypeOf(null)) null else shape.rect(r) });
+ f.emit(.{ .clip = if (@TypeOf(r) == @TypeOf(null)) null else shapes.rect(r) });
}
pub fn canvas(f: *Frame, w: u32, h: u32) void {
f.emit(.{ .canvas = .{ .w = w, .h = h } });
@@ -171,6 +242,13 @@ pub const Frame = struct {
}
};
+/// A colour argument: `shape.color`'s forms, or a `Color` constant by
+/// name (`.white`), which an `anytype` parameter cannot resolve itself.
+fn paint(value: anytype) Color {
+ if (@TypeOf(value) == @EnumLiteral()) return @field(Color, @tagName(value));
+ return shapes.color(value);
+}
+
/// What `command` receives: somewhere to answer, the current input, and the
/// allocators for Session and Store.
pub const Console = struct {
@@ -305,7 +383,11 @@ pub fn Glue(comptime App: type) type {
test {
_ = request;
_ = abi.layout;
- _ = shape;
+ _ = shapes;
_ = @import("camera.zig");
_ = tween;
+ _ = draw;
+ _ = @import("clock.zig");
+ _ = @import("list.zig");
+ _ = @import("derived.zig");
}
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index bc7fead..27313a6 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -18,7 +18,18 @@ const js = struct {
extern "host" fn openFile(command: [*]const u8, command_len: usize, pattern: [*]const u8, pattern_len: usize) void;
extern "canvas" fn clear(r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn fill(x: f32, y: f32, w: f32, h: f32, r: u32, g: u32, b: u32, a: u32) void;
- extern "canvas" fn image(id: u32, x: f32, y: f32, w: f32, h: f32, sx: f32, sy: f32, sw: f32, sh: f32, alpha: u32) void;
+ extern "canvas" fn image(id: u32, x: f32, y: f32, w: f32, h: f32, sx: f32, sy: f32, sw: f32, sh: f32, r: u32, g: u32, b: u32, a: u32) void;
+ /// The image (or `sw` x `sh` at `sx`, `sy`) with its corners at the
+ /// three points: top left, top right, bottom left.
+ extern "canvas" fn imageCorners(id: u32, x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32, sx: f32, sy: f32, sw: f32, sh: f32, r: u32, g: u32, b: u32, a: u32) void;
+ /// Fills the subpaths `points[ends[i - 1] .. ends[i]]` nonzero:
+ /// `points` is `len` pairs of f32, `ends` `ends_len` u32s, `colors`
+ /// `colors_len` RGBA quadruples, one per subpath (else `r, g, b, a`).
+ extern "canvas" fn shape(points: [*]const [2]f32, len: usize, ends: [*]const u32, ends_len: usize, colors: [*]const abi.Color, colors_len: usize, r: u32, g: u32, b: u32, a: u32) void;
+ /// Draws into image `id`, or the canvas for 0.
+ extern "canvas" fn target(id: u32) void;
+ /// `abi.BlendMode` by value.
+ extern "canvas" fn blend(mode: u32) void;
extern "canvas" fn text(x: f32, y: f32, scale: f32, ptr: [*]const u8, len: usize, r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn clip(enabled: u32, x: f32, y: f32, w: f32, h: f32) void;
extern "canvas" fn canvas(w: u32, h: u32) void;
@@ -136,8 +147,11 @@ fn Driver(comptime App: type) type {
const now: u64 = @intFromFloat(@max(0, ms) * std.time.ns_per_ms);
const dt = if (last == 0) 0 else now -| last;
last = now;
+ // `in.dt` comes from the tick, as on native, so it is what a
+ // replay of the tick would give.
+ const tick = abi.Event.tick(now, dt);
if (event_count < events.len) {
- events[event_count] = .{ .kind = .tick, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) };
+ events[event_count] = tick;
event_count += 1;
}
for (events[0..event_count]) |*e| {
@@ -147,7 +161,7 @@ fn Driver(comptime App: type) type {
_ = scratch.reset(.retain_capacity);
commands = .empty;
input.now = now;
- input.dt = dt;
+ input.dt = tick.tickDt();
input.frame += 1;
input.events = events[0..event_count];
input.started = input.frame == 1;
@@ -159,9 +173,15 @@ fn Driver(comptime App: type) type {
G.update(&ctx, std.mem.asBytes(&state));
input.events = &.{};
event_count = 0;
+ // No timeline here: only the first frame comes from nowhere.
+ input.jumped = input.frame == 1;
G.draw(&ctx, std.mem.asBytes(&state));
+ js.target(0);
+ js.blend(0);
js.clip(0, 0, 0, 0, 0);
for (commands.items) |c| submit(c);
+ js.target(0);
+ js.blend(0);
// After the frame, as on native: lines `draw` asked to run.
for (commands.items) |c| if (c == .run) run(c.run);
@@ -176,7 +196,13 @@ fn Driver(comptime App: type) type {
switch (c) {
.clear => |v| js.clear(v.r, v.g, v.b, v.a),
.rect => |v| js.fill(v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.color.r, v.color.g, v.color.b, v.color.a),
- .image => |v| js.image(@backingInt(v.image), v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.src.x, v.src.y, v.src.w, v.src.h, v.tint.a),
+ .image => |v| if (v.corners) |q|
+ js.imageCorners(@backingInt(v.image), q.top_left[0], q.top_left[1], q.top_right[0], q.top_right[1], q.bottom_left[0], q.bottom_left[1], v.src.x, v.src.y, v.src.w, v.src.h, v.tint.r, v.tint.g, v.tint.b, v.tint.a)
+ else
+ js.image(@backingInt(v.image), v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.src.x, v.src.y, v.src.w, v.src.h, v.tint.r, v.tint.g, v.tint.b, v.tint.a),
+ .shape => |v| js.shape(v.points.ptr, v.points.len, v.ends.ptr, v.ends.len, v.colors.ptr, v.colors.len, v.color.r, v.color.g, v.color.b, v.color.a),
+ .target => |v| js.target(@backingInt(v)),
+ .blend => |v| js.blend(@backingInt(v)),
.text => |v| js.text(v.x, v.y, v.scale, v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a),
.clip => |v| if (v) |r| js.clip(1, r.x, r.y, r.w, r.h) else js.clip(0, 0, 0, 0, 0),
.canvas => |v| {
@@ -320,8 +346,10 @@ fn Driver(comptime App: type) type {
/// it, and returns its length; -1 when there is no such enum field.
fn tag(len: usize) callconv(.c) i32 {
const name = path[0..@min(len, path.len)];
- for (G.description.state.fields) |f| {
- if (f.kind != .@"enum" or !std.mem.eql(u8, std.mem.span(f.path), name)) continue;
+ // Paths may index arrays and vector lanes (`list[2].mood`).
+ if (abi.layout.resolve(G.description.state.fields, name)) |r| {
+ const f = r.field;
+ if (f.kind != .@"enum") return -1;
const value: u64 = @intFromFloat(field(len));
var pairs = std.mem.tokenizeScalar(u8, std.mem.span(f.tags), ',');
while (pairs.next()) |pair| {
@@ -339,9 +367,9 @@ fn Driver(comptime App: type) type {
fn field(len: usize) callconv(.c) f64 {
const name = path[0..@min(len, path.len)];
const bytes = std.mem.asBytes(&state);
- for (G.description.state.fields) |f| {
- if (!std.mem.eql(u8, std.mem.span(f.path), name)) continue;
- const raw = bytes[f.offset..][0..f.size];
+ if (abi.layout.resolve(G.description.state.fields, name)) |r| {
+ const f = r.field;
+ const raw = bytes[r.offset..][0..f.size];
var value: u64 = 0;
for (raw[0..@min(raw.len, 8)], 0..) |b, i| value |= @as(u64, b) << @intCast(i * 8);
return switch (f.kind) {
diff --git a/src/vector/Cpu.zig b/src/vector/Cpu.zig
index c17366f..ac5c6ea 100644
--- a/src/vector/Cpu.zig
+++ b/src/vector/Cpu.zig
@@ -6,7 +6,7 @@
//! wasm included, and is the reference the GPU backend is tested against.
const Cpu = @This();
const std = @import("std");
-const geom = @import("geom.zig");
+const geom = @import("math");
const Drawing = @import("Drawing.zig");
const Polygons = @import("Polygons.zig");
const Paint = @import("Paint.zig");
diff --git a/src/vector/Drawing.zig b/src/vector/Drawing.zig
index 0a3b77b..339f1ce 100644
--- a/src/vector/Drawing.zig
+++ b/src/vector/Drawing.zig
@@ -3,7 +3,7 @@
//! read and recombine them.
const Drawing = @This();
const std = @import("std");
-const geom = @import("geom.zig");
+const geom = @import("math");
const Vec = geom.Vec;
const Cubic = geom.Cubic;
diff --git a/src/vector/Gpu.zig b/src/vector/Gpu.zig
index 5853145..3c9d48c 100644
--- a/src/vector/Gpu.zig
+++ b/src/vector/Gpu.zig
@@ -1,16 +1,33 @@
-//! The GPU backend, as data: every fill becomes a stencil draw and a cover
-//! draw in an `abi.gpu.Pass` that the host runs. Stencil-then-cover:
-//! - stencil: the contours as triangle fans, counting windings in the
-//! stencil buffer (increment/decrement by facing for nonzero, invert for
-//! even-odd), color writes off;
-//! - cover: the bounding box, painted where the stencil is set, zeroing the
-//! stencil as it goes so the next fill starts clean.
-//! Anti-aliasing is 8x multisampling. Paint runs in `cover.frag`, the GPU
-//! twin of `Paint.zig`.
+//! The GPU backend, as data: fills become draws in an `abi.gpu.Pass` that
+//! the host runs. A fill is drawn one of two ways:
+//! - direct, when its polygons are one convex contour: its triangle fan,
+//! painted, covers each inside sample exactly once;
+//! - stencil-then-cover otherwise: the contours as triangle fans count
+//! windings in the stencil buffer (increment/decrement by facing for
+//! nonzero, invert for even-odd), color writes off; then its bounding box
+//! is painted where the stencil is set, zeroing the stencil as it goes so
+//! the next fill starts clean.
+//!
+//! Fills are batched into layers, so the draw count follows how deep fills
+//! pile up, not how many there are. A layer draws its stencil fans (one
+//! draw per fill rule), then its cover boxes, then its direct fans, each in
+//! one draw. A fill goes into the lowest layer that keeps the picture as if
+//! every fill were drawn alone, in order: above every layer holding an
+//! earlier fill whose box overlaps its own, except that a direct fill may
+//! share the layer of what it overlaps (it is drawn after that layer's
+//! covers, and after earlier direct fans in order). Stencilled fills in one
+//! layer never overlap, so their stencils and covers cannot mix. Overlap is
+//! judged on a coarse grid of the image, conservatively: neighbours in a
+//! cell count as overlapping.
+//!
+//! Each vertex of a painted triangle carries its fill's paint: a solid
+//! color, or the index of a gradient in a storage buffer of `Paint` blocks
+//! uploaded with the pass. Anti-aliasing is 8x multisampling. Gradients run
+//! in `paint.frag`, the GPU twin of `Paint.zig`.
const Gpu = @This();
const std = @import("std");
const abi = @import("abi");
-const geom = @import("geom.zig");
+const geom = @import("math");
const Drawing = @import("Drawing.zig");
const Polygons = @import("Polygons.zig");
const Paint = @import("Paint.zig");
@@ -21,9 +38,13 @@ pub const samples = 8;
const vertex: abi.gpu.Shader = .{ .code = shaders.path_vert, .uniform_buffers = 1 };
const stencil_only: abi.gpu.Shader = .{ .code = shaders.stencil_frag };
+const painted_vertex: abi.gpu.Shader = .{ .code = shaders.paint_vert, .uniform_buffers = 1 };
+const painted_fragment: abi.gpu.Shader = .{ .code = shaders.paint_frag, .storage_buffers = 1 };
+
+pub const Pipeline = enum(u32) { nonzero, evenodd, cover, direct };
const pipelines = [_]abi.gpu.Pipeline{
- // 0: nonzero winding.
+ // Stencil fans, nonzero winding.
abi.gpu.pipeline(layouts.Vertex, .{
.vertex = vertex,
.fragment = stencil_only,
@@ -31,7 +52,7 @@ const pipelines = [_]abi.gpu.Pipeline{
.write_color = false,
.stencil = .{ .front = .{ .pass = .increment_and_wrap }, .back = .{ .pass = .decrement_and_wrap } },
}),
- // 1: even-odd.
+ // Stencil fans, even-odd.
abi.gpu.pipeline(layouts.Vertex, .{
.vertex = vertex,
.fragment = stencil_only,
@@ -39,30 +60,58 @@ const pipelines = [_]abi.gpu.Pipeline{
.write_color = false,
.stencil = .{ .front = .{ .pass = .invert }, .back = .{ .pass = .invert } },
}),
- // 2: cover.
- abi.gpu.pipeline(layouts.Vertex, .{
- .vertex = vertex,
- .fragment = .{ .code = shaders.cover_frag, .uniform_buffers = 1 },
+ // Cover boxes.
+ abi.gpu.pipeline(layouts.Painted, .{
+ .vertex = painted_vertex,
+ .fragment = painted_fragment,
.stencil = .{
.front = .{ .compare = .not_equal, .pass = .zero },
.back = .{ .compare = .not_equal, .pass = .zero },
},
}),
+ // Convex fills, drawn directly.
+ abi.gpu.pipeline(layouts.Painted, .{ .vertex = painted_vertex, .fragment = painted_fragment }),
+};
+
+/// One layer's triangles, one draw each.
+const Layer = struct {
+ /// Stencil fans by fill rule.
+ stencil: [2]std.ArrayList(layouts.Vertex) = .{ .empty, .empty },
+ cover: std.ArrayList(layouts.Painted) = .empty,
+ direct: std.ArrayList(layouts.Painted) = .empty,
};
+/// The overlap grid's cells are 2^shift pixels square.
+const min_shift = 2;
+const max_cells = 1 << 16;
+
width: u32,
height: u32,
image: abi.Image,
/// Frame lifetime: the pass's vertices and uniforms live here until the
/// host consumes the frame.
arena: std.mem.Allocator = undefined,
-draws: std.ArrayList(abi.gpu.Draw) = .empty,
clear_color: [4]f32 = .{ 0, 0, 0, 0 },
viewport: []const u8 = &.{},
+layers: std.ArrayList(Layer) = .empty,
+/// The gradients of this pass's fills, uploaded by `upload`.
+paints: std.ArrayList(layouts.Paint) = .empty,
+/// Per grid cell: 1 + the highest layer of a fill touching it; 0 if none.
+grid: []u32 = &.{},
+shift: u5 = min_shift,
+columns: u32 = 0,
+draws: std.ArrayList(abi.gpu.Draw) = .empty,
+/// GPU memory for `paints`, kept across frames: made, and remade larger,
+/// by `upload`; freed by the renderer's `deinit`.
+paint_buffer: abi.Buffer = .none,
+paint_capacity: u32 = 0,
pub fn begin(g: *Gpu, arena: std.mem.Allocator, clear: Drawing.Color) void {
g.arena = arena;
g.draws = .empty;
+ g.layers = .empty;
+ g.paints = .empty;
+ g.grid = &.{};
g.clear_color = Paint.premultiply(clear);
g.viewport = abi.gpu.uniform(arena, layouts.Viewport{ .size = .{ @floatFromInt(g.width), @floatFromInt(g.height) } });
}
@@ -73,45 +122,97 @@ pub fn fill(g: *Gpu, polys: *const Polygons, rule: Drawing.FillRule, paint: *con
}
fn record(g: *Gpu, polys: *const Polygons, rule: Drawing.FillRule, paint: *const Paint, alpha: f32) !void {
+ const b = polys.bounds();
+ const lo = @max(@floor(b.min), geom.splat(0));
+ const hi = @min(@ceil(b.max), geom.Vec{ @floatFromInt(g.width), @floatFromInt(g.height) });
+ if (!(lo[0] < hi[0] and lo[1] < hi[1])) return;
+ const direct = polys.contours.items.len == 1 and Polygons.convex(polys.points.items);
+ const layer = try g.place(lo, hi, direct);
+ const p = try g.painted(paint, alpha);
+ if (direct) {
+ // A convex polygon's fan from its first point: no triangle overlaps
+ // another, so each sample inside is painted once.
+ const pts = polys.points.items;
+ const out = try layer.direct.addManyAsSlice(g.arena, (pts.len - 2) * 3);
+ for (1..pts.len - 1) |k| {
+ const tri = out[(k - 1) * 3 ..][0..3];
+ tri.* = .{ p.at(pts[0]), p.at(pts[k]), p.at(pts[k + 1]) };
+ }
+ return;
+ }
// Fans from each contour's first point. Their overlaps cancel or add
// exactly as the winding rule needs, so no triangulation is required.
var triangles: usize = 0;
var it = polys.iterator();
while (it.next()) |pts| triangles += pts.len - 2;
- const fan = try g.arena.alloc(layouts.Vertex, triangles * 3);
+ const fan = try layer.stencil[@backingInt(rule)].addManyAsSlice(g.arena, triangles * 3);
var i: usize = 0;
it = polys.iterator();
while (it.next()) |pts| for (1..pts.len - 1) |k| {
- fan[i + 0] = .{ .position = pts[0] };
- fan[i + 1] = .{ .position = pts[k] };
- fan[i + 2] = .{ .position = pts[k + 1] };
+ fan[i..][0..3].* = .{ .{ .position = pts[0] }, .{ .position = pts[k] }, .{ .position = pts[k + 1] } };
i += 3;
};
- const b = polys.bounds();
- const lo = @max(@floor(b.min), geom.splat(0));
- const hi = @min(@ceil(b.max), geom.Vec{ @floatFromInt(g.width), @floatFromInt(g.height) });
- if (lo[0] >= hi[0] or lo[1] >= hi[1]) return;
- const quad = try g.arena.dupe(layouts.Vertex, &.{
- .{ .position = .{ lo[0], lo[1] } }, .{ .position = .{ hi[0], lo[1] } }, .{ .position = .{ hi[0], hi[1] } },
- .{ .position = .{ lo[0], lo[1] } }, .{ .position = .{ hi[0], hi[1] } }, .{ .position = .{ lo[0], hi[1] } },
- });
- try g.draws.append(g.arena, .{
- .pipeline = if (rule == .nonzero) 0 else 1,
- .vertices = std.mem.sliceAsBytes(fan),
- .vertex_count = @intCast(fan.len),
- .vertex_uniforms = g.viewport,
- });
- try g.draws.append(g.arena, .{
- .pipeline = 2,
- .vertices = std.mem.sliceAsBytes(quad),
- .vertex_count = 6,
- .vertex_uniforms = g.viewport,
- .fragment_uniforms = abi.gpu.uniform(g.arena, block(paint, alpha)),
+ try layer.cover.appendSlice(g.arena, &.{
+ p.at(.{ lo[0], lo[1] }), p.at(.{ hi[0], lo[1] }), p.at(.{ hi[0], hi[1] }),
+ p.at(.{ lo[0], lo[1] }), p.at(.{ hi[0], hi[1] }), p.at(.{ lo[0], hi[1] }),
});
}
-/// `Paint` as the shader's uniform block. More stops than the block holds
-/// are resampled evenly.
+/// The layer for a fill covering pixels `lo` to `hi`, its cells marked.
+fn place(g: *Gpu, lo: geom.Vec, hi: geom.Vec, direct: bool) !*Layer {
+ if (g.grid.len == 0) {
+ g.shift = min_shift;
+ while (cells(g.width, g.shift) * cells(g.height, g.shift) > max_cells) g.shift += 1;
+ g.columns = cells(g.width, g.shift);
+ g.grid = try g.arena.alloc(u32, g.columns * cells(g.height, g.shift));
+ @memset(g.grid, 0);
+ }
+ const x0: u32 = @as(u32, @intFromFloat(lo[0])) >> g.shift;
+ const y0: u32 = @as(u32, @intFromFloat(lo[1])) >> g.shift;
+ const x1: u32 = (@as(u32, @intFromFloat(hi[0])) - 1) >> g.shift;
+ const y1: u32 = (@as(u32, @intFromFloat(hi[1])) - 1) >> g.shift;
+ var top: u32 = 0;
+ for (y0..y1 + 1) |y| for (g.grid[y * g.columns ..][x0 .. x1 + 1]) |cell| {
+ top = @max(top, cell);
+ };
+ const index = layerFor(top, direct);
+ for (y0..y1 + 1) |y| for (g.grid[y * g.columns ..][x0 .. x1 + 1]) |*cell| {
+ cell.* = @max(cell.*, index + 1);
+ };
+ while (g.layers.items.len <= index) try g.layers.append(g.arena, .{});
+ return &g.layers.items[index];
+}
+
+/// The layer for a fill whose box overlaps fills up to layer `top - 1`
+/// (`top` 0: none). A direct fill may join that layer; a stencilled one
+/// goes above it.
+pub fn layerFor(top: u32, direct: bool) u32 {
+ if (top == 0) return 0;
+ return if (direct) top - 1 else top;
+}
+
+fn cells(pixels: u32, shift: u5) u32 {
+ return @max((pixels + (@as(u32, 1) << shift) - 1) >> shift, 1);
+}
+
+/// A fill's paint, as its vertices carry it.
+const Painted = struct {
+ color: [4]f32,
+ gradient: f32,
+
+ fn at(p: Painted, q: geom.Vec) layouts.Painted {
+ return .{ .position = q, .color = p.color, .gradient = p.gradient };
+ }
+};
+
+fn painted(g: *Gpu, paint: *const Paint, alpha: f32) !Painted {
+ if (paint.kind == .solid) return .{ .color = paint.color * @as(@Vector(4, f32), @splat(alpha)), .gradient = -1 };
+ try g.paints.append(g.arena, block(paint, alpha));
+ return .{ .color = @splat(alpha), .gradient = @floatFromInt(g.paints.items.len - 1) };
+}
+
+/// `Paint` as the shader's block. More stops than the block holds are
+/// resampled evenly.
fn block(paint: *const Paint, alpha: f32) layouts.Paint {
const m = paint.to_gradient;
var out: layouts.Paint = .{
@@ -140,8 +241,36 @@ fn unpremultiply(c: @Vector(4, f32)) [4]f32 {
return .{ c[0] / c[3], c[1] / c[3], c[2] / c[3], c[3] };
}
+/// Puts this pass's gradients in GPU memory, before `pass`. `f` is a
+/// `sketch.Frame`. Painted draws bind the buffer even when no fill has a
+/// gradient, so there always is one.
+pub fn upload(g: *Gpu, f: anytype) void {
+ const count: u32 = @intCast(@max(g.paints.items.len, 1));
+ if (count > g.paint_capacity) {
+ if (g.paint_buffer != .none) f.host.freeBuffer(g.paint_buffer);
+ const capacity = std.math.ceilPowerOfTwo(u32, count) catch count;
+ g.paint_buffer = f.host.newBuffer(capacity * @sizeOf(layouts.Paint));
+ g.paint_capacity = if (g.paint_buffer == .none) 0 else capacity;
+ }
+ if (g.paints.items.len > 0 and g.paint_buffer != .none) f.upload(g.paint_buffer, 0, std.mem.sliceAsBytes(g.paints.items));
+}
+
+/// Frees what `upload` made. `host` is a `sketch.Host`.
+pub fn deinit(g: *Gpu, host: anytype) void {
+ if (g.paint_buffer != .none) host.freeBuffer(g.paint_buffer);
+ g.paint_buffer = .none;
+ g.paint_capacity = 0;
+}
+
/// The pass that draws everything recorded since `begin`.
-pub fn pass(g: *const Gpu) abi.gpu.Pass {
+pub fn pass(g: *Gpu) abi.gpu.Pass {
+ g.draws = .empty;
+ const storage = g.arena.dupe(abi.Buffer, &.{g.paint_buffer}) catch &.{};
+ for (g.layers.items) |*layer| {
+ for (layer.stencil, [_]Pipeline{ .nonzero, .evenodd }) |fans, pipeline| g.add(pipeline, std.mem.sliceAsBytes(fans.items), fans.items.len, storage);
+ g.add(.cover, std.mem.sliceAsBytes(layer.cover.items), layer.cover.items.len, storage);
+ g.add(.direct, std.mem.sliceAsBytes(layer.direct.items), layer.direct.items.len, storage);
+ }
return .{
.image = g.image,
.width = g.width,
@@ -154,21 +283,151 @@ pub fn pass(g: *const Gpu) abi.gpu.Pass {
};
}
-test "a fill is a stencil fan and a covering quad with its paint" {
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- var g: Gpu = .{ .width = 100, .height = 50, .image = @fromBackingInt(@intCast(1)) };
- g.begin(arena.allocator(), .{ 0, 0, 0, 1 });
- var p: Polygons = .init(arena.allocator());
- try p.points.appendSlice(arena.allocator(), &.{ .{ 10, 10 }, .{ 40, 10 }, .{ 40, 30 }, .{ 10, 30 } });
- try p.contours.append(arena.allocator(), 4);
- const red: Paint = .solid(.{ 1, 0, 0, 1 });
- g.fill(&p, .evenodd, &red, 0.5);
- const pass_ = g.pass();
- try std.testing.expectEqual(@as(usize, 2), pass_.draws.len);
- try std.testing.expectEqual(@as(u32, 1), pass_.draws[0].pipeline);
- try std.testing.expectEqual(@as(u32, 6), pass_.draws[0].vertex_count);
- const block_ = std.mem.bytesAsValue(layouts.Paint, pass_.draws[1].fragment_uniforms);
- try std.testing.expectEqual(@as(f32, 0.5), block_.extra[1]);
- try std.testing.expectEqual(@as(f32, 1), block_.color[0]);
+fn add(g: *Gpu, pipeline: Pipeline, vertices: []const u8, count: usize, storage: []const abi.Buffer) void {
+ if (count == 0) return;
+ const painted_ = pipeline == .cover or pipeline == .direct;
+ g.draws.append(g.arena, .{
+ .pipeline = @backingInt(pipeline),
+ .vertices = vertices,
+ .vertex_count = @intCast(count),
+ .vertex_uniforms = g.viewport,
+ .fragment_storage = if (painted_) storage else &.{},
+ }) catch {};
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+
+const Test = struct {
+ arena: std.heap.ArenaAllocator,
+ g: Gpu,
+ p: Polygons,
+
+ fn init(t: *Test) void {
+ t.arena = .init(std.testing.allocator);
+ t.g = .{ .width = 100, .height = 50, .image = @fromBackingInt(@intCast(1)) };
+ t.g.begin(t.arena.allocator(), .{ 0, 0, 0, 1 });
+ t.p = .init(t.arena.allocator());
+ }
+
+ fn deinit(t: *Test) void {
+ t.arena.deinit();
+ }
+
+ /// Fills the contours `shape`, offset by `at`.
+ fn fill(t: *Test, shape: []const []const geom.Vec, at: geom.Vec, rule: Drawing.FillRule, paint: Paint) !void {
+ t.p.clear();
+ for (shape) |pts| {
+ for (pts) |q| try t.p.points.append(t.arena.allocator(), q + at);
+ try t.p.contours.append(t.arena.allocator(), @intCast(pts.len));
+ }
+ t.g.fill(&t.p, rule, &paint, 1);
+ }
+
+ fn pipelinesOf(t: *Test) ![]const Pipeline {
+ const draws = t.g.pass().draws;
+ const out = try t.arena.allocator().alloc(Pipeline, draws.len);
+ for (draws, out) |d, *o| o.* = @fromBackingInt(@intCast(d.pipeline));
+ return out;
+ }
+};
+
+const square: []const []const geom.Vec = &.{&.{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 } }};
+/// Not convex: two contours.
+const ring: []const []const geom.Vec = &.{ &.{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 } }, &.{ .{ 3, 3 }, .{ 3, 7 }, .{ 7, 7 }, .{ 7, 3 } } };
+const red: Paint = .solid(.{ 1, 0, 0, 1 });
+
+test "a convex fill is one painted fan, no stencil" {
+ var t: Test = undefined;
+ t.init();
+ defer t.deinit();
+ try t.fill(square, .{ 10, 10 }, .evenodd, red);
+ const draws = t.g.pass().draws;
+ try std.testing.expectEqual(@as(usize, 1), draws.len);
+ try std.testing.expectEqual(@backingInt(Pipeline.direct), draws[0].pipeline);
+ try std.testing.expectEqual(@as(u32, 6), draws[0].vertex_count);
+ const v = std.mem.bytesAsSlice(layouts.Painted, draws[0].vertices);
+ try std.testing.expectEqual([4]f32{ 1, 0, 0, 1 }, v[0].color);
+ try std.testing.expectEqual(@as(f32, -1), v[0].gradient);
+}
+
+test "a fill that is not convex is a stencil fan and a covering quad with its paint" {
+ var t: Test = undefined;
+ t.init();
+ defer t.deinit();
+ t.p.clear();
+ const half: Paint = .solid(.{ 1, 0, 0, 0.5 });
+ try t.fill(ring, .{ 10, 10 }, .evenodd, half);
+ const draws = t.g.pass().draws;
+ try std.testing.expectEqualSlices(Pipeline, &.{ .evenodd, .cover }, try t.pipelinesOf());
+ try std.testing.expectEqual(@as(u32, 12), draws[0].vertex_count);
+ try std.testing.expectEqual(@as(u32, 6), draws[1].vertex_count);
+ const v = std.mem.bytesAsSlice(layouts.Painted, draws[1].vertices);
+ try std.testing.expectEqual([4]f32{ 0.5, 0, 0, 0.5 }, v[0].color);
+ try std.testing.expectEqual(geom.Vec{ 10, 10 }, v[0].position);
+ try std.testing.expectEqual(geom.Vec{ 20, 20 }, v[2].position);
+}
+
+test "fills batch into layers: disjoint ones share draws, overlapping ones keep their order" {
+ var t: Test = undefined;
+ t.init();
+ defer t.deinit();
+ // Three disjoint rings, both rules: one layer, a stencil draw per rule
+ // and one cover draw for all three.
+ try t.fill(ring, .{ 0, 0 }, .nonzero, red);
+ try t.fill(ring, .{ 30, 0 }, .evenodd, red);
+ try t.fill(ring, .{ 60, 0 }, .nonzero, red);
+ try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover }, try t.pipelinesOf());
+ try std.testing.expectEqual(@as(u32, 18), t.g.pass().draws[2].vertex_count);
+ // A convex fill over the first ring joins its layer, drawn after the
+ // covers; a second one over it too, after it.
+ try t.fill(square, .{ 5, 5 }, .nonzero, red);
+ try t.fill(square, .{ 8, 8 }, .nonzero, red);
+ try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover, .direct }, try t.pipelinesOf());
+ // A ring over those goes above them; so does a convex fill over it.
+ try t.fill(ring, .{ 10, 10 }, .nonzero, red);
+ try t.fill(square, .{ 12, 12 }, .nonzero, red);
+ try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover, .direct, .nonzero, .cover, .direct }, try t.pipelinesOf());
+ // Far from everything: the bottom layer again.
+ try t.fill(ring, .{ 80, 30 }, .evenodd, red);
+ try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover, .direct, .nonzero, .cover, .direct }, try t.pipelinesOf());
+ try std.testing.expectEqual(@as(u32, 24), t.g.pass().draws[2].vertex_count);
+}
+
+test "layers: stencilled fills go above what they overlap, direct ones join it" {
+ try std.testing.expectEqual(@as(u32, 0), layerFor(0, false));
+ try std.testing.expectEqual(@as(u32, 0), layerFor(0, true));
+ try std.testing.expectEqual(@as(u32, 3), layerFor(3, false));
+ try std.testing.expectEqual(@as(u32, 2), layerFor(3, true));
+}
+
+test "gradients go to the paint buffer, their vertices carry the index and alpha" {
+ var t: Test = undefined;
+ t.init();
+ defer t.deinit();
+ const stops = [_]Drawing.Gradient.Stop{ .{ .offset = 0, .color = .{ 1, 0, 0, 1 } }, .{ .offset = 1, .color = .{ 0, 0, 1, 1 } } };
+ const gradient: Paint = .{ .kind = .linear, .p1 = .{ 1, 0 }, .stops = &stops };
+ try t.fill(square, .{ 0, 0 }, .nonzero, red);
+ t.p.clear();
+ try t.p.points.appendSlice(t.arena.allocator(), &.{ .{ 30, 0 }, .{ 40, 0 }, .{ 40, 10 }, .{ 30, 10 } });
+ try t.p.contours.append(t.arena.allocator(), 4);
+ t.g.fill(&t.p, .nonzero, &gradient, 0.25);
+ try std.testing.expectEqual(@as(usize, 1), t.g.paints.items.len);
+ try std.testing.expectEqual(@as(f32, 2), t.g.paints.items[0].extra[2]);
+ const draws = t.g.pass().draws;
+ try std.testing.expectEqual(@as(usize, 1), draws.len);
+ try std.testing.expectEqual(@as(usize, 1), draws[0].fragment_storage.len);
+ const v = std.mem.bytesAsSlice(layouts.Painted, draws[0].vertices);
+ try std.testing.expectEqual(@as(f32, -1), v[0].gradient);
+ try std.testing.expectEqual(@as(f32, 0), v[6].gradient);
+ try std.testing.expectEqual([4]f32{ 0.25, 0.25, 0.25, 0.25 }, v[6].color);
+}
+
+test "fills outside the image draw nothing" {
+ var t: Test = undefined;
+ t.init();
+ defer t.deinit();
+ try t.fill(square, .{ 200, 0 }, .nonzero, red);
+ try t.fill(ring, .{ -50, 0 }, .nonzero, red);
+ try std.testing.expectEqual(@as(usize, 0), t.g.pass().draws.len);
}
diff --git a/src/vector/Paint.zig b/src/vector/Paint.zig
index fb838d0..0c56588 100644
--- a/src/vector/Paint.zig
+++ b/src/vector/Paint.zig
@@ -4,7 +4,7 @@
//! which mirrors `param` and `stopColor`.
const Paint = @This();
const std = @import("std");
-const geom = @import("geom.zig");
+const geom = @import("math");
const Drawing = @import("Drawing.zig");
const Vec = geom.Vec;
diff --git a/src/vector/Polygons.zig b/src/vector/Polygons.zig
index c0ed335..c64db3d 100644
--- a/src/vector/Polygons.zig
+++ b/src/vector/Polygons.zig
@@ -4,7 +4,7 @@
//! the same way, so the nonzero rule unions them.
const Polygons = @This();
const std = @import("std");
-const geom = @import("geom.zig");
+const geom = @import("math");
const Drawing = @import("Drawing.zig");
const Vec = geom.Vec;
const Affine = geom.Affine;
@@ -97,6 +97,44 @@ pub fn bounds(p: *const Polygons) geom.Bounds {
return b;
}
+/// Whether `pts`, as a closed contour, is a convex polygon going around once:
+/// every turn the same way (straight runs and repeated points allowed), and
+/// the edge direction's x flips sign at most twice, which rules out
+/// spirals. Its fan from any point then covers each inside point once and
+/// nothing outside, under either fill rule. Exact: the slightest reflex
+/// turn says no.
+pub fn convex(pts: []const Vec) bool {
+ var turn: f32 = 0;
+ var flips: u32 = 0;
+ var first: ?Vec = null;
+ var prev: Vec = undefined;
+ var first_sign: f32 = 0;
+ var last_sign: f32 = 0;
+ for (0..pts.len) |i| {
+ const e = pts[(i + 1) % pts.len] - pts[i];
+ if (e[0] == 0 and e[1] == 0) continue;
+ if (first == null) first = e else if (!turns(prev, e, &turn)) return false;
+ prev = e;
+ if (e[0] != 0) {
+ const sign = std.math.sign(e[0]);
+ if (first_sign == 0) first_sign = sign else if (sign != last_sign) flips += 1;
+ last_sign = sign;
+ }
+ }
+ if (!turns(prev, first orelse return false, &turn)) return false;
+ if (last_sign != first_sign) flips += 1;
+ return turn != 0 and flips <= 2;
+}
+
+/// Whether the corner from edge `a` to edge `b` turns the way `turn` (the
+/// first nonzero cross product so far) does, or goes straight on.
+fn turns(a: Vec, b: Vec, turn: *f32) bool {
+ const cross = geom.cross(a, b);
+ if (cross == 0) return geom.dot(a, b) > 0;
+ if (turn.* == 0) turn.* = cross;
+ return (cross > 0) == (turn.* > 0);
+}
+
/// Iterates contours as point slices.
pub fn iterator(p: *const Polygons) Iterator {
return .{ .p = p };
@@ -368,6 +406,25 @@ fn truncate(list: *std.ArrayList(Vec), len: f32) []const Vec {
return pts;
}
+test "convex contours" {
+ const square = [_]Vec{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 } };
+ try std.testing.expect(convex(&square));
+ // Either orientation, repeated points, a closing point equal to the
+ // first, straight runs.
+ try std.testing.expect(convex(&.{ .{ 0, 10 }, .{ 10, 10 }, .{ 10, 0 }, .{ 0, 0 } }));
+ try std.testing.expect(convex(&.{ .{ 0, 0 }, .{ 5, 0 }, .{ 5, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 }, .{ 0, 0 } }));
+ // A reflex corner (an L), a bow tie, a pentagram, a square wound twice,
+ // a line and a point.
+ try std.testing.expect(!convex(&.{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 5 }, .{ 5, 5 }, .{ 5, 10 }, .{ 0, 10 } }));
+ try std.testing.expect(!convex(&.{ .{ 0, 0 }, .{ 10, 10 }, .{ 10, 0 }, .{ 0, 10 } }));
+ var star: [5]Vec = undefined;
+ for (&star, 0..) |*q, i| q.* = geom.unit(@as(f32, @floatFromInt(i * 2)) * std.math.tau / 5) * geom.splat(10);
+ try std.testing.expect(!convex(&star));
+ try std.testing.expect(!convex(&(square ++ square)));
+ try std.testing.expect(!convex(&.{ .{ 0, 0 }, .{ 10, 0 }, .{ 20, 0 } }));
+ try std.testing.expect(!convex(&.{ .{ 1, 1 }, .{ 1, 1 }, .{ 1, 1 } }));
+}
+
test "a square stroke is four quads and four miters, all wound one way" {
var p: Polygons = .init(std.testing.allocator);
defer p.deinit();
diff --git a/src/vector/layouts.zig b/src/vector/layouts.zig
index 097e682..5d17568 100644
--- a/src/vector/layouts.zig
+++ b/src/vector/layouts.zig
@@ -4,13 +4,26 @@
pub const max_stops = 32;
-/// A path point in device pixels.
+/// A path point in device pixels, for stencil fans.
pub const Vertex = extern struct {
position: [2]f32,
pub const glsl = .vertex;
};
+/// A point of a painted triangle (a cover quad, or a convex fill's fan),
+/// carrying its fill's paint, so fills of any paint share one draw.
+pub const Painted = extern struct {
+ position: [2]f32,
+ /// Solid paints: the premultiplied color times the fill's alpha.
+ /// Gradients: the alpha, in all four.
+ color: [4]f32,
+ /// The gradient's index in the pass's `Paint` buffer; -1 for solid.
+ gradient: f32,
+
+ pub const glsl = .vertex;
+};
+
pub const Viewport = extern struct {
size: [2]f32,
pad: [2]f32 = .{ 0, 0 },
@@ -18,7 +31,8 @@ pub const Viewport = extern struct {
pub const glsl = .{ .uniform = .{ .set = 1, .instance = "viewport" } };
};
-/// A resolved `Paint`, as `cover.frag` reads it.
+/// A resolved gradient `Paint`, as `paint.frag` reads it from a storage
+/// buffer (all members are vec4s, so std430 lays it out as std140 would).
pub const Paint = extern struct {
/// Premultiplied solid color.
color: [4]f32,
@@ -29,12 +43,12 @@ pub const Paint = extern struct {
row1: [4]f32,
/// p0 then p1.
points: [4]f32,
- /// Radius, alpha, stop count.
+ /// Radius, alpha (unused: the vertices carry it), stop count.
extra: [4]f32,
/// Stop offsets, four per element.
offsets: [max_stops / 4][4]f32,
/// Straight stop colors.
colors: [max_stops][4]f32,
- pub const glsl = .{ .uniform = .{ .set = 3, .instance = "paint" } };
+ pub const glsl = .plain;
};
diff --git a/src/vector/morph.zig b/src/vector/morph.zig
index 319eccf..f285c7e 100644
--- a/src/vector/morph.zig
+++ b/src/vector/morph.zig
@@ -4,7 +4,7 @@
//! color is interpolated. A shape without a partner collapses to (or grows
//! from) the other drawing's center.
const std = @import("std");
-const geom = @import("geom.zig");
+const geom = @import("math");
const Drawing = @import("Drawing.zig");
const Vec = geom.Vec;
const Cubic = geom.Cubic;
diff --git a/src/vector/root.zig b/src/vector/root.zig
index 0414286..e5e9975 100644
--- a/src/vector/root.zig
+++ b/src/vector/root.zig
@@ -1,11 +1,12 @@
//! Vector graphics for sketches: SVG in, cubic geometry as data, and two
//! interchangeable renderers. The CPU backend computes exact coverage and
//! runs anywhere (it is also the reference in tests); the GPU backend
-//! describes stencil-then-cover passes for the host to run. The backend is
+//! describes passes for the host to run: convex fills drawn directly, the
+//! rest stencil-then-cover, batched into a few draws (see `Gpu.zig`). The backend is
//! a comptime choice: `vector.Renderer(.gpu)` or `vector.Renderer(.cpu)`.
const std = @import("std");
const abi = @import("abi");
-pub const geom = @import("geom.zig");
+pub const geom = @import("math");
pub const Drawing = @import("Drawing.zig");
pub const svg = @import("svg.zig");
pub const Polygons = @import("Polygons.zig");
@@ -57,7 +58,10 @@ pub fn Renderer(comptime backend: Backend) type {
}
pub fn deinit(r: *Self, host: anytype) void {
- if (backend == .cpu) r.target.deinit();
+ switch (backend) {
+ .cpu => r.target.deinit(),
+ .gpu => r.target.deinit(host),
+ }
r.polys.deinit();
host.freeImage(r.image);
}
@@ -118,7 +122,10 @@ pub fn Renderer(comptime backend: Backend) type {
pub fn present(r: *Self, f: anytype, dst: anytype) void {
switch (backend) {
.cpu => f.pixels(r.image, r.target.width, r.target.height, r.target.pixels, .{ .premultiplied = true }),
- .gpu => f.gpu(r.target.pass()),
+ .gpu => {
+ r.target.upload(f);
+ f.gpu(r.target.pass());
+ },
}
f.image(r.image, dst, .{});
}
diff --git a/src/vector/shaders/cover.frag b/src/vector/shaders/paint.frag
index a57a916..97eb551 100644
--- a/src/vector/shaders/cover.frag
+++ b/src/vector/shaders/paint.frag
@@ -1,11 +1,16 @@
#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.
+// Paints a fill: its solid color, or its gradient times its alpha. A draw
+// holds many fills, so each vertex says which (paint.vert). Mirrors
+// vector/Paint.zig: `param` gives the gradient parameter, `stop_color` the
+// color at it. The Paint struct is generated from vector/layouts.zig.
+layout(location = 0) flat in vec4 fill_color;
+layout(location = 1) flat in int fill_gradient;
layout(location = 0) out vec4 out_color;
#include "Paint.glsl"
+layout(set = 2, binding = 0, std430) readonly buffer Paints { Paint paints[]; };
+#define paint paints[fill_gradient]
float offset_at(int i) {
return paint.offsets[i / 4][i % 4];
@@ -60,6 +65,5 @@ vec4 stop_color(float t) {
}
void main() {
- vec4 c = paint.row0.w < 0.5 ? paint.color : stop_color(param(gl_FragCoord.xy));
- out_color = c * paint.extra.y;
+ out_color = fill_gradient < 0 ? fill_color : stop_color(param(gl_FragCoord.xy)) * fill_color;
}
diff --git a/src/vector/shaders/paint.vert b/src/vector/shaders/paint.vert
new file mode 100644
index 0000000..89c2c82
--- /dev/null
+++ b/src/vector/shaders/paint.vert
@@ -0,0 +1,15 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+// Painted triangles: device pixels (y down) to normalized device
+// coordinates (y up), as in path.vert, with the fill's paint passed on.
+#include "Painted.glsl"
+#include "Viewport.glsl"
+
+layout(location = 0) flat out vec4 fill_color;
+layout(location = 1) flat out int fill_gradient;
+
+void main() {
+ gl_Position = vec4(position.x / viewport.size.x * 2.0 - 1.0, 1.0 - position.y / viewport.size.y * 2.0, 0.0, 1.0);
+ fill_color = color;
+ fill_gradient = int(gradient);
+}
diff --git a/src/vector/svg.zig b/src/vector/svg.zig
index 9c0ec53..31d9b15 100644
--- a/src/vector/svg.zig
+++ b/src/vector/svg.zig
@@ -10,7 +10,7 @@
//! patterns, markers, images, CSS stylesheets. Group opacity is approximated
//! by multiplying it into each shape.
const std = @import("std");
-const geom = @import("geom.zig");
+const geom = @import("math");
const Drawing = @import("Drawing.zig");
const Vec = geom.Vec;
const Affine = geom.Affine;
diff --git a/test/fixtures/drat-meout-v1.state-fixture b/test/fixtures/drat-meout-v1.state-fixture
new file mode 100644
index 0000000..b736bb8
--- /dev/null
+++ b/test/fixtures/drat-meout-v1.state-fixture
Binary files differ
diff --git a/test/reload.script b/test/reload.script
index 863ecc6..d2b2b36 100644
--- a/test/reload.script
+++ b/test/reload.script
@@ -1,4 +1,16 @@
# The counter sketch reloads with a changed layout and keeps its values.
+# A recording made by this build plays without a warning.
+console snapshot 2
+console record 0
+click 10 10
+console stop
+console play 0
+frames 3
+expect clicks 1
+expect-no-log another build
+console stop
+console load 2
+expect clicks 0
click 10 10
click 10 10
expect clicks 2
@@ -8,7 +20,7 @@ console save
load {v2}
expect clicks 2
expect label warm
-expect streak 7
+expect streak 7 ~0.5
click 10 10
expect clicks 12
# The snapshot was migrated with the live state.
@@ -16,3 +28,6 @@ console load 3
expect clicks 2
console set streak 9
expect streak 9
+# The recording was made by the first build: playing it warns.
+console play 0
+expect-log another build
diff --git a/test/render.script b/test/render.script
new file mode 100644
index 0000000..286e1f0
--- /dev/null
+++ b/test/render.script
@@ -0,0 +1,43 @@
+# Phase 3's 2D features natively (test/render.zig); tools/render_web.mjs
+# compares the same frame in Chrome.
+frames 2
+screenshot .zig-cache/render/native.png
+frames 1
+# The target, drawn as is: its translucent circle over white, its rect.
+expect-pixel .zig-cache/render/native.png 60 40 255 127 127 255 2
+expect-pixel .zig-cache/render/native.png 30 80 0 0 255 255 0
+# Tinted half transparent (premultiplied natively: not darker at edges).
+expect-pixel .zig-cache/render/native.png 140 80 127 127 255 255 2
+expect-pixel .zig-cache/render/native.png 170 40 255 191 191 255 2
+# Turned 30 degrees about its centre at 300,60.
+expect-pixel .zig-cache/render/native.png 300 60 255 127 127 255 2
+# Added over 0x404040: red at alpha 128, green opaque, both, the rect.
+expect-pixel .zig-cache/render/native.png 40 175 192 64 64 255 2
+expect-pixel .zig-cache/render/native.png 80 175 192 255 64 255 2
+expect-pixel .zig-cache/render/native.png 160 150 89 89 255 255 2
+# One command, a colour per subpath: red, translucent green, the ring.
+expect-pixel .zig-cache/render/native.png 225 160 255 0 0 255 0
+expect-pixel .zig-cache/render/native.png 260 145 127 255 127 255 2
+expect-pixel .zig-cache/render/native.png 350 137 128 0 128 255 0
+expect-pixel .zig-cache/render/native.png 350 160 255 255 255 255 0
+# The painted target is kept: one repaint so far (the bar is 10 px).
+expect-pixel .zig-cache/render/native.png 15 117 0 0 0 255 0
+expect-pixel .zig-cache/render/native.png 25 117 255 255 255 255 0
+# `set` jumps: the target is painted again, from the new State.
+console set hue 1
+frames 5
+screenshot .zig-cache/render/set.png
+frames 1
+expect-pixel .zig-cache/render/set.png 30 80 0 160 0 255 0
+expect-pixel .zig-cache/render/set.png 25 117 0 0 0 255 0
+expect-pixel .zig-cache/render/set.png 35 117 255 255 255 255 0
+# A snapshot load jumps too; plain frames and `get` do not.
+console save 1
+console get hue
+frames 5
+console load 1
+frames 1
+screenshot .zig-cache/render/load.png
+frames 1
+expect-pixel .zig-cache/render/load.png 35 117 0 0 0 255 0
+expect-pixel .zig-cache/render/load.png 45 117 255 255 255 255 0
diff --git a/test/render.zig b/test/render.zig
new file mode 100644
index 0000000..597b252
--- /dev/null
+++ b/test/render.zig
@@ -0,0 +1,101 @@
+//! Phase 3's 2D features, for the native screenshot test
+//! (test/render.script) and the browser one (tools/render_web.mjs): an
+//! offscreen target with translucent content, drawn plain, with a
+//! translucent tint and turned; additive blending of shapes, a rect and
+//! an image over gray; shapes of several colours in one command; a soft
+//! image from `pixels`, tinted and turned; antialiased shape edges.
+//!
+//! The target is painted only when `in.jumped` (or when made): the bar
+//! under it grows by one step per repaint, and `hue` picks its colour, so
+//! a script can see that `set` repaints and plain frames do not.
+const std = @import("std");
+const sk = @import("sketch");
+const vec = sk.math;
+
+pub const name = "render";
+pub const width = 400;
+pub const height = 300;
+
+pub const State = struct {
+ hue: u8 = 0,
+};
+
+pub const Session = struct {
+ layer: sk.Image = .none,
+ soft: sk.Image = .none,
+ paints: u32 = 0,
+};
+
+const red: sk.Color = .{ .r = 255, .g = 0, .b = 0, .a = 128 };
+
+/// 32 x 32 white, alpha falling off from the middle, like NoC's texture.
+fn soft() [32 * 32]sk.Color {
+ @setEvalBranchQuota(100_000);
+ var px: [32 * 32]sk.Color = undefined;
+ for (0..32) |y| for (0..32) |x| {
+ const d = vec.distance(.{ @floatFromInt(x), @floatFromInt(y) }, .{ 15.5, 15.5 }) / 16;
+ px[y * 32 + x] = sk.Color.white.alphaFloat(1 - d);
+ };
+ return px;
+}
+const soft_pixels = soft();
+
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ f.clear(.white);
+ const fresh = ss.layer == .none;
+ if (fresh) {
+ ss.layer = f.host.newImage(100, 100);
+ ss.soft = f.host.newImage(32, 32);
+ f.pixels(ss.soft, 32, 32, std.mem.sliceAsBytes(&soft_pixels), .{});
+ }
+ if (fresh or f.in.jumped) {
+ ss.paints += 1;
+ f.target(ss.layer);
+ f.clear(sk.Color.black.alpha(0));
+ sk.draw.circle(f, .{ 50, 50 }, 40, .{ .fill = red });
+ f.fill(.{ .x = 10, .y = 60, .w = 50, .h = 30 }, if (s.hue == 0) sk.Color.hex(0x0000ff) else sk.Color.hex(0x00a000));
+ f.target(.none);
+ }
+ // The target three ways: as is, half transparent, turned.
+ f.image(ss.layer, .{ .x = 10, .y = 10, .w = 100, .h = 100 }, .{});
+ f.image(ss.layer, .{ .x = 120, .y = 10, .w = 100, .h = 100 }, .{ .tint = sk.Color.white.alpha(128) });
+ f.imageAt(ss.layer, .place(.{ 300, 60 }, std.math.pi / 6.0), .{});
+ f.fill(.{ .x = 10, .y = 115, .w = @as(f32, @floatFromInt(@min(ss.paints, 30))) * 10, .h = 4 }, .black);
+
+ // Additive blending over gray.
+ f.fill(.{ .x = 10, .y = 130, .w = 180, .h = 90 }, 0x404040);
+ f.blend(.add);
+ sk.draw.circle(f, .{ 60, 175 }, 35, .{ .fill = red });
+ sk.draw.circle(f, .{ 100, 175 }, 35, .{ .fill = sk.Color.hex(0x00c800) });
+ f.fill(.{ .x = 140, .y = 140, .w = 40, .h = 70 }, sk.Color.hex(0x2020ff).alpha(200));
+ f.image(ss.soft, .{ .x = 140, .y = 180, .w = 32, .h = 32 }, .{ .tint = sk.Color.hex(0xff64ff).alpha(200) });
+ f.blend(.alpha);
+
+ // Several colours in one shape: three circles and a ring (two subpaths).
+ var t: sk.draw.Tessellation = .empty;
+ var colors: std.ArrayList(sk.Color) = .empty;
+ const each = [_]struct { at: vec.Vec, color: sk.Color }{
+ .{ .at = .{ 230, 160 }, .color = sk.Color.hex(0xff0000) },
+ .{ .at = .{ 260, 160 }, .color = sk.Color.hex(0x00ff00).alpha(128) },
+ .{ .at = .{ 290, 160 }, .color = sk.Color.hex(0x0000ff).alpha(128) },
+ };
+ for (each) |e| {
+ t.fillCircle(f.scratch, e.at, 20, .identity) catch return;
+ while (colors.items.len < t.ends.items.len) colors.append(f.scratch, e.color) catch return;
+ }
+ t.strokeCircle(f.scratch, .{ 350, 160 }, 25, 8, .identity) catch return;
+ while (colors.items.len < t.ends.items.len) colors.append(f.scratch, sk.Color.hex(0x800080)) catch return;
+ f.shapeColors(&t, colors.items);
+
+ // The soft image: plain, tinted translucent, and turned 45 degrees.
+ f.fill(.{ .x = 210, .y = 200, .w = 180, .h = 90 }, 0x203040);
+ f.image(ss.soft, .{ .x = 220, .y = 220, .w = 32, .h = 32 }, .{});
+ f.image(ss.soft, .{ .x = 270, .y = 220, .w = 32, .h = 32 }, .{ .tint = sk.Color.hex(0xff64ff).alpha(128) });
+ f.imageAt(ss.soft, .place(.{ 346, 236 }, std.math.pi / 4.0), .{ .size = .{ 48, 48 } });
+
+ // Thin antialiased lines: a fan of 1 px strokes.
+ for (0..8) |i| {
+ const a = @as(f32, @floatFromInt(i)) * std.math.pi / 16.0;
+ sk.draw.line(f, .{ 30, 280 }, .{ 30 + 150 * @cos(a), 280 - 50 * @sin(a) }, .{ .stroke = .black });
+ }
+}
diff --git a/test/replay.script b/test/replay.script
new file mode 100644
index 0000000..1c19d3f
--- /dev/null
+++ b/test/replay.script
@@ -0,0 +1,73 @@
+# A recording replays to the state it stopped at: played, seeked, stepped,
+# resumed from the middle, and after the live pointer moved elsewhere.
+# The button is down before recording starts: the recording begins with it.
+move 100 80
+down 100 80
+console snapshot 1
+console record 0
+frames 5
+move 300 200
+frames 5
+up 300 200
+hold left_shift
+move 500 300
+frames 3
+click 400 100
+release left_shift
+click 120 140
+frames 20
+# Saving stops the recording first: slot 2 holds the state at the stop.
+console save 2
+# The button held from before the recording came up at 300,200.
+expect dots.len 3
+expect dots.buffer[0].pos[0] 300
+expect dots.buffer[1].kind big
+expect dots.buffer[1].pos[0] 400
+expect dots.buffer[2].pos[1] 140
+expect dots.buffer[2].kind small
+expect position[0] 120 ~60
+console set dots.buffer[3].pos[1] 7.5
+expect dots.buffer[3].pos[1] 7.5
+# Reading takes no frame: `print` and `console get` leave `updates` alone,
+# and vectors and structs print every value in them.
+expect updates 46
+print dots.buffer[1]
+console get dots.buffer[0].pos
+expect-log dots.buffer[0].pos = { 300, 200 }
+console get dots.buffer[1]
+expect-log dots.buffer[1] = { .pos[0] = 400, .pos[1] = 100, .kind = .big }
+expect updates 46
+
+# Played to the end, one recorded frame per frame.
+console play 0
+frames 60
+expect-snapshot 2
+# Paused at the end: the state does not move.
+frames 10
+expect-snapshot 2
+console seek end
+expect-snapshot 2
+console seek start
+console step 1000
+expect-snapshot 2
+console step -7
+console step 7
+expect-snapshot 2
+# From the middle, played on.
+console seek 200
+console pause
+frames 60
+expect-snapshot 2
+console diff 2
+expect-log same
+
+# A live move, then the same replay.
+console stop
+move 600 20
+down 600 20
+frames 3
+console play 0
+frames 60
+expect-snapshot 2
+expect-no-log another build
+console stop
diff --git a/test/replay.zig b/test/replay.zig
new file mode 100644
index 0000000..096acab
--- /dev/null
+++ b/test/replay.zig
@@ -0,0 +1,48 @@
+//! Replay fixture: state driven by the pointer, buttons, keys and time,
+//! frame by frame, so any difference between a live run and its replay
+//! (batched frames, input state, dt) shows in the bytes.
+const sk = @import("sketch");
+
+pub const name = "replay";
+pub const width = 640;
+pub const height = 360;
+
+const Dot = struct {
+ pos: @Vector(2, f32) = @splat(0),
+ kind: enum(u8) { small = 1, big = 2 } = .small,
+};
+
+pub const State = struct {
+ /// Chases the pointer a little every frame: where it ends depends on
+ /// where the pointer was at each frame, not only at the end.
+ position: @Vector(2, f32) = .{ 320, 180 },
+ velocity: @Vector(2, f32) = @splat(0),
+ /// Sum of `in.dt` over updates, and how many there were.
+ elapsed: u64 = 0,
+ updates: u32 = 0,
+ /// Frames with the left button, and with shift, held.
+ pressing: u32 = 0,
+ shifting: u32 = 0,
+ /// One per click, shaped like `sk.List`.
+ dots: struct { buffer: [8]Dot = @splat(.{}), len: u32 = 0 } = .{},
+};
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ const mouse: @Vector(2, f32) = .{ in.mouse_x, in.mouse_y };
+ s.velocity = (s.velocity + (mouse - s.position) * @as(@Vector(2, f32), @splat(0.01))) * @as(@Vector(2, f32), @splat(0.9));
+ s.position += s.velocity;
+ s.elapsed += in.dt;
+ s.updates += 1;
+ if (in.buttons & 1 != 0) s.pressing += 1;
+ if (in.held(sk.Key.left_shift)) s.shifting += 1;
+ for (in.events) |e| if (e.kind == .mouse_up and s.dots.len < s.dots.buffer.len) {
+ s.dots.buffer[s.dots.len] = .{ .pos = .{ e.x, e.y }, .kind = if (in.held(sk.Key.left_shift)) .big else .small };
+ s.dots.len += 1;
+ };
+}
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ f.clear(0x202020);
+ for (s.dots.buffer[0..s.dots.len]) |d| f.fill(.{ .x = d.pos[0] - 4, .y = d.pos[1] - 4, .w = 8, .h = 8 }, 0x80c0ff);
+ f.fill(.{ .x = s.position[0] - 10, .y = s.position[1] - 10, .w = 20, .h = 20 }, 0xff8040);
+}
diff --git a/test/shapes.script b/test/shapes.script
new file mode 100644
index 0000000..3111d5c
--- /dev/null
+++ b/test/shapes.script
@@ -0,0 +1,30 @@
+# Command.shape natively: each case at points well inside it (edges are
+# aliased here and antialiased on the web; tools/shapes_web.mjs compares
+# whole pictures). Translucent colours blend once per command.
+frames 2
+screenshot .zig-cache/shapes/native.png
+frames 1
+# Two translucent circles: once alone, twice where they overlap.
+expect-pixel .zig-cache/shapes/native.png 60 80 255 127 127 255 2
+expect-pixel .zig-cache/shapes/native.png 110 80 255 63 63 255 2
+# The concave polygon: one blend everywhere inside, nothing in its notch.
+expect-pixel .zig-cache/shapes/native.png 300 40 127 191 127 255 2
+expect-pixel .zig-cache/shapes/native.png 240 40 127 191 127 255 2
+expect-pixel .zig-cache/shapes/native.png 300 120 255 255 255 255 0
+# The acute zig-zag: one blend at its joins too (no overlap, no hole).
+expect-pixel .zig-cache/shapes/native.png 60 228 127 127 255 255 2
+expect-pixel .zig-cache/shapes/native.png 100 372 127 127 255 255 2
+expect-pixel .zig-cache/shapes/native.png 140 228 127 127 255 255 2
+expect-pixel .zig-cache/shapes/native.png 80 300 127 127 255 255 2
+# The ring and its hole.
+expect-pixel .zig-cache/shapes/native.png 300 212 175 95 175 255 2
+expect-pixel .zig-cache/shapes/native.png 300 240 255 255 255 255 0
+# A 1 px line on a pixel row: full intensity, one row.
+expect-pixel .zig-cache/shapes/native.png 300 300 0 0 0 255 0
+expect-pixel .zig-cache/shapes/native.png 300 299 255 255 255 255 0
+expect-pixel .zig-cache/shapes/native.png 300 301 255 255 255 255 0
+# Many circles, one command each and all in one.
+console circles 5000
+frames 2
+console batched 5000
+frames 2
diff --git a/test/shapes.zig b/test/shapes.zig
new file mode 100644
index 0000000..5145143
--- /dev/null
+++ b/test/shapes.zig
@@ -0,0 +1,63 @@
+//! The cases `Command.shape` must draw alike on both hosts, for the native
+//! screenshot test (test/shapes.script) and the browser one
+//! (tools/shapes_web.mjs): overlapping translucent circles, a concave
+//! polygon, an acute translucent zig-zag, a ring, a 1 px line. The console
+//! line `circles N` switches to N circles batched or not (`batched N`),
+//! for timing.
+const std = @import("std");
+const sk = @import("sketch");
+
+pub const name = "shapes";
+pub const width = 400;
+pub const height = 400;
+
+pub const State = struct {
+ circles: u32 = 0,
+ batched: bool = false,
+};
+
+pub const commands = .{ "circles", "batched" };
+
+pub fn command(s: *State, line: []const u8) !bool {
+ var words = std.mem.tokenizeScalar(u8, line, ' ');
+ const verb = words.next() orelse return false;
+ if (!std.mem.eql(u8, verb, "circles") and !std.mem.eql(u8, verb, "batched")) return false;
+ s.circles = try std.fmt.parseInt(u32, words.next() orelse "0", 10);
+ s.batched = std.mem.eql(u8, verb, "batched");
+ return true;
+}
+
+const red: sk.Color = .{ .r = 255, .g = 0, .b = 0, .a = 128 };
+const green: sk.Color = .{ .r = 0, .g = 128, .b = 0, .a = 128 };
+const blue: sk.Color = .{ .r = 0, .g = 0, .b = 255, .a = 128 };
+const purple: sk.Color = .{ .r = 128, .g = 0, .b = 128, .a = 160 };
+
+const arrow = [_]sk.math.Vec{ .{ 220, 20 }, .{ 380, 20 }, .{ 380, 180 }, .{ 300, 70 }, .{ 220, 180 } };
+const zigzag = [_]sk.math.Vec{ .{ 20, 380 }, .{ 60, 220 }, .{ 100, 380 }, .{ 140, 220 }, .{ 180, 380 } };
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ f.clear(sk.Color.white);
+ if (s.circles > 0) return many(s, f);
+ // Two commands: the overlap blends twice, on both hosts.
+ sk.draw.circle(f, .{ 80, 80 }, 50, .{ .fill = red });
+ sk.draw.circle(f, .{ 140, 80 }, 50, .{ .fill = red });
+ sk.draw.polygon(f, &arrow, .{ .fill = green });
+ var t: sk.draw.Tessellation = .empty;
+ t.strokePolyline(f.scratch, &zigzag, 14, .identity) catch return;
+ f.shape(&t, blue);
+ sk.draw.circle(f, .{ 300, 240 }, 30, .{ .stroke = purple, .width = 8 });
+ sk.draw.line(f, .{ 220, 300.5 }, .{ 380, 300.5 }, .{ .stroke = .black });
+}
+
+/// Circles spread by a hash, in one shape each or all in one.
+fn many(s: *const State, f: *sk.Frame) void {
+ var t: sk.draw.Tessellation = .empty;
+ for (0..s.circles) |i| {
+ const h = std.hash.Wyhash.hash(0, std.mem.asBytes(&i));
+ const at: sk.math.Vec = .{ @floatFromInt(h % 400), @floatFromInt((h >> 16) % 400) };
+ if (s.batched) {
+ t.fillCircle(f.scratch, at, 4, .identity) catch return;
+ } else sk.draw.circle(f, at, 4, .{ .fill = .{ .r = @truncate(h >> 32), .g = 40, .b = 90, .a = 160 } });
+ }
+ if (s.batched) f.shape(&t, .{ .r = 200, .g = 40, .b = 90 });
+}
diff --git a/tools/chrome.mjs b/tools/chrome.mjs
new file mode 100644
index 0000000..e3361e9
--- /dev/null
+++ b/tools/chrome.mjs
@@ -0,0 +1,119 @@
+// Headless Chrome (software Canvas2D, no GPU needed) on a built web page,
+// for tests: serves `dir` (plus `extra` files by URL path), opens it at
+// `width` x `height`, waits for `window.sketch`, and hands `run` an
+// `evaluate(expression)` that returns the value. Uncaught page errors fail.
+import {spawn} from 'node:child_process';
+import {createServer} from 'node:http';
+import {mkdtemp, readFile, rm} from 'node:fs/promises';
+import {tmpdir} from 'node:os';
+import {extname, join} from 'node:path';
+import assert from 'node:assert/strict';
+
+export async function withPage({dir, extra = {}, width, height, chromePath}, run) {
+ const types = {'.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.png': 'image/png'};
+ const server = createServer(async (request, response) => {
+ const path = new URL(request.url, 'http://x').pathname;
+ try {
+ const body = extra[path] ? await readFile(extra[path]) : await readFile(join(dir, path === '/' ? 'index.html' : path));
+ response.writeHead(200, {'content-type': types[extname(path)] ?? 'text/html'});
+ response.end(body);
+ } catch {
+ response.writeHead(404);
+ response.end();
+ }
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ const url = `http://127.0.0.1:${server.address().port}/`;
+ const profile = await mkdtemp(join(tmpdir(), 'sketchbook-chrome-'));
+ const chrome = spawn(chromePath || process.env.CHROME || 'google-chrome-stable', ['--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run',
+ '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], {stdio: ['ignore', 'ignore', 'pipe']});
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
+ let socket, stderr = '', sequence = 0;
+ const pending = new Map(), errors = [];
+ try {
+ chrome.stderr.on('data', b => stderr += b);
+ let endpoint;
+ for (let i = 0; i < 100 && !endpoint; i++) {
+ endpoint = stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1];
+ if (chrome.exitCode !== null) throw new Error(stderr);
+ if (!endpoint) await sleep(100);
+ }
+ assert.ok(endpoint, 'Chrome did not start');
+ const tabs = await (await fetch(`${endpoint.replace(/^ws:/, 'http:').split('/devtools/')[0]}/json/list`)).json();
+ socket = new WebSocket(tabs.find(t => t.type === 'page').webSocketDebuggerUrl);
+ await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });
+ socket.onmessage = e => {
+ const m = JSON.parse(e.data);
+ if (m.id) { const p = pending.get(m.id); pending.delete(m.id); m.error ? p.reject(new Error(JSON.stringify(m.error))) : p.resolve(m.result); }
+ else if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails);
+ };
+ const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; pending.set(id, {resolve, reject}); socket.send(JSON.stringify({id, method, params})); });
+ const evaluate = async expression => {
+ const r = await send('Runtime.evaluate', {expression, returnByValue: true, awaitPromise: true});
+ if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails));
+ return r.result.value;
+ };
+ await send('Runtime.enable');
+ await send('Emulation.setDeviceMetricsOverride', {width, height, deviceScaleFactor: 1, mobile: false});
+ await send('Page.navigate', {url});
+ let ready = false;
+ for (let i = 0; i < 100 && !ready; i++) { ready = await evaluate(`!!window.sketch`); if (!ready) await sleep(100); }
+ assert.ok(ready, 'the sketch did not start');
+ await run(evaluate);
+ assert.deepEqual(errors, []);
+ } finally {
+ socket?.close();
+ chrome.kill('SIGTERM');
+ await new Promise(r => chrome.exitCode !== null ? r() : chrome.once('exit', r));
+ await rm(profile, {recursive: true, force: true, maxRetries: 10, retryDelay: 100});
+ server.close();
+ }
+}
+
+// Page code comparing the canvas with `native.png`: pixels away from edges
+// (neither picture changes by more than 8 within a pixel) must agree within
+// `tolerance`; pixels next to edges are only counted, by how far apart.
+export const compareScript = (width, height, tolerance, points) => `(async () => {
+ const W = ${width}, H = ${height};
+ const canvas = document.querySelector('canvas');
+ if (canvas.width !== W || canvas.height !== H) return {error: 'canvas is ' + canvas.width + 'x' + canvas.height};
+ const web = canvas.getContext('2d').getImageData(0, 0, W, H).data;
+ const image = new Image();
+ image.src = 'native.png';
+ await image.decode();
+ const scratch = new OffscreenCanvas(W, H).getContext('2d');
+ scratch.drawImage(image, 0, 0);
+ const native = scratch.getImageData(0, 0, W, H).data;
+ const at = (d, x, y) => [0, 1, 2].map(c => d[(y * W + x) * 4 + c]);
+ const edge = (x, y) => {
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
+ const nx = x + dx, ny = y + dy;
+ if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue;
+ for (const d of [native, web]) {
+ const a = at(d, x, y), b = at(d, nx, ny);
+ if (a.some((v, c) => Math.abs(v - b[c]) > 8)) return true;
+ }
+ }
+ return false;
+ };
+ let compared = 0, differing = 0, worst = 0, first = null, edges = 0, edgeOver16 = 0, edgeOver48 = 0, edgeSum = 0;
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
+ const a = at(native, x, y), b = at(web, x, y);
+ const d = Math.max(...a.map((v, c) => Math.abs(v - b[c])));
+ if (edge(x, y)) { edges++; edgeSum += d; if (d > 16) edgeOver16++; if (d > 48) edgeOver48++; continue; }
+ compared++;
+ worst = Math.max(worst, d);
+ if (d > ${tolerance}) { differing++; first ??= {x, y, native: a, web: b}; }
+ }
+ const sampled = {};
+ for (const [name, [x, y]] of Object.entries(${JSON.stringify(points)})) sampled[name] = {native: at(native, x, y), web: at(web, x, y)};
+ return {compared, edges, differing, worst, first, sampled, edgeOver16, edgeOver48, edgeMean: edges ? edgeSum / edges : 0};
+})()`;
+
+export function report(result, tolerance) {
+ assert.ok(!result.error, result.error);
+ console.log(`compared ${result.compared} pixels away from edges: ${result.differing} differ by more than ${tolerance}, worst ${result.worst}`);
+ console.log(`next to edges ${result.edges}: mean difference ${result.edgeMean.toFixed(1)}, ${result.edgeOver16} over 16, ${result.edgeOver48} over 48`);
+ for (const [name, {native, web}] of Object.entries(result.sampled)) console.log(` ${name.padEnd(8)} native ${native.join(',').padEnd(12)} web ${web.join(',')}`);
+ assert.equal(result.differing, 0, `first difference: ${JSON.stringify(result.first)}`);
+}
diff --git a/tools/reload_edit.zig b/tools/reload_edit.zig
new file mode 100644
index 0000000..0fe2bf3
--- /dev/null
+++ b/tools/reload_edit.zig
@@ -0,0 +1,49 @@
+//! Copies a source tree and applies textual edits to the copy, for
+//! `addReloadCheck`: `reload_edit <in dir> <out dir> [<file> <old> <new>]...`.
+//! Each `old` must occur exactly once in its file (relative to the tree),
+//! or nothing is written and the edit is reported.
+const std = @import("std");
+
+pub fn main(init: std.process.Init) !void {
+ const io = init.io;
+ const arena = init.arena.allocator();
+ var args = init.minimal.args.iterate();
+ _ = args.skip();
+ const in_path = args.next() orelse return error.Usage;
+ const out_path = args.next() orelse return error.Usage;
+ const cwd = std.Io.Dir.cwd();
+
+ var input = try cwd.openDir(io, in_path, .{ .iterate = true });
+ defer input.close(io);
+ var output = try cwd.createDirPathOpen(io, out_path, .{});
+ defer output.close(io);
+
+ var walker = try input.walk(arena);
+ defer walker.deinit();
+ while (try walker.next(io)) |entry| switch (entry.kind) {
+ .directory => try output.createDirPath(io, entry.path),
+ .file, .sym_link => try input.copyFile(entry.path, output, entry.path, io, .{}),
+ else => {},
+ };
+
+ var failed = false;
+ while (args.next()) |file| {
+ const old = args.next() orelse return error.Usage;
+ const new = args.next() orelse return error.Usage;
+ const source = output.readFileAlloc(io, file, arena, .limited(64 << 20)) catch |err| {
+ std.log.err("edit {s}: {t}", .{ file, err });
+ failed = true;
+ continue;
+ };
+ const count = std.mem.count(u8, source, old);
+ if (count != 1) {
+ std.log.err("edit {s}: the text to replace occurs {d} times, not once:\n{s}", .{ file, count, old });
+ failed = true;
+ continue;
+ }
+ const at = std.mem.indexOf(u8, source, old).?;
+ const edited = try std.mem.concat(arena, u8, &.{ source[0..at], new, source[at + old.len ..] });
+ try output.writeFile(io, .{ .sub_path = file, .data = edited });
+ }
+ if (failed) std.process.exit(1);
+}
diff --git a/tools/render_web.mjs b/tools/render_web.mjs
new file mode 100644
index 0000000..1327310
--- /dev/null
+++ b/tools/render_web.mjs
@@ -0,0 +1,13 @@
+// Draws test/render.zig (targets, blend modes, image placement and tint,
+// colours per subpath, antialiased edges) in headless Chrome and compares
+// it with the native host's screenshot of the same frame.
+// usage: node tools/render_web.mjs <web dir> <native.png> [chrome]
+import {withPage, compareScript, report} from './chrome.mjs';
+
+const [dir, nativePng, chromePath] = process.argv.slice(2);
+const points = {target: [30, 70], tinted: [140, 70], targetBlue: [20, 80], turned: [300, 60], add: [80, 175], addRect: [160, 150],
+ addImage: [156, 196], colors: [230, 160], ring: [350, 137], soft: [236, 236], softTint: [286, 236], line: [100, 280]};
+await withPage({dir, extra: {'/native.png': nativePng}, width: 400, height: 300, chromePath}, async evaluate => {
+ const tolerance = 3;
+ report(await evaluate(`(async () => { sketch.frame(performance.now()); sketch.frame(performance.now() + 16); return await ${compareScript(400, 300, tolerance, points)}; })()`), tolerance);
+});
diff --git a/tools/shapes_web.mjs b/tools/shapes_web.mjs
new file mode 100644
index 0000000..913bc8b
--- /dev/null
+++ b/tools/shapes_web.mjs
@@ -0,0 +1,41 @@
+// Draws test/shapes.zig in headless Chrome (software Canvas2D, no GPU
+// needed) and compares it with the native host's screenshot of the same
+// frame: equal within a small tolerance everywhere except next to edges,
+// which both antialias, differently. Then times 5000
+// circles a frame, one shape each and batched into one.
+// usage: node tools/shapes_web.mjs <web dir> <native.png> [chrome]
+import {withPage, compareScript, report} from './chrome.mjs';
+import assert from 'node:assert/strict';
+
+const [dir, nativePng, chromePath] = process.argv.slice(2);
+await withPage({dir, extra: {'/native.png': nativePng}, width: 400, height: 400, chromePath}, async evaluate => {
+ // One frame drawn now, then both pictures compared in the page.
+ const points = {circle: [60, 80], overlap: [110, 80], polygon: [300, 40], notch: [300, 120], join: [60, 228], ring: [300, 212], hole: [300, 240], line: [300, 300], above: [300, 299]};
+ const result = await evaluate(`(async () => { sketch.frame(performance.now()); return await ${compareScript(400, 400, 3, points)}; })()`);
+ report(result, 3);
+ // The 1 px line at full intensity, as natively (a body thinned for an
+ // antialiasing fringe would give half).
+ assert.deepEqual(result.sampled.line.web, [0, 0, 0]);
+ assert.deepEqual(result.sampled.above.web, [255, 255, 255]);
+
+ // Frame time with 5000 circles, raster included (getImageData waits for it).
+ const timing = await evaluate(`(() => {
+ const ctx = document.querySelector('canvas').getContext('2d');
+ const time = line => {
+ sketch.command(line);
+ const times = [];
+ for (let i = 0; i < 12; i++) {
+ const t0 = performance.now();
+ sketch.frame(t0);
+ ctx.getImageData(0, 0, 1, 1);
+ times.push(performance.now() - t0);
+ }
+ times.sort((a, b) => a - b);
+ return times[times.length >> 1];
+ };
+ return {separate: time('circles 5000'), batched: time('batched 5000')};
+ })()`);
+ console.log(`5000 circles a frame, median: ${timing.separate.toFixed(1)} ms as 5000 shapes, ${timing.batched.toFixed(1)} ms batched into one`);
+ const budget = Number(process.env.SHAPES_BUDGET_MS ?? 16);
+ for (const [how, ms] of Object.entries(timing)) assert.ok(ms < budget, `5000 circles (${how}) took ${ms.toFixed(1)} ms, over ${budget} ms`);
+});
diff --git a/tools/spirv_strip.zig b/tools/spirv_strip.zig
new file mode 100644
index 0000000..e10711a
--- /dev/null
+++ b/tools/spirv_strip.zig
@@ -0,0 +1,33 @@
+//! Drops memory-access operands (`Aligned 4`) from OpLoad/OpStore: Zig
+//! emits them, Vulkan accepts them, naga's SPIR-V reader does not.
+const std = @import("std");
+
+pub fn main(init: std.process.Init) !void {
+ var args = init.minimal.args.iterate();
+ _ = args.skip();
+ const in_path = args.next().?;
+ const out_path = args.next().?;
+ const cwd = std.Io.Dir.cwd();
+ const arena = init.arena.allocator();
+ const bytes = try cwd.readFileAlloc(init.io, in_path, arena, .limited(16 << 20));
+ const words: []const u32 = @alignCast(std.mem.bytesAsSlice(u32, bytes));
+ if (words.len < 5 or words[0] != 0x07230203) return error.NotSpirv;
+ var out: std.ArrayList(u32) = .empty;
+ try out.appendSlice(arena, words[0..5]);
+ var i: usize = 5;
+ while (i < words.len) {
+ const count = words[i] >> 16;
+ const opcode = words[i] & 0xffff;
+ if (count == 0 or i + count > words.len) return error.Malformed;
+ // OpLoad: op, type, id, pointer; OpStore: op, pointer, object.
+ const keep: u32 = switch (opcode) {
+ 61 => @min(count, 4),
+ 62 => @min(count, 3),
+ else => count,
+ };
+ try out.append(arena, (keep << 16) | opcode);
+ try out.appendSlice(arena, words[i + 1 .. i + keep]);
+ i += count;
+ }
+ try cwd.writeFile(init.io, .{ .sub_path = out_path, .data = std.mem.sliceAsBytes(out.items) });
+}
diff --git a/tools/wasi_run.mjs b/tools/wasi_run.mjs
new file mode 100644
index 0000000..ab5d95a
--- /dev/null
+++ b/tools/wasi_run.mjs
@@ -0,0 +1,9 @@
+// Runs a wasm32-wasi program (a Zig test binary) under Node's WASI, with
+// the rest of the arguments as its own; exits with its exit code.
+// usage: node tools/wasi_run.mjs program.wasm [args...]
+import {readFile} from 'node:fs/promises';
+import {WASI} from 'node:wasi';
+
+const wasi = new WASI({version: 'preview1', args: process.argv.slice(2), env: {}, returnOnExit: true});
+const module = await WebAssembly.compile(await readFile(process.argv[2]));
+process.exitCode = wasi.start(await WebAssembly.instantiate(module, wasi.getImportObject()));
diff --git a/web/host.js b/web/host.js
index aa45840..2c410f7 100644
--- a/web/host.js
+++ b/web/host.js
@@ -4,7 +4,9 @@
// about any particular sketch.
const canvas = document.querySelector('canvas');
const status = document.querySelector('#status');
-const ctx = canvas.getContext('2d', {alpha: false});
+const screen = canvas.getContext('2d', {alpha: false});
+// Where 2D commands draw: the canvas, or an image's (`Command.target`).
+let ctx = screen, drawing = null, composite = 'source-over';
const decoder = new TextDecoder();
const encoder = new TextEncoder();
const images = [null];
@@ -26,9 +28,9 @@ function fit() {
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;
+ if (clipped && ctx === screen) { ctx.restore(); clipped = false; }
+ screen.setTransform(canvas.width / w, 0, 0, canvas.height / h, 0, 0);
+ screen.imageSmoothingEnabled = false;
}
// Hands bytes to the sketch: into memory it allocates, which the export
@@ -405,6 +407,66 @@ function deliver() {
gpu.arrived = [];
}
+// Draws `source` (or its `sw` x `sh` region at `sx`, `sy`) into `x, y, w,
+// h`, its colour multiplied by `r, g, b` as SDL's colour mod does, which
+// canvas compositing cannot do exactly where the image is translucent. So
+// the pixels are multiplied one by one into a scratch canvas kept per
+// image, and kept while the tint, region and image stay the same (an
+// animated alpha costs nothing: that is `globalAlpha`). A GPU pass's output
+// changes every frame and cannot be read cheaply: it goes through the
+// compositing approximation, exact where it is opaque.
+function drawTinted(entry, source, x, y, w, h, sx, sy, sw, sh, r, g, b) {
+ if (r === 255 && g === 255 && b === 255) {
+ if (sw > 0) ctx.drawImage(source, sx, sy, sw, sh, x, y, w, h); else ctx.drawImage(source, x, y, w, h);
+ return;
+ }
+ const iw = sw > 0 ? Math.ceil(sw) : source.width, ih = sh > 0 ? Math.ceil(sh) : source.height;
+ if (!iw || !ih) return;
+ const region = sw > 0 ? [sx, sy, sw, sh] : [0, 0, source.width, source.height];
+ const key = `${r},${g},${b},${region},${entry.version ?? 0}`;
+ const scratch = entry.tinted ??= document.createElement('canvas');
+ if (entry.texture || entry.tintKey !== key) {
+ if (scratch.width !== iw || scratch.height !== ih) { scratch.width = iw; scratch.height = ih; }
+ const t = scratch.getContext('2d', {willReadFrequently: !entry.texture});
+ t.globalCompositeOperation = 'copy';
+ t.drawImage(source, ...region, 0, 0, iw, ih);
+ if (entry.texture) {
+ t.globalCompositeOperation = 'multiply';
+ t.fillStyle = `rgb(${r},${g},${b})`;
+ t.fillRect(0, 0, iw, ih);
+ t.globalCompositeOperation = 'destination-in';
+ t.drawImage(source, ...region, 0, 0, iw, ih);
+ } else {
+ const pixels = t.getImageData(0, 0, iw, ih), d = pixels.data;
+ for (let i = 0; i < d.length; i += 4) { d[i] = d[i] * r / 255; d[i + 1] = d[i + 1] * g / 255; d[i + 2] = d[i + 2] * b / 255; }
+ t.putImageData(pixels, 0, 0);
+ }
+ entry.tintKey = entry.texture ? null : key;
+ }
+ ctx.drawImage(scratch, 0, 0, iw, ih, x, y, w, h);
+}
+
+// Command.image: as on native, a GPU pass's output scales smoothly, an
+// image nearest; `tint` multiplies, its alpha as `globalAlpha`. `place`
+// sets the transform `x, y, w, h` are drawn under.
+function drawImage(id, x, y, w, h, sx, sy, sw, sh, r, g, b, a, place) {
+ const entry = images[id];
+ if (id && entry === drawing) return; // Drawing into itself: nothing.
+ const ready = entry?.texture || (entry?.source && !(entry.source instanceof Image && !entry.w));
+ ctx.save();
+ if (place) ctx.transform(...place);
+ if (!ready) {
+ ctx.fillStyle = '#6e1e46';
+ ctx.fillRect(x, y, w, h);
+ } else {
+ if (entry.texture) gpu.present(entry);
+ ctx.globalAlpha = a / 255;
+ ctx.imageSmoothingEnabled = !!entry.texture;
+ drawTinted(entry, entry.texture ? entry.shown : entry.source, x, y, w, h, sx, sy, sw, sh, r, g, b);
+ }
+ ctx.restore();
+}
+
const imports = {
host: {
log(ptr, len) { console.log(string(ptr, len)); },
@@ -439,32 +501,78 @@ const imports = {
openFile(command, commandLen, pattern, patternLen) { openFile(string(command, commandLen), string(pattern, patternLen)); },
},
canvas: {
- clear(r, g, b, a) { ctx.fillStyle = rgba(r, g, b, a); ctx.fillRect(0, 0, size[0], size[1]); },
+ // Replaces, ignoring the blend, as SDL's clear does; into an image with
+ // its alpha too.
+ clear(r, g, b, a) {
+ ctx.save();
+ ctx.globalCompositeOperation = drawing ? 'copy' : 'source-over';
+ ctx.fillStyle = rgba(r, g, b, a);
+ ctx.fillRect(0, 0, drawing ? drawing.w : size[0], drawing ? drawing.h : size[1]);
+ ctx.restore();
+ },
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?.texture) {
- // GPU renders scale smoothly, as on native.
- gpu.present(entry);
- ctx.globalAlpha = alpha / 255;
- ctx.imageSmoothingEnabled = true;
- if (sw > 0) ctx.drawImage(entry.shown, sx, sy, sw, sh, x, y, w, h); else ctx.drawImage(entry.shown, x, y, w, h);
- ctx.imageSmoothingEnabled = false;
- ctx.globalAlpha = 1;
- return;
+ image(id, x, y, w, h, sx, sy, sw, sh, r, g, b, a) { drawImage(id, x, y, w, h, sx, sy, sw, sh, r, g, b, a, null); },
+ // The unit square onto the three corners, and the image into it.
+ imageCorners(id, x0, y0, x1, y1, x2, y2, sx, sy, sw, sh, r, g, b, a) {
+ drawImage(id, 0, 0, 1, 1, sx, sy, sw, sh, r, g, b, a, [x1 - x0, y1 - y0, x2 - x0, y2 - y0, x0, y0]);
+ },
+ // Command.target: later 2D commands draw into the image's canvas (at
+ // its pixels, 1:1), or the screen for 0. Unclips, as native does.
+ target(id) {
+ if (clipped) { ctx.restore(); clipped = false; }
+ const entry = id ? images[id] : null;
+ if (id && !entry?.ctx) return;
+ ctx = entry ? entry.ctx : screen;
+ drawing = entry;
+ if (entry) { entry.version = (entry.version ?? 0) + 1; ctx.imageSmoothingEnabled = false; }
+ ctx.globalCompositeOperation = composite;
+ },
+ // Command.blend, by abi.BlendMode value.
+ blend(mode) { composite = ['source-over', 'lighter'][mode] ?? 'source-over'; ctx.globalCompositeOperation = composite; },
+ // Command.shape: its subpaths filled nonzero (the triangles are for
+ // native), one path per positively wound subpath together with the
+ // negatively wound ones after it (its holes). One fill per shape, as
+ // native blends once per triangle: shapes batched into one command
+ // that overlap blend twice on both hosts. Canvas2D also slows down
+ // badly on one path of thousands of subpaths (5000 circles: 200 ms
+ // as one path, 9 ms as 5000).
+ // With `colors`, each group fills in its first subpath's colour.
+ shape(ptr, len, endsPtr, endsLen, colorsPtr, colorsLen, r, g, b, a) {
+ if (!len || !endsLen) return;
+ const p = new Float32Array(wasm.memory.buffer, ptr, len * 2);
+ const ends = new Uint32Array(wasm.memory.buffer, endsPtr, endsLen);
+ const colors = colorsLen ? new Uint8Array(wasm.memory.buffer, colorsPtr, colorsLen * 4) : null;
+ const style = k => k < colorsLen ? rgba(colors[4 * k], colors[4 * k + 1], colors[4 * k + 2], colors[4 * k + 3]) : rgba(r, g, b, a);
+ ctx.fillStyle = style(0);
+ ctx.beginPath();
+ let start = 0, open = false;
+ for (let k = 0; k < endsLen; k++) {
+ const end = Math.min(ends[k], len);
+ if (end - start >= 3) {
+ let area = 0;
+ for (let i = start, j = end - 1; i < end; j = i++) area += p[2 * j] * p[2 * i + 1] - p[2 * i] * p[2 * j + 1];
+ if (area > 0 && open) { ctx.fill('nonzero'); ctx.beginPath(); }
+ if (area > 0 && colors) ctx.fillStyle = style(k);
+ ctx.moveTo(p[2 * start], p[2 * start + 1]);
+ for (let i = start + 1; i < end; i++) ctx.lineTo(p[2 * i], p[2 * i + 1]);
+ ctx.closePath();
+ open = true;
+ }
+ start = Math.max(start, end);
}
- 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;
+ if (open) ctx.fill('nonzero');
},
+ // Always blended alpha, as native text is.
text(x, y, scale, ptr, len, r, g, b, a) {
+ ctx.save();
+ ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = rgba(r, g, b, a);
// The native font is a fixed 8px cell: the same advance, and a size
// whose capitals fill the cell as native ones do.
ctx.font = `${10 * scale}px monospace`;
ctx.textBaseline = 'top';
for (const [i, ch] of Array.from(string(ptr, len)).entries()) ctx.fillText(ch, x + i * 8 * scale, y);
+ ctx.restore();
},
clip(enabled, x, y, w, h) {
if (clipped) { ctx.restore(); clipped = false; }
@@ -481,6 +589,7 @@ const imports = {
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);
+ entry.version = (entry.version ?? 0) + 1;
},
},
gpu: {
@@ -629,6 +738,9 @@ try {
command(line) { const encoded = encoder.encode(line); wasm.sk_command(give(encoded), encoded.length); },
sound(name, samples) { const encoded = encoder.encode(name); wasm.sk_sound(give(encoded), encoded.length, give(samples), samples.length); },
size: () => size,
+ // Runs one frame now, at `ms` on the page's clock, for tests that time
+ // or compare frames without waiting for the display.
+ frame(ms) { frameNumber++; deliver(); wasm.sk_frame(ms); },
// 'running', or 'suspended' until a tap or key starts sound.
audio: () => sound.context.state,
};