# Critique: minimalism, Zig idiom, evidence (critic-zig) Inputs: board.md, research-love-raylib.md, research-processing-p5.md, research-zig-internals.md, friction-a.md (friction-b.md had not appeared when this was written; porter-b's board entries were used instead), the 12 ports and both helper files, `lib/sketchbook/src/{sketch,vector,host}`, and `sketches/shaders/README.md`. The rule I applied: a proposal gets in only if it removes lines (or a bug) that the ports actually contain. Code lines below are non-blank, non-comment lines. The ports total 778 lines and the helpers 296 (helpers_a 128, helpers_b 168). ## 0. The groupthink, in one paragraph All three researchers reached the same conclusions: a Pen, `Command.shape`, a Clock, an Rng, noise, a List, targets with `jumped`, blend modes, colour helpers, image affines and build-option modes. They read each other's notes, so the agreement is weak evidence. The ports use far less than that: | Feature | Ports that use it | | --- | --- | | filled and stroked circle | 9 | | single line segment | 3 (angular_forces, pendulum, flow_field) | | convex triangle | 2 (flocking, flow_field) | | transform: translate then rotate, always that pair | 3 | | alpha in the fill | 4 | No port uses an arc, an ellipse, a polyline with joins, a concave polygon, a stroked rect, a blend mode, HSV, an image transform, a text transform, a camera, randomness in `draw`, a Gaussian, `pick`, or `fork`. Everything in that list is deferred below. A NoC chapter that needs one of them adds it then. The researchers also share one mistake. **All three Clock designs are wrong under replay.** See the Clock row in §1 (Time and input). That is the strongest finding here. ## 0b. Layering (owner constraint, board "Owner: layering") The new API sits on top of what exists, the way `std.Io` sits on `std.posix`. Nothing below it changes: `abi.Command`, `f.emit`, GPU passes, `Input.events` and today's Frame methods (`clear`, `fill`, `text`, `image`, ...). The new layer adds **one** host primitive, `Command.shape`. The rest is sketch-library code with no state of its own. | Level | Namespace | What it is | State | | --- | --- | --- | --- | | L0 (exists) | `sk.abi`, `f.emit`, `f.gpu`, `f.fill/clear/text/image`, `in.events` | commands as data | none | | L0 (new) | `abi.Command.shape { color, triangles }` | the only new host primitive | none | | L1 (new) | `sk.draw` geometry functions: `fillCircle`, `strokeCircle`, `fillPolygon`, `strokePolygon`, `strokeLine`, each appending to a caller-owned `std.ArrayList([2]f32)` with an explicit allocator | **the exposed intermediate data**: triangles you emit as a `shape`, merge, or upload into your own GPU pass | none: the caller owns the list | | L2 (new) | `sk.draw.circle/line/polygon(f, ..., pen)` with `sk.draw.Pen` (plain data) | the convenience: L1 into `f.scratch`, then `f.emit(.shape)` once for the fill and once for the stroke | none: the Pen is a value the caller passes | | math (new) | `sk.math`: the `geom` module shared with `vector` (`Vec`, the vec functions, `Affine`), and `noise` | pure functions | none | | time and data (new) | `sk.Clock` and `sk.List` in the root, next to `Camera` and `tween` | plain State data with methods over `Input` | only the State the sketch declares | This settles three of my verdicts in the layered design's favour: - **Pen holding `*Frame` (love/p5): still rejected, now for one more reason.** A Pen that owns its sink cannot hand you triangles without emitting them. L2 is free functions in `sk.draw` that take `f`. Frame gets **no** new methods, so today's Frame stays exactly as it is. - **Batching:** with L1 exposed, a sketch batches **explicitly** by appending many shapes to one list and emitting once. Neither the Frame nor the host needs to batch. See the flocking rewrite in §2. - **Clock** is L2 over `Input.events`. The L1 form already exists: loop over `in.events` and handle `.tick`, as B's ports do. Both stay valid. A sketch can drop a level at any point without rewriting the rest. §2 shows it in every rewrite: flocking emits L1 triangles itself, fluid_resistance mixes `f.fill` with `sk.draw.circle`, and angular_forces uses L2 only. --- ## 1. Verdicts Columns: **+lib** is the estimated lines added to sketchbook. **−noc** is the lines it removes from the noc ports and helpers. ### Drawing | Proposal | Verdict | +lib | −noc | Why | | --- | --- | --- | --- | --- | | love P2 / p5 P1 / zig A→B: `Command.shape { color, triangles }`, tessellated in the lib | **Accept, without `fringe` in iteration 1** | abi 5, native ~30, web ~25 | (with the Frame shapes below) | It is the only design where both hosts get the same geometry and the hosts stay small. The fringe is an optional field the web ignores, and because host and sketch are built together (`abi.hash`), adding it later costs nothing. **Caveat:** native shapes will be aliased until the fringe lands, and the current ports get 8x MSAA from the vector module. If the owner does not accept that, the fringe is the one thing to pull forward (~60 lib lines). Do not pull batching or join/cap options forward with it. | | love P1 / p5 P2: `Pen` holding `*Frame`, with methods `circle/ellipse/arc/rect/roundRect/line/polyline/polygon/point/image/print/draw(Path)` | **Shrink**: `sk.draw.Pen` as plain data (no pointer); L1 triangle functions; three L2 functions `sk.draw.circle/line/polygon(f, ..., pen)`. **No new Frame methods.** | ~150 (tessellation for convex fill, closed convex stroke ring, a segment with round caps, segment count from the error bound) | helpers_b Pen/Canvas/gray 44, helpers_a showGpu 9, and ~110 lines of port plumbing (Session renderers ×9, `vector` imports ×4, pen setup ×10, `show` ×10, `paint` wrappers 5×4, `catch {}` ×6) | **Data, not an object.** A `Pen` with no `*Frame` can be a file-scope `const` (`const boid_pen: sk.draw.Pen = .{...}`), a `State` field (a colour picker), or a comptime value. The draw target appears at every call, as in `writer.print`. A Pen holding `*Frame` cannot do any of that, and it cannot yield triangles without emitting them (the layering rule). "push/pop = copy" still works: `const p = pen.transformed(m)`. **Surface:** `circle`, `line`, `polygon` (convex). Nothing else has evidence. | | p5 P2 `pen.with(overrides: anytype)` | **Reject** | | | This is anytype soup: the field names are checked only by `@hasField`, and there is no ZLS completion. Copy the value and assign the field (`var p = pen; p.fill = null;`), or use a typed decl literal. | | p5 P2 `sk.Path` builder (beginShape/vertex) | **Defer** | | 0 | No port builds a path. | | p5 P1 Frame-side batching (patching the last command's slice) | **Reject** | | 0 | Hidden state in the Frame ("the open batch"), which is a mode by another name. With L1 exposed, a sketch that needs it batches explicitly: append many shapes to one list, emit once (flocking in §2). Opaque only, which research-p5 is right about. No host coalescing in iteration 1. | | love P5 / p5 P9 blend `{alpha, add, multiply}` | **Defer** | | 0 | No port uses it. | | love P6 / p5 P10 / zig §5 offscreen `target` + `newTarget` + `Input.jumped` + `sk.Layer` + `sk.Ring` | **Defer**, but **accept the MSAA `clear = null` load fix** (gpu.zig:213, ~5 lines; it is a parity bug) | ~150 across abi, both hosts and the lib | ~30 (helpers_a Trail, plus about 6 in noise_walker) | Evidence: 2 of 12 ports (random_walk, noise_walker), and both have **correct** workarounds today: a bitset in State, and a shadow simulation in Session. The proposal makes trails faster but **wrong after a seek** unless the full history is in State. research-zig concedes this ("for pictures that must be exact under seek, keep the data in State"). Under that rule the Ring holds only the last N steps, so a seek repaints a short trail. Paying ~150 lines to trade correctness for speed in 2 sketches does not pay. Once the load fix lands, a GPU vector layer can accumulate trails with no new ABI. | | love P7 / p5 P6b image affine; the web tint fix | **Defer the affine. The tint parity bug belongs to critic-core.** | | 0 | No port draws images. | | love P8 textures in passes, P9 `instances` | **Defer** | | 0 | Outside NoC. The shader pass is where to make the case for them. | | p5 P11 rect anchors, P12 `sk.fx`, P13 export | **Defer** | | 0 | No evidence. | | zig §6: `draw`/`update`/`init` may return `!void` | **Defer** | 8 | 0 once shapes are infallible | All 5 `paint` wrappers exist only because helper `Pen` calls can fail. The L2 `sk.draw` functions log and drop on OOM, as `emit` already does, so the wrappers disappear with the shapes. | ### Math | Proposal | Verdict | +lib | −noc | Why | | --- | --- | --- | --- | --- | | zig §3: `sk.Vec2 = extern struct {x, y}` with methods `add/sub/scale/...` as the type to store | **Reject** | ~120 | **negative** | Physics gets longer and noisier: `m.velocity += m.acceleration` becomes `m.velocity = m.velocity.add(m.acceleration)` at about 15 sites. porter-a counted `+=` as the one place sketchbook already beats Processing. Method chains like `.xy(..).sub(..).withLen(..)` are the PVector DSL in Zig syntax. It also loses the shader symmetry: `@Vector(2, f32)` is SPIR-V's `vec2` (shaders README). Both real problems it solves have smaller fixes: (1) inspection, by splitting vector leaves; (2) the Debug 16-byte layout, because migration matches leaves **by path** (memory.zig:95-111), so lane leaves `pos[0]`/`pos[1]` migrate across `-Doptimize` changes. | | zig §3.3: `layout.flatten` splits `@Vector(N, T)` into N lane leaves | **Accept**, top value per line | ~10, plus ~5 in fields.zig `set` | together with `expect ~tol` (below): the test-only fields `bounces`, `caught`, `frame_count`×3, `resets`, `fields_made`, `ticks` (~16 lines with comments) | Gives `get/set/expect position[0]`. Fixes vectors resetting when you switch `-Doptimize`. Needs no new types. | | love P10 `sk.v2` / p5 P7 `sk.V2` + 15 functions / helpers_b's 8 | **Shrink to 8 free functions** in one `geom` module shared by `sketch` and `vector` (`vector/geom.zig` already has `length`, `normalize`, `dot`, `cross`, `perp`, `splat`, `mix`) | ~15 new, ~5 in build.zig | helpers_b vec 25 | Free functions over `@Vector`, as geom already does. Use Zig names, with a PVector table in the docs: `scale`, `distance`, `withLength` (setMag), `clampLength` (limit), `angle` (heading), `unit` (fromAngle). Drop `rotate`, `reflect`, `angleBetween`, `lerp` (tween.lerp has it), and `cross`/`perp` (they already exist): none of them has evidence. Keep `angle` out of shader code, because atan2 is table-driven (shaders README). | | zig `Affine` lifted into the sketch lib | **Accept**, as part of the shared `geom` module, plus `Affine.place(at: Vec, radians: f32)` (translate·rotate, 3 lines) | 3 | removes 11 `[0], [1]` argument pairs at draw sites and shortens 3 lines | All 3 transform sites in the ports are exactly `translate(p[0], p[1]).mul(.rotate(a))`. | | zig §3.4 / p5 P7 / helpers_a `map`/`remap` | **Reject** | 0 | helpers_a map 5 | All 3 uses map 0..1 or -1..1: `std.math.lerp(0, width, n)` covers them, as the_wave.zig:38 already does. `tween.progress` is the clamped inverse. `smoothstep`, `fract`, `angle`, `approach`: no evidence. | | p5 P8 colour: `hsv/hsl/oklch/mix`, HSV duck typing | **Defer.** Accept only **`Color.gray(v: u8)`** | 3 | helpers_b gray 4 (its 22 call sites stay one call each) | No port uses HSV. Typed `?Color` fields make `.fill = .gray(127)` work as a decl literal through the optional. **Checked:** `.gray(127).alpha(127)` does *not* compile ("type '@EnumLiteral()' not a function"), so alpha reads `sk.Color.gray(127).alpha(127)`. That is fine. Do not add `grayAlpha`. | ### Time and input | Proposal | Verdict | +lib | −noc | Why | | --- | --- | --- | --- | --- | | love P3 `Clock.advance(in, hz, max)` / p5 P5 `Clock.steps(in, hz)` / zig `Clock.advance(in, hz)` / helpers_a `steps60` | **Accept the type, after the host fix below.** Without that fix, all four are a replay bug. | ~15 | steps60 10, and `frame_count` in 4 ports (→ `clock.count`, ~8) | **All four sum every tick in `in.events` and then step.** Live, an update has one tick, so this works. On seek, `runLine` feeds every replayed event in **one** update (Host.zig:437, timeline.zig:158-166), and so does playback that falls behind (`h.tick(now)`). The sketch then sees all the clicks first and steps afterwards. `in.mouse_x` is the final position for every step (Host.zig:246 tracks the whole batch before the call). So **accel_to_mouse.zig:29-35 and fluid_resistance.zig:76-88 diverge from their live run after a seek** (found by reading the code, not by running it). B's ports avoid this only because they loop over `in.events` by hand. **Shape:** `hz` is a field, not an argument (`clock: sk.Clock = .{ .hz = 60 }`), so `set clock.hz 30` gives slow motion from the console. Fields: `hz`, `owed`, `count`. No `alpha` (no port interpolates), no variable-dt `advance`, no `seconds`. | | porter-b #2 / research-p5's dt bug / research-p5 P14 `prevMouse` | **Host: one `update` call per tick.** `Host.update` splits the batch after each `tick`, then tracks, sets `in.dt`/`in.now` from that frame, and calls the sketch. | ~12, native only (the web driver already feeds one frame at a time) | pendulum's `mouse` tracking 5, and makes `in.mouse_x`/`in.buttons`/`in.pressed` correct in `update` | **The smallest fix for a whole class of bugs:** the Clock sum, end-of-batch pointer state, and `in.dt`/`in.now` in replay all go away at once. The alternatives are worse. An `in.steps()` iterator is a new API that every sketch must remember to use. Making `update` unable to see `dt`/`now` changes `Input`. Hand-tracking pointer state in State puts the burden on every sketch. Seek costs no more: the steps are the same, only there are more calls. I am asking critic-core to check this. | | love P3 / p5 P14 `released/clicked/unclicked/wheel/typed/elapsed` | **Defer** | 6 | ~0 | `if (in.clicked(.left))` is the same line count as `for (in.events) \|e\| if (e.kind == .mouse_down)`. Once the host fix makes `in.pressed` correct in replay, flow_field.zig:89 can call `in.pressed(.space)`, which already exists. | | porter-b: put the held buttons in `Event.code` on `mouse_move` | **Defer** | 2 per host | flocking `pressed` 4 | Cheap, but it changes what old recordings mean, and with one tick per update `in.buttons` is close enough. | ### Randomness and noise | Proposal | Verdict | +lib | −noc | Why | | --- | --- | --- | --- | --- | | love P4 `sk.Rng extern {s: [4]u32}` with `float/range/chance/normal/pick/fork` / p5 P3 PCG32 `Rng` with `spare`, `onCircle`, `fork`, `random()` | **Reject the wrapper type** | ~100 | 0 | It duplicates `std.Random`, which is already the interface and already has `float`, `floatNorm`, `uintLessThan`, `intRangeLessThan`, `shuffle`, `weightedIndex`, `enumValue` (Random.zig:82-407). research-zig is right that a wrapper only copies std's API. Store a **concrete** generator, `std.Random.Xoshiro256`, never the `DefaultPrng` alias (0 lines, docs only). Pinning `float()` itself against a std change is a toolchain-compatibility question for critic-core, not an API one: the host and sketch are built by one compiler anyway. | | zig §2 free functions `range/gaussian/chance/unit/inRect/pick/acceptReject/stream` / helpers_b `random(rng, lo, hi)` | **Reject** | 0 | helpers_b random 3 | All 11 uses of `random(lo, hi)` become `std.math.lerp(lo, hi, r.float(f32))`. That is std only and the same length. **Checked:** `std.math.lerp(-1, 1, r.float(f32))` compiles to f32 and gives the same bits in self-hosted Debug, `-fllvm`, ReleaseFast and `-mcpu=x86_64` without FMA (checksum 5e10c88f over 100k values). The others have no uses. | | p5 P3 `rand.at(seed, key)` / love `hash`/`hashFloat` / zig `hash01` | **Defer** | | 0 | No port draws random values in `draw`. | | love P4 / p5 P4 / zig §2 `sk.noise` (perlin2/3, fbm2/3 with options, hash01, `Classic`, a GLSL twin) | **Shrink to one function**: `sk.noise(seed: u32, x: f32, y: f32, z: f32) f32`, 0..1, 4 octaves, falloff 0.5. That is p5's `noise()` with the seed passed in. | ~50 | helpers_b noise 54 and helpers_a noise 82 (if noise_walker accepts values that differ from Processing) | The ports use 1D and 2D noise. Call `noise(seed, t, 0, 0)` rather than adding 3 overloads. **Defer** the octave options (no `noiseDetail` in the ports). **Defer** `Classic`: bit-exact Processing noise matters only for pixel comparison with the book, which nobody does, and if wanted it stays in noc's helpers. **Replace** the GLSL twin with the same Zig function compiled for SPIR-V (shaders README): no second source. | | p5 build options `.noise = .perlin\|.processing\|.p5`, `.hue = .turns\|.degrees` | **Reject** | | | These are Processing modes moved to build time: `sk.noise(x, y)` would mean different things in different apps. The owner's rule ("knobs in build.zig") is about host and runtime resources, not about making call semantics depend on a mode. research-zig agrees. `.antialias` and `.canvas`: defer until the fringe exists. | ### State containers and migration | Proposal | Verdict | +lib | −noc | Why | | --- | --- | --- | --- | --- | | zig §1 / coordinator: element-wise array migration (repeated leaves, prefix copy, indexed paths) | **Accept.** It is a correctness fix and removes few lines. | ~230 | 0 directly. Indexed paths remove test-only fields (shared with the lane split above). | 5 ports keep arrays of structs in State (`movers[9]`, `movers[20]`, `vehicles`, `boids`, `emitters`). Today, adding a field to `Mover` while the sketch runs wipes the array. That breaks hot reload's main promise. It also protects the game's tracker songs. | | zig §1 `sk.List(T, cap)` + `Ring` / love `Bounded` / p5 `List` | **Accept a minimal `List`, only together with migration. Defer `Ring`.** | ~30 | helpers_b List 24 | The coordinator is right that `[N]T + len` would be enough, except for one hazard: after a capacity shrink, `len` exceeds `N` (verified by research-zig). Only a type can clamp that. Use std's names and contract: `appendBounded` (`error{OutOfMemory}!void`, as on `ArrayList`), `orderedRemove`, `swapRemove`, `slice`/`constSlice`. Not `append`, which in std takes an allocator. `Ring` serves only the deferred Layer. | | zig §6 game lifts (`Press`, `Images(Id)`, `Cue`) | **Out of scope** | | 0 | The evidence comes from the game, not from NoC. Judge them in a game pass. | ### Build options | Proposal | Verdict | Why | | --- | --- | --- | | zig: host constants (snapshot slots, header size, store reserve, web queue, gpu cache/staging, `use_llvm`) as `sketchbook.init(b, .{...})` | **Defer, except `use_llvm` if the lane split is not done** | No port hit these limits. porter-b's "100 KB × 8 snapshots" is 800 KB, nothing. The owner's rule says *where* these go when they are needed, not that they are needed now. | | (missed by the researchers; from porter-a #7) a build option for the optimize mode of e2e and script runs, default ReleaseSafe | **Accept** (~5 lines in build.zig) | This is evidence-backed: 0.5 s per frame for a debug pixel loop looked like a hang, and flocking takes 76 ms in Debug against 8.7 ms in ReleaseFast. It is exactly the kind of knob the owner wants in `build.zig`. | --- ## 2. Before and after The "after" code uses the iteration-1 surface in §4, with the host fix (one `update` per tick) in place. ### flocking: update and draw Before (flocking.zig:96-147: 41 code lines, plus helpers_b's Canvas, Pen, List and gray): ```zig pub const State = struct { rng: b.Rng = .init(11), boids: b.List(Boid, max_boids) = .{}, /// Button state as of the event being handled, for mouseDragged. pressed: bool = false, }; pub const Session = struct { canvas: b.Canvas = .{}, draw_ns: f32 = 0, }; pub fn update(s: *State, in: *const sk.Input) void { for (in.events) |e| switch (e.kind) { .mouse_down => s.pressed = true, .mouse_up, .cancel => s.pressed = false, .mouse_move => if (s.pressed) { _ = s.boids.append(.init(&s.rng, e.x, e.y)); }, .tick => { const boids = s.boids.slice(); for (boids) |*boid| boid.run(boids); }, else => {}, }; } pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { const started = f.host.clock(); paint(s, ss, f) catch |err| f.host.print("draw: {t}", .{err}); // ... 4 lines of timing ... } fn paint(s: *const State, ss: *Session, f: *sk.Frame) !void { var pen = ss.canvas.begin(f); pen.fill = b.gray(127, 255); pen.stroke = b.gray(0, 255); pen.weight = 1; for (s.boids.view()) |boid| { pen.transform = b.Affine.translate(boid.position[0], boid.position[1]).mul(.rotate(b.heading(boid.velocity))); try pen.polygon(&.{ .{ Boid.r * 2, 0 }, .{ -Boid.r * 2, -Boid.r }, .{ -Boid.r * 2, Boid.r } }); } try ss.canvas.show(f, &pen, width, height, b.gray(255, 255)); } ``` After (21 lines, no Session, no helpers). `update` and the State use L2 (`sk.Clock`, `sk.List`). `draw` **drops to L1 and L0**: it builds triangles itself and emits two `shape` commands for every boid, rather than 2000. That is the explicit replacement for the batching I rejected. It is valid because the boids are opaque. One visible difference: all fills come before all strokes, so a boid's outline can show over a neighbour's body. Use `sk.draw.polygon(f, &boid_shape, pen)` per boid when that matters. ```zig pub const State = struct { rng: std.Random.Xoshiro256 = .init(11), boids: sk.List(Boid, max_boids) = .{}, clock: sk.Clock = .{ .hz = 60 }, }; pub fn update(s: *State, in: *const sk.Input) void { // One update is one frame now, so `in.buttons` is as of this frame. if (in.buttons & 1 != 0) for (in.events) |e| if (e.kind == .mouse_move) { s.boids.appendBounded(.init(s.rng.random(), e.x, e.y)) catch {}; }; for (0..s.clock.steps(in)) |_| { const boids = s.boids.slice(); for (boids) |*boid| boid.run(boids); } } const boid_shape = [_]sk.math.Vec{ .{ Boid.r * 2, 0 }, .{ -Boid.r * 2, -Boid.r }, .{ -Boid.r * 2, Boid.r } }; pub fn draw(s: *const State, f: *sk.Frame) void { f.clear(0xffffff); // today's Frame method var body: std.ArrayList([2]f32) = .empty; // L1: the triangles are ours var edge: std.ArrayList([2]f32) = .empty; for (s.boids.constSlice()) |boid| { const xf: sk.math.Affine = .place(boid.position, sk.math.angle(boid.velocity)); sk.draw.fillPolygon(&body, f.scratch, &boid_shape, xf) catch return; sk.draw.strokePolygon(&edge, f.scratch, &boid_shape, 1, xf) catch return; } f.emit(.{ .shape = .{ .color = .gray(127), .triangles = body.items } }); // L0 f.emit(.{ .shape = .{ .color = .black, .triangles = edge.items } }); } ``` The same `body.items` could instead be uploaded with `f.upload` and drawn by the sketch's own GPU pass, with no change to the rest of the file. `Boid`'s methods only rename `b.` to `sk.math.`. The vector helpers move code out of the helper file; they do not shorten the steering code, and I am not pretending they do. The timing code goes too; that job belongs to the host. ### angular_forces: draw, plus update Before (angular_forces.zig:71-98: 24 lines, plus `showGpu` and the `vector` import): ```zig pub fn update(s: *State, in: *const sk.Input) void { for (0..h.steps60(&s.clock, in)) |_| { for (&s.movers) |*m| { m.applyForce(attractor.attract(m.*)); m.update(); } s.frame_count += 1; } } pub const Session = struct { layer: ?vector.Renderer(.gpu) = null, }; pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { f.clear(0xffffff); var pen: hb.Pen = .{ .b = .init(f.scratch), .fill = hb.gray(175, 200), .stroke = hb.gray(0, 255), .weight = 2 }; pen.circle(attractor.position[0], attractor.position[1], attractor.mass * 2) catch {}; pen.fill = hb.gray(127, 127); for (s.movers) |m| { pen.transform = Affine.translate(m.position[0], m.position[1]).mul(.rotate(m.angle)); pen.circle(0, 0, m.radius * 2) catch {}; pen.line(0, 0, m.radius, 0) catch {}; } pen.transform = .identity; h.showGpu(&ss.layer, f, &pen, width, height); } ``` After (15 lines): ```zig pub fn update(s: *State, in: *const sk.Input) void { for (0..s.clock.steps(in)) |_| for (&s.movers) |*m| { m.applyForce(attractor.attract(m.*)); m.update(); }; } const attractor_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(175).alpha(200), .stroke = .black, .width = 2 }; const mover_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 }; pub fn draw(s: *const State, f: *sk.Frame) void { f.clear(0xffffff); sk.draw.circle(f, attractor.position, attractor.mass, attractor_pen); for (s.movers) |m| { const pen = mover_pen.transformed(.place(m.position, m.angle)); // push; translate; rotate sk.draw.circle(f, .{ 0, 0 }, m.radius, pen); sk.draw.line(f, .{ 0, 0 }, .{ m.radius, 0 }, pen); } // pop: `pen` goes out of scope; nothing to reset } ``` `frame_count` (and its comment saying "expect cannot look into arrays") goes: `clock.count` and `movers[3].position[0]` replace it. porter-a's "forgetting the reset leaks the transform" bug can no longer be written. ### accel_to_mouse: whole file (this one also fixes a bug) Before: 35 lines. On seek it **diverges**: `in.mouse_x` is read inside `steps60`, but it holds the end-of-batch position for every replayed step. After: 21 lines, and correct, because `update` sees one frame's events. ```zig const sk = @import("sketch"); const vec = sk.math; pub const name = "accel_to_mouse"; pub const width = 640; pub const height = 360; pub const State = struct { position: vec.Vec = .{ width / 2, height / 2 }, velocity: vec.Vec = .{ 0, 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; } } 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); } ``` ### fluid_resistance: draw, mixing today's Frame methods with L2 Before (fluid_resistance.zig:91-101, plus `showGpu`): the liquid is an `f.fill`, and the movers go through a separate GPU vector layer that is drawn *over* everything. A translucent mover can therefore never sit under a later `f.fill` without a second layer (porter-a's "two pipelines that do not compose"). After: the two layers are interleaved in one command list, in painter's order. ```zig const mover_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 }; pub fn draw(s: *const State, f: *sk.Frame) void { f.clear(0xffffff); // L0-level Frame method, unchanged f.fill(.{ .x = liquid.x, .y = liquid.y, .w = liquid.w, .h = liquid.h }, 0xdcdcdc); // unchanged for (s.movers) |m| sk.draw.circle(f, m.position, m.radius, mover_pen); // new layer f.print(8, 8, 1, 0x000000, "resets {d}", .{s.resets}); // and back to a Frame method } ``` The script's `await caught true` becomes `await position[0] ~560 24`. That needs the lane split and the `~` tolerance, so `caught` goes. ### Estimate across the batch | | ports | helpers | | --- | --- | --- | | now | 778 | 296 | | after iteration 1 | about 640 | about 25 (Trail), plus 82 if noise_walker keeps Processing-exact noise | --- ## 3. Things nobody proposed 1. **Fix the host batching, not the sketches** (§1, time). Every researcher designed a Clock against the batch and none asked why the batch exists. One `update` per tick removes the Clock bug, the `in.dt`/`in.now` bug, porter-b's #2, and the pointer state copied into State in pendulum and flocking. 2. **Two colour types.** `abi.Color` is u8 RGBA and `vector.Drawing.Color` is `[4]f32`. helpers_b's `gray()` exists only to convert, and porter-a's alpha is `a / 255` in one and a u8 in the other. Frame shapes take `abi.Color`, so drawing has one colour type. `vector` keeps its own for gradients. 3. **Tolerance in script `expect`/`await`** (`expect position[0] ~250 0.5`). porter-a asked for it and no researcher picked it up. It is ~15 lines in the script runner. Together with the lane split and indexed paths, it removes every test-only State field in the batch: 8 fields, which are State shaped by the test harness. 4. **A build option for the e2e/script optimize mode** (§1, build options). It is evidence-backed, and it is the owner's preferred kind of knob. 5. **Typed parameters for new APIs.** The ports all use one point type, so the new `sk.draw` functions should take `sk.math.Vec` and `?Color`, not `anytype`: decl literals, ZLS completion and readable errors depend on it. The anytype duck typing in `shape.zig` can stay for existing calls. Do not spread it. 6. **Radius, not diameter** (p5 had it). It removes `* 2` at 7 circle sites and `/ 2` in the helper. 7. **Bugs found by the porters, not API** (and so outside this critique): concurrent e2e runs share a state path and segfault in `SDL_DestroyRenderer` on the error path (Host.zig:118). `LeakedSdlMemory` is flaky under parallel Vulkan devices. The first tick has dt = 0, so a 600-frame script makes 599 steps: document it, do not "fix" it. 8. **Unfixable, document once:** `draw` sees State after `update`, so a Processing sketch that draws, then moves, is one step ahead (the_wave's `- 0.02`, the pendulum drag). No API can fix this without storing the drawn state. --- ## 4. Iteration 1: the whole surface, by layer, ordered by lines saved per line added New host primitives: **one** (`Command.shape`), plus one change to host behaviour (one `update` per tick) that adds no API. Everything else is sketch-library code with no state of its own. Today's `Frame` gets no new methods. ```zig // ---- L0: abi (new command; everything else unchanged) ---- pub const Command = union(enum) { ..., shape: struct { color: Color, triangles: []const [2]f32 } }; pub fn gray(v: u8) Color; // abi.Color decl, for `.gray(127)` // ---- sk.math: the `geom` module shared with `vector` (pure) ---- pub const Vec = @Vector(2, f32); // already in geom: length, normalize, dot, cross, perp, splat, mix pub fn scale(v: Vec, k: f32) Vec; pub fn distance(a: Vec, b: Vec) f32; pub fn withLength(v: Vec, len: f32) Vec; // setMag pub fn clampLength(v: Vec, max: f32) Vec; // limit pub fn angle(v: Vec) f32; // heading (not for shaders: atan2) pub fn unit(radians: f32) Vec; // fromAngle pub const Affine = struct { ..., pub fn place(at: Vec, radians: f32) Affine }; // translate · rotate pub fn noise(seed: u32, x: f32, y: f32, z: f32) f32; // 0..1, 4 octaves, hash lattice // random(lo, hi) / map(): std.math.lerp(lo, hi, r.float(f32)), with std.Random.Xoshiro256 in State // ---- sk.draw L1: triangles as data (caller owns the list and the allocator) ---- pub const Error = std.mem.Allocator.Error; pub fn fillCircle(out: *std.ArrayList([2]f32), gpa: Allocator, center: Vec, radius: f32, xf: Affine) Error!void; pub fn strokeCircle(out: *std.ArrayList([2]f32), gpa: Allocator, center: Vec, radius: f32, width: f32, xf: Affine) Error!void; pub fn fillPolygon(out: *std.ArrayList([2]f32), gpa: Allocator, points: []const Vec, xf: Affine) Error!void; // convex pub fn strokePolygon(out: *std.ArrayList([2]f32), gpa: Allocator, points: []const Vec, width: f32, xf: Affine) Error!void; pub fn strokeLine(out: *std.ArrayList([2]f32), gpa: Allocator, a: Vec, b: Vec, width: f32, xf: Affine) Error!void; // round caps // ---- sk.draw L2: L1 into f.scratch, then f.emit(.shape); logs and drops on OOM like Frame.emit ---- pub const Pen = struct { fill: ?Color = null, stroke: ?Color = null, width: f32 = 1, xf: Affine = .identity, pub fn transformed(p: Pen, m: Affine) Pen; // push = copy }; pub fn circle(f: *Frame, center: Vec, radius: f32, pen: Pen) void; pub fn line(f: *Frame, a: Vec, b: Vec, pen: Pen) void; pub fn polygon(f: *Frame, points: []const Vec, pen: Pen) void; // ---- root: plain State data over Input ---- pub const Clock = struct { // L1 form: loop in.events, handle .tick hz: f32 = 60, owed: f64 = 0, count: u64 = 0, pub fn steps(c: *Clock, in: *const Input) u32; // at most 8 per call }; pub fn List(comptime T: type, comptime capacity: u32) type; // buffer, len; slice, constSlice, // appendBounded, orderedRemove, swapRemove (clamped) ``` | # | Item | Layer | +lib | −noc | Ratio | | --- | --- | --- | --- | --- | --- | | 1 | `std.math.lerp` in docs; no `range`, no `map` | std | 0 | 8 | ∞ | | 2 | `sk.math.noise` | math | 50 | 136 | 2.7 | | 3 | `sk.math` vec functions + `Affine.place` (geom module shared with `vector`) | math | 25 | 25, plus 11 `[0], [1]` pairs | 1.0+ | | 4 | `Color.gray` | L0 decl | 3 | 4 | 1.3 | | 5 | `sk.Clock` | root | 15 | 18 | 1.2 | | 6 | **Host:** one `update` per tick (`in.dt`/`in.now` from that frame) | host behaviour, no API | 12 | ~10, plus 2 replay bugs | 0.8 + bugs | | 7 | `Command.shape` + `sk.draw` L1 + L2 + `Pen` | L0 / L1 / L2 | 210 | 163 | 0.8, plus speed, ordering with `f.fill`/`f.text`, web without WebGPU, and an exposed triangle list for GPU passes | | 8 | `@Vector` lane leaves + script `~tol` | host tooling | 30 | ~16 | 0.5 | | 9 | `sk.List` | root | 30 | 24 | 0.8 | | 10 | Element-wise array migration | host | 230 | 0 | correctness | | 11 | Native MSAA `clear = null` load fix; e2e optimize option in build.zig | host / build | 10 | 0 | parity | Out of iteration 1: the AA fringe (pull it forward only if aliased native shapes are unacceptable), `Ring`, `Layer`, `target`, `jumped`, blend modes, colour spaces, image affines, textures, instances, `Path`, arc, ellipse, join/cap options, batching inside the Frame or host (L1 lets a sketch batch itself), `Rng`, keyed randomness, `Classic` noise, fbm options, `Vec2`, input sugar, fallible `draw`, and the host-constant build options.