# Friction log, batch A (porter-a) Six Nature of Code examples, ported from Processing to sketchbook. LOC is counted as non-blank, non-comment lines. "+helpers" is the share of `src/helpers_a.zig` (128 code lines) and `src/helpers_b.zig` that the port uses. All six run in `zig build e2e`, and I checked every screenshot by eye. | sketch | original | port | uses | |---|---|---|---| | random_walk | 33 | 45 | steps60 | | noise_walker | 30 | 44 | steps60, noise, map, Trail, B's Pen | | bouncing_ball | 21 | 36 | steps60, showGpu, B's Pen | | accel_to_mouse | 36 | 35 | steps60, showGpu, B's Pen + Vec ops | | fluid_resistance | 96 | 86 | steps60, showGpu, B's Pen + Vec ops + Rng | | angular_forces | 82 | 83 | steps60, showGpu, B's Pen + Vec ops + Rng | Once the helpers exist, the ports are about as long as the originals, and the physics code is shorter: `s.velocity += s.acceleration` beats `velocity.add(acceleration)`. The cost is the roughly 250 helper lines across A and B, which every new sketchbook user would have to write again. Without them, each port would need its own ~40-line circle/stroke pipeline. --- ## 1. random_walk (Example 0.1) **Processing:** `background(255)` once in `setup()`, then `point(x, y)` each frame on a canvas that is never cleared. **Friction** - **No persistent canvas.** The host's 2D canvas is redrawn from scratch every frame, and leaving out `f.clear` gives undefined swapchain contents. The trail has to live somewhere: - Keeping it in Session does not survive a replay or a seek, because Session is not snapshotted. - Recomputing it in draw would mean replaying the PRNG from the start every frame. - What I did: keep the trail in **State** as a bitset, and paint it into an image every frame. ```zig trail: std.StaticBitSet(width * height) = .empty, // 28.8 KB of State ... const rgba = f.scratch.alloc([4]u8, width * height) catch return; @memset(rgba, .{ 255, 255, 255, 255 }); var it = s.trail.iterator(.{}); while (it.next()) |i| rgba[i] = .{ 0, 0, 0, 255 }; f.pixels(ss.image, width, height, std.mem.sliceAsBytes(rgba), .{}); f.image(ss.image, .{ .x = 0, .y = 0, .w = width, .h = height }, .{}); ``` This is correct under replay, but only because a walk's history happens to fit in a bitmap. Every frame uploads a 920 KB texture to show one new pixel. - **No `point()`, and no 1-px primitive except `f.fill` with a 1x1 rect.** With no persistent canvas to draw on, it would not have helped anyway. - **Debug build performance.** My first draw loop was `for (rgba, 0..) |*px, i| px.* = if (s.trail.isSet(i)) ...`, over 230 k pixels. It took about **0.5 s per frame** in the default Debug build, so the 600-frame e2e looked hung. I lost about 20 minutes to this, partly because `ptrace` attach is blocked here, so the only way to get a stack was to start the program under gdb and interrupt it. Processing users never meet this kind of trap. - **The PRNG must live in State.** `rng: std.Random.DefaultPrng = .init(1)` was easy, and calling `s.rng.random().uintLessThan(u8, 4)` worked. My first try, `uintLessThan(u2, 4)`, does not compile, because 4 does not fit in a `u2`. Small, but it is the kind of thing `floor(random(4))` never asks you. - **The 60 Hz draw loop is my job.** `update` runs once per display frame, which may be 144 Hz. Processing runs 60 steps a second. I wrote `steps60`, which accumulates the tick dt in a `clock: f64` State field. Every port needs it: ```zig for (0..h.steps60(&s.clock, in)) |_| { ... one Processing frame ... } ``` **Gotcha:** the first frame's tick has dt = 0, so 600 script frames make 599 steps. The script expects `steps 599`. **Wished-for API:** `f.layer(id, .{ .keep = true })` or `Frame.target(img)`: an offscreen image that the frame draws into and that keeps its contents, plus `Input.jumped` (true after a load, seek or reload) to signal "repaint from state". Also `sk.FixedStep(60)`, a plain-data clock in State with `steps(in)`. ## 2. noise_walker (Example 0.6) **Processing:** `noise(t)`, `map()`, and `circle()` with fill and stroke, with no `background()` in draw, so the circles pile up into a trail. **Friction** - **No `noise()`.** I ported Processing's `PApplet.noise` exactly: 4 octaves, 0.5 falloff, and the half-degree cos table. I fill its 4096-entry table at **comptime** with `java.util.Random`'s LCG, so the values are what `noiseSeed(0)` would give: ```zig const perlin: [4096]f32 = blk: { @setEvalBranchQuota(100_000); ... seed = (seed *% 0x5DEECE66D +% 0xB) & mask; ... }; ``` That is 60 lines. B's `Noise` fills the table with Xoshiro at `Noise.init(seed)`, and the State keeps only the seed, so the 16 KB table is rebuilt each time it is needed. B also drops z. **Mine is better for fidelity and cost:** the values match Processing and nothing is rebuilt. **B's is better if the seed must change at runtime** (`noiseSeed(n)`). A library `sk.noise` should be a pure function of `(seed, x, y, z)`, using hashing rather than a table, so it is stateless and can have a GLSL twin. - **No `map()`.** It is a one-liner, but every port writes it. - **Circles with stroke need the vector module.** That means adding a `vector` import in build.zig (porter-b and I both made the same edit at the same moment), a `Drawing.Builder`, a `Renderer` kept in Session, and an error union on every builder call inside a `void` draw. B's `Pen` covers this. - **The persistent canvas, again, and worse this time.** The trail cannot be rebuilt from a bitmap. It could be recomputed from the frame number, but only by replaying the whole walk. I wrote `Trail`, a CPU renderer in Session that is never cleared, plus a **shadow walker** in Session that draw steps forward to paint only the new circles: ```zig const r = ss.trail.begin(f, width, height, s.frame_count, hb.gray(255, 255)) orelse return; if (ss.trail.drawn == 0) ss.shadow = .{}; for (ss.trail.drawn..s.frame_count) |_| { ss.shadow.step(); pen.circle(ss.shadow.x, ss.shadow.y, 48) catch break; } ss.trail.end(f, &pen, s.frame_count); ``` So draw re-runs the simulation, and `frame_count < drawn` is my guess at whether the user went back in time. It would miss a jump to a different timeline at a higher frame count, such as a snapshot taken from another run. The script checks the rewind path with `console save 1` … `console load 1`, and the screenshot shows the repainted 2 s trail. - **A GPU trail is impossible.** `vector.Renderer(.gpu)` renders 8x MSAA, and `host/gpu.zig:213` always clears a multisampled pass (`clear = null` is ignored), so the trail has to be CPU: 920 KB uploaded per frame. No documentation mentions this. I found it by reading the host. **Wished-for API:** `sk.noise(x, y, z)` / `sk.Noise{ .seed }`, and `sk.map`. Retained layers (see 1) that the host keeps on the GPU, with `Input.jumped` to signal a repaint. ## 3. bouncing_ball (Example 1.2) **Processing:** 21 lines: `background`, `PVector.add`, and `circle` with stroke. **Friction** - **The circle costs a whole renderer.** For one stroked circle the port needs a `Session { layer: ?vector.Renderer(.gpu) = null }`, a Pen built in scratch memory, and `showGpu`. Inside `showGpu`: lazy init with `f.session` and `f.host`, `finish`, `begin` with a transparent clear, `draw`, `present`. That is 10 lines of plumbing written once, but a first sketch has to discover all of it: ```zig f.clear(0xffffff); var pen: hb.Pen = .{ .b = .init(f.scratch), .fill = hb.gray(127, 255), .stroke = hb.gray(0, 255), .weight = 2 }; pen.circle(s.position[0], s.position[1], 48) catch {}; h.showGpu(&ss.layer, f, &pen, width, height); ``` - **Two pipelines that do not compose.** `f.clear` and `f.fill` are host primitives, while the vector layer is an image drawn over them. The draw order is clear (commands run in order), but layering a translucent vector shape *under* a host rect would take a second layer. - **`@Vector(2, f32)` vs inspection.** I chose `@Vector` for PVector math (`s.position += s.velocity`). But `expect position ...` shows `<16 bytes>`, because layout leaves keep vectors and arrays whole. So I added a `bounces: u32` field just for the script. With a `struct { x, y }`, `expect` would see the fields, but the arithmetic would have to be written out field by field. **You cannot have both.** - **Indexing is worse than PVector names.** `s.position[0]` reads worse than `position.x`. A vector type with named lanes does not exist in Zig. (Swizzles aside, `v.x` is not available on `@Vector`.) - **Easier than Processing:** the state is two vectors in a struct. Hot reload keeps the ball where it was while I edit the bounce code, and replay works for free. **Wished-for API:** `sk.Vec2` = `@Vector(2, f32)` with free functions (`mag`, `setMag`, `limit`, `heading`, `fromAngle`, `dist`), and the layout/console learning to show `@Vector` and small arrays element-wise (`position[0]`, or `position` → `{250, 220}`). Then `f.circle(center, d, .{ .fill, .stroke, .weight })` as a host command (Canvas2D has `arc`, and SDL can take `RenderGeometry` triangles), with no Session renderer. ## 4. accel_to_mouse (Example 1.10) **Processing:** `mouseX`/`mouseY`, plus `normalize`, `mult`, `limit` and `add`. **Friction** - **The mouse is fine:** `in.mouse_x`/`in.mouse_y` are there in update and replay correctly. Before any event the mouse is at (0, 0), as in Processing. - **No scalar broadcast:** `dir * 0.2` does not compile, so I wrote `hb.scale(dir, 0.2)` or `dir * @as(Vec, @splat(0.2))`. Every force formula pays this tax. - **The script needs a scalar to wait on.** I wanted `await` on "the mover reached the mouse". There is no tolerance compare for floats, and vectors are opaque, so I added `caught: bool` (distance < 24) to State: ``` move 560 300 await caught true ``` It works well and reads nicely, but it is test-only state. - **Easier than Processing:** the script drives the mouse (`move 560 300`) and the run is deterministic, so a "does it chase the mouse" test was 7 lines. Processing has nothing like it. **Wished-for API:** `expect position.x ~250 0.5` (a tolerance), or `await dist(position, mouse) < 24` (expressions are probably too much). At least make `@Vector` lanes addressable. ## 5. fluid_resistance (Example 2.5) **Processing:** an array of `Mover` objects, a `Liquid`, `random(0.5, 3)`, `mousePressed()`, `fill(127, 127)` (alpha), `rect` with `noStroke`. **Friction** - **Random initial state needs `init`.** `setup()` calls `reset()`, which calls `random()`. In sketchbook, defaults are comptime, so the random reset goes into `pub fn init(s: *State)`. That part is easy and documented. But the PRNG seed is fixed (`.init(25)`), unlike Processing's time seed. Seeding from `host.clock()` in `init` should be safe, since init is not replayed, but nothing says so explicitly. - **`mousePressed()` is an event scan:** ```zig for (in.events) |e| if (e.kind == .mouse_down) { reset(s); s.resets += 1; }; ``` This is fine, if lower level. `in.pressed(key)` exists for keys, but there is no `in.clicked(button)` for the mouse. - **The update/draw split changes the order of operations slightly.** Processing calls `show()` *before* `checkEdges()`, so a mover is drawn below the floor for the one frame it bounces. In the port, update clamps first, so draw sees the clamped position. This difference cannot be seen, but a faithful port could not reproduce Processing's order without storing a "drawn position". - **Arrays of structs cannot be inspected.** `movers[0].position` is not a field path, so `resets` and `frame_count` exist only for the script. - **Alpha works:** `hb.gray(127, 127)` → `Drawing.Color` with a = 0.5, blended correctly over both white and the 220-gray liquid in the screenshot. - **The liquid is one `f.fill` rect** under the vector layer. That is the nicest line in the port. - **Easier than Processing:** a fixed-size `[9]Mover` is ordinary Zig, and `@splat(.{})` makes the default. Methods on `Mover` and `Liquid` read like the Java. **Wished-for API:** `in.clicked(.left)` / `in.mouseDown(.left)` next to `pressed`. Console and `expect` paths into arrays (`movers.3.position`). A documented "init may use `host.clock()` to seed". ## 6. angular_forces (Example 3.2) **Processing:** `push(); translate(); rotate(); circle(); line(); pop();`, `constrain`, and `fill(175, 200)` for the attractor. **Friction** - **Transforms exist, but only as an explicit affine on each shape.** B's Pen has a `transform` field, and the vector geom `Affine` composes: ```zig 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; // pop() ``` This is honest and more explicit than a matrix stack, and I like it. The only snag is that forgetting the reset leaks the transform into later shapes, which is exactly the bug a `pop()` prevents. A by-value Pen (copy = push) would fix that. - **Processing's style state leaks across frames.** `strokeWeight(2)` set in `Mover.show()` still applies when the attractor is drawn on the next frame, so the attractor really has weight 2 from frame 2 on. Being explicit avoids this kind of hidden global. The port uses weight 2 throughout. - **`catch {}` on every shape.** The Pen's `circle`/`line` return `!void` because the builder allocates, but draw returns `void`. Fourteen `catch` arms across this batch (8 in the ports, 6 in helpers_a). - **Positions spread over the whole canvas need `init` and the PRNG**, as in 5. **`constrain` is `std.math.clamp`:** fine. **Wished-for API:** `sk.Pen` as a value with `translate`/`rotate` methods that return a new Pen, so that pop is just a copy going out of scope. Shape calls that do not fail, recording into scratch and dropping on OOM with one log line, like `Frame.emit` already does. --- ## Helpers: A vs B, and which design wins I adopted B's Vec ops, `Rng`, `random`, `gray` and `Pen`, and deleted my own copies: my `Style` struct passed to each call, `setMag`/`limit`/`range`. What is left in `helpers_a.zig`: | piece | A | B | better | |---|---|---|---| | Pen style | mine: `Style` value passed per call | stateful `Pen` fields like Processing | **B's** for porting speed. A by-value `Style` composes better for push/pop. A library Pen should be a value (copy = push). | | noise | comptime `java.util.Random` table, matches `noiseSeed(0)`, 3D | runtime Xoshiro table from a seed, 2D | **A's** for fidelity and zero runtime cost. B's allows a runtime seed. The library should hash, not use a table. | | fixed step | `steps60(&clock, in)` | none (one step per update) | **A's**: B's dynamics run 2.4x fast on a 144 Hz display. | | canvas | `showGpu` (GPU, 8x MSAA, transparent, redrawn) + `Trail` (CPU, accumulating, repaints on seek back) | `Canvas` (CPU, clears to bg each frame) | Different jobs: GPU for redraw-every-frame, CPU only where pixels must persist. | | List(T, cap) | not needed (fixed arrays) | yes | B's. None of my examples grows a list. | --- ## Ranked summary: the gaps that cost the most 1. **There is no shape drawing in the Frame API.** It has no circle, line, stroke, alpha shapes or transforms. Five of the six ports need circles with strokes, and the only route is the vector module: a build.zig import, a Renderer in Session, a Drawing per frame, and a layer image. That is about 40 lines of helpers, plus 14 `catch` arms across the batch. *Wish:* `f.circle/line/rect/polygon(…, .{ .fill, .stroke, .weight, .transform })` as host commands, or an `sk.Pen` value backed by one `Command.shape`. 2. **Nothing persists across frames, and nothing tells the sketch it jumped in time.** Accumulating sketches (random walk, noise walker, and anything with trails) need a bitmap in State or a shadow simulation in Session plus a "steps drawn" heuristic to repaint. Multisampled GPU passes always clear, so trails are forced onto the CPU, at a 920 KB upload per frame. *Wish:* retained offscreen targets that draw commands can render into, `Input.jumped`, and a documented recipe for repainting from State. 3. **Scripts and the console cannot see `@Vector` fields or array elements, and compare floats as exact text.** Every port grew a scalar just for its test (`frame_count`, `bounces`, `caught`, `resets`). The idiomatic math type (`@Vector`) is the one that inspection cannot see. *Wish:* lanes and elements as field paths (`position[0]`, `movers[3].mass`), plus `expect field ~value tol`. 4. **There is no fixed-rate step.** Per-tick physics runs at the display's rate, and the first tick has dt = 0. *Wish:* `sk.FixedStep` / `sk.Clock(60)` as plain data in State. 5. **There is no noise, map or random-in-range.** `noise` is about 60 lines to do right. *Wish:* a pure `sk.noise(seed, x, y, z)` with a GLSL twin, plus `sk.map` and an `sk.Rng` with `float(lo, hi)`. 6. **PVector ergonomics.** There is no scalar broadcast (`v * 0.2` fails), `v[0]` instead of `v.x`, and no `mag`/`setMag`/`limit`/`heading` outside `vector.geom`, which has `length`/`normalize` but is a different module. *Wish:* `sk.vec` with those free functions, re-exported from `sketch`. 7. **Debug builds make per-pixel draw loops unusably slow** (0.5 s/frame for 230 k `isSet` calls), and a slow script looks exactly like a hang. *Wish:* build e2e and run steps with `-Doptimize=ReleaseSafe` by default for sketches, as a build.zig option. A frame-time warning from the headless host would also help, such as "frame 20 took 480 ms". 8. **Concurrent e2e runs collide.** The per-sketch script state path in .zig-cache is fixed, so two `zig build e2e` runs at once fail with "store is open in another process", and then **segfault** in `SDL_DestroyRenderer` on the error path (`host/Host.zig:118` errdefer). The crash is a bug in its own right. *Wish:* a unique state path per run, and an errdefer order that does not cancel a GPU command buffer from a half-made renderer. 9. **`zig build e2e` is flaky under load.** Each full run, 2–8 random sketches (A's and B's alike) fail with `LeakedSdlMemory` from SDL's Vulkan allocations at exit (`host/root.zig:74`), never with a failed `expect`. The same scripts run one after another: 0 failures in 16 runs. This is a leak check that depends on parallelism, and it makes "e2e must pass" unreliable. *Wish:* the SDL leak check opt-in for scripts, or the underlying Vulkan teardown fixed. 10. **Small papercuts:** - There is no `in.clicked(button)`. - It is undocumented whether `init` may read `host.clock()` for a seed. - `uintLessThan(u2, 4)` does not compile. - The `vector` module needs a build.zig import, which every sketch that draws anything round will need. **Easier than Processing** - Deterministic replay, and scripts that drive the mouse and check state. A 7-line "chases the mouse" test, and a test that rewinds to a snapshot and checks the trail repaint, are impossible to write in Processing. - Hot reload keeps the simulation running while I edit forces. - Fixed arrays of plain structs with methods read like the Java and need no `new`. - `@Vector` arithmetic (`velocity += acceleration`) is shorter than `PVector.add`. - The vector renderer's quality: anti-aliased 8x MSAA, correct alpha, and round caps. The output looks like Processing's.