diff options
Diffstat (limited to 'README.md')
| -rw-r--r-- | README.md | 237 |
1 files changed, 145 insertions, 92 deletions
@@ -45,24 +45,23 @@ An app is an ordinary module. Every declaration is optional: | Declaration | Meaning | | --- | --- | | `name`, `width`, `height` | Window title and initial canvas | -| `State` | Saved to a file, kept in every session's keyframes and marks, replayed: what `update` changes. No pointers and no host handles (compile errors). | +| `State` | The one thing a sketch keeps: what `update` changes, saved in one file with its history, replayed. No pointers, no host handles, and at most 32 MiB, half of a save (compile errors). | | `Session` | This process: survives reloads, never saved. Caches, image and buffer handles, playback cursors. | -| `Store` | On disk, at the same address in every run: survives reloads and restarts. Big data that is not replayed (a recording, a document). May point into itself; no host handles. | | `init(state, host)` | Seed brand-new state, after the declared defaults | | `setup(session, init) !void` | Initialize resources once per fresh Session, including startup with restored State | | `update(state, input)` | **Deterministic**: the host replays recorded input through it | -| `draw(state, session, store, frame)` | Pictures and sound, as commands; may change Session and Store | -| `command(state, session, store, console, line) !bool` | Console lines the host does not know | +| `draw(state, session, frame)` | Pictures and sound, as commands; may change Session | +| `command(state, session, console, line) !bool` | Console lines the host does not know | | `commands` | Console completions | Functions take the parameters they name, matched by type and in any order: -`draw(s: *const State, f: *sk.Frame)` and `draw(s: *const State, store: -*Store, ss: *Session, f: *sk.Frame)` both work. `update` can only ask for +`draw(s: *const State, f: *sk.Frame)` and `draw(f: *sk.Frame, ss: *Session, +s: *const State)` both work. `update` can only ask for `State` and `Input`; asking for more is a compile error, since a replay could not reproduce it. -`setup` receives `*sk.Init` with `host`, `session`, and `store` allocators; -it may also request Session, Store, or Host directly. It gets no State, Input, +`setup` receives `*sk.Init` with `host` and the `session` allocator; it may +also request Session or Host directly. It gets no State, Input, or Frame. Load assets and create/upload GPU buffers there, then use those resources in `draw`. `try init.host.writeBuffer(buffer, offset, bytes)` submits a copy immediately; the source bytes may be released when it returns. WebGPU @@ -83,14 +82,11 @@ Memory comes by lifetime, one allocator each: | --- | --- | --- | | `f.scratch` | this frame | all at once, after the frame is drawn | | `f.session` | this process | one allocation at a time; the rest when Session's layout changes, along with the images and buffers the session made | -| `f.store` | on disk, `<state>.store` | one allocation at a time; `--fresh` empties it | -A Store layout change migrates field by field like State: unchanged fields, -pointers included, keep their values, since the store never moves. -`command` gets the session and store allocators on its `Console`. +`command` gets the session allocator on its `Console`. -`update` sees only State, so when a key should do something to Session or -Store, State carries a request: `seek: sk.Request(f32)`, sent with +`update` sees only State, so when a key should do something to Session, +State carries a request: `seek: sk.Request(f32)`, sent with `s.seek.send(0.5)`. Session keeps an `sk.Handled`, and `draw` runs `if (ss.seek.take(s.seek)) |to| ...` once per request. A fresh Session counts earlier requests as handled, so nothing re-fires after a restart. @@ -126,13 +122,13 @@ Session (a trail in an offscreen image) is stale then; repaint it from State. `draw` gets a `Frame`: `clear`, `fill`, `shape`, `shapeColors`, `image`, -`imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `gain`, `audio`, `microphone`, `pixels`, `gpu`, +`imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `gain`, `audio`, `audioBuffer`, `microphone`, `pixels`, `gpu`, `compute`, `upload`, `download`, `openFile`, `run`, `quit`, plus the three allocators and `f.host` (`loadImage`, `decodeImage`, `newImage`, `newBuffer`, `loadSound`, -`decodeSound`, `newSound`, `samples`, `readFile`, `env`, `log`, `textSize`). Commands may be built +`decodeSound`, `newSound`, `samples`, `readFile`, `appendFile`, `writeFile`, `env`, `log`, `textSize`). Commands may be built from locals: the methods copy what they keep (text, GPU descriptions, uniforms) into scratch. Bulk data (vertices, samples, pixels, uploads) is -not copied and must outlive the frame: scratch, session or store memory. +not copied and must outlive the frame: scratch or session memory. `f.text(x, y, scale, bytes, color)` draws one line from its top left corner; scale 1 is a 13 px monospace face (8 px a character on a 16 px @@ -169,13 +165,24 @@ move. The web host ignores `raster`. dialog; the answer comes back as the console line `open <path>`, so it reaches the sketch's `command` like anything typed there. `f.run(line)` does the same with any line, after the frame: `draw` cannot write State, -so this is how it tells State something only it learns (how many takes a -Store holds, say). +so this is how it tells State something only it learns (which of its +files are already written, say). + +`f.host.appendFile(name, bytes)` appends to a file of the sketch's own, +`<stem>.<name>` beside its save `<stem>.xitdb` (in `.sketchbook/` under +`zig build run`), creating it, and returns its path for `readFile` ("" when nothing +was written, and always on the web). Only `draw` and `command` can call it, +and a write is not replayed, like sound. `readFile` maps a file once, so +what is appended afterwards is not in what it returned. +`f.host.writeFile(name, bytes)` does the same to a new, empty file of that +name. micscope starts each take's `take-<id>.f32` so, and appends to it as +it records. `f.download(buffer, .{ .size = n, .key = k })` reads a GPU buffer back without stalling: the bytes arrive in a later frame's `in.downloads`, a frame or two behind. For measurements a shader made (a pitch, a level), -not for pixels. +not for pixels; sound a shader made goes to the speakers with +`f.audioBuffer` (see sound, below), which does not wait a frame. 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 @@ -368,9 +375,8 @@ 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 kept in keyframes, replayed and migrated, so -it holds what `update` changes, at a size fixed in its type. Store is not -kept in keyframes or replayed, so what is in it does not follow a seek. Three -cases, by who needs the data: +it holds what `update` changes, at a size fixed in its type, 32 MiB at most. +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). @@ -384,7 +390,8 @@ cases, by who needs the data: 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. + document): a `List` in State, or, bigger than a save, files of the + sketch's own (`appendFile`), named from State, as micscope's takes are. The timeline then needs nothing more: a seek changes the key like an update does (`examples/noc`: `koch`, `lsystem`, `quadtree`). @@ -450,8 +457,31 @@ topping its queue up to 2048 samples (about 43 ms) ahead of the device, so what `draw` declares is heard up to that much later. `f.audio(key, samples, .{})` streams PCM, and `input.stream(key)` reports -what the host has queued and played: the sketch chooses how far ahead it -keeps a stream. `f.microphone()` keeps the default recording device open +what the host has queued and played, and its `underruns` (pushes that found +it empty though the frame before had pushed to it: each a gap). The sketch +chooses how far ahead it keeps a stream; `input.lead` is how far the host +would: the slowest of the last 64 frames' worth of samples (a stream is fed +once a frame), plus the device's pull (what it takes from a stream at once, +1024 samples by SDL's default), plus half a pull for each recent underrun. +A sketch that makes its sound as it goes pushes `in.lead -| +in.stream(key).queued` a frame, and a change it makes is heard after what +is queued ahead of it, about a pull: 19 to 27 ms after `draw` on this +machine at 60 Hz. `SDL_AUDIO_DEVICE_SAMPLE_FRAMES=256` in the environment +asks SDL for 5 ms pulls instead, and a change leaves in about 6.5 ms (on +PipeWire every client then runs at that size). `f.audioBuffer(key, buffer, .{ .count += n })` streams `n` samples a compute shader wrote (f32 from `.offset` +bytes): the host reads them back within the frame, waiting for the GPU's +work so far (about 0.2 ms), and queues them. A GPU synth is then: + +```zig +const n: u32 = @min(f.in.lead -| f.in.stream(1).queued, max_block); +if (n > 0) { + f.compute(.{ .kernel = synth, .readwrite = &.{ss.block}, .uniforms = ..., .groups = .{ (n + 63) / 64, 1, 1 } }); + f.audioBuffer(1, ss.block, .{ .count = n }); +} +``` + +(`examples/spheres` is one.) `f.microphone()` keeps the default recording device open while declared, and the next frame's `input.microphone` holds what it heard (to `draw` only: it is a device, not an event, so it does not replay). `host.samples(audio)` gives a loaded sound's samples, mono at @@ -810,37 +840,40 @@ a talk with a slider, a loop, a choice, two slides and `beside`. and shaders), and a save that touches several files may build more than once. The cache grows with each start of the watch (65 MB for a game), not with edits. -- **State file.** `<name>.state` holds the live State, shared via - `MAP_SHARED`, so the file is up to date as it changes. Its header carries - the reflected layout, so a layout change migrates it field by field, with - enums matched by tag 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, and the snapshot slots of files from before sessions become - marks `1` to `7` in a run that records; 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. - Keyframes, marks and replays do not cover it (only `draw` and `command` - change it). -- **Where files go.** `zig build run`, `probe` and `export` keep a sketch's - files in `.sketchbook/`: `<name>.state`, `<name>.state.store` and - `<name>.xitdb`. The host makes the directory with a `.gitignore` of `*`, - so neither git nor jj takes in a database that grows (the jj snapshot a - build makes would commit one while it is under a megabyte), and moves in, - once, the state and store an older build kept in the project's root; - when both exist, nothing moves and the host says which is used. Without - `--state`, a run keeps them in `$XDG_DATA_HOME/<name>/` - (`~/.local/share/<name>/` without it), which is where a shipped game's - go; a script or an export uses `sketch.state` in the working directory. -- **Sessions.** Every run of a build that records is a session in - `<name>.xitdb`, one xitdb database per sketch beside its state file: an - append-only log of the events live `update` was fed, in whole frames, and +- **The save.** A sketch keeps one thing, State, in one file, its save: + `<name>.xitdb`, an xitdb database. Live State is process memory; the save + holds the present, its newest keyframe and the frames logged after it, + which a run restores and replays through `update` (played by another + build, the keyframe alone, and the run says how many frames it left), + so a run starts where the last stopped; and the history before it + (Sessions, below). `--fresh` starts from defaults and leaves the save as + it is. A keyframe is State in 4 KiB pages and writes only the pages that + changed since the keyframe before it, an all-zero page nothing: about 5 + KB a keyframe for drat-meout's 20 KiB State, 10 KB for a 4 MiB State + edited once a minute. Each stretch carries the reflected layout, so a + keyframe from an older layout migrates field by field, with enums + matched by tag name, and so does live State at a reload. 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. A state + file from before (`<name>.state` beside the save, any of its formats) is + imported into a new save once: its State the present, its snapshot slots + marks `1` to `7`; the file is left as it was and not read again, and one + that is not a state file is said and left. +- **Where files go.** `zig build run` and `export` keep a sketch's files in + `.sketchbook/`: `<name>.xitdb` and the `<name>.<file>` it appends to. The + host makes the directory with a `.gitignore` of `*`, so neither git nor + jj takes in a save that grows (the jj snapshot a build makes would commit + one while it is under a megabyte), and moves in, once, the `<name>.state` + an older build kept in the project's root; when both exist, nothing moves + and the host says which is used. Without `--state`, a run keeps them in + `$XDG_DATA_HOME/<name>/` (`~/.local/share/<name>/` without it), which is + where a shipped game's go; a script or an export uses `sketch.xitdb` in + the working directory. `--state x.xitdb` and `--state x.state` both name + the save `x.xitdb`. +- **Sessions.** Every run is a session in the save: an append-only log of the events live `update` was fed, in whole frames, and keyframes, the State at the start, every minute while it changes, at every jump (`load`, `set`, `reset`, a seek, a sketch command), before and after a reload, at every mark and at exit. Each stretch of a session @@ -848,34 +881,53 @@ a talk with a slider, a loop, a choice, two slides and `beside`. was built from: the repository's revision (`jj:<commit> <change>`, else `git:<sha>`, `+dirty` with uncommitted changes, read once per `zig build`), Zig's version, the backend and the mode. Nothing in it is ever - overwritten; marks and clips are names pointing into it. + overwritten, only dropped, oldest first, at the cap (below); marks and + clips are names pointing into it. - `App.Options.record` decides who records, at build time: null, the - default, means Debug builds. A playtest build of a release opts in with - one line, `.record = b.option(bool, "record", "collect sessions in a - release build")`. A script from `--fresh` state records in memory (time - travel works, nothing touches the disk; it stops at 256 MiB, ten hours or - more of play, keeping what it has), a script without `--fresh` to the - file, an export nothing. A build that does not record has no marks or - clips, and the console says so. The console's status line ends with - `rec file`, `rec memory` or `rec off`, and `sessions` says where. + `App.Options.record` decides how much of it the save keeps, at build + time: null, the default, means Debug builds keep all of it, up to the + cap below. A build that does not record keeps the present and the marks + (and clips) only: at every keyframe it drops the frames and keyframes + before it, and at exit it compacts the file, so while it runs the disk + holds at most the last minute of input, and after, none. A playtest + build of a release opts in with one line, `.record = b.option(bool, + "record", "collect sessions in a release build")`. A script from + `--fresh` state records in memory (time travel works, nothing touches + the disk; it stops at 256 MiB, ten hours or more of play, keeping what + it has), a script without `--fresh` to the file, an export nothing, and + an export has no marks or clips, as the console says. The console's + status line ends with `rec file`, `rec memory` or `rec off`, and + `sessions` says where. A commit is a second of play (of event time, so a script commits on the same frames every run), and is made at once for a reload, a mark, a clip's start or end, an export and exit; only a mark and exit are synced to disk. A crash (a panic, `kill -9`) loses the frames not yet committed, - under a second: the session lists as `(crashed)`, and a clip it left - open ends where the session does. A power loss loses what the kernel had + under a second (15 of 255 in the kill test): the next run starts from the + last committed frame's State, the session lists as `(crashed)`, and a + clip it left open ends where the session does. A power loss loses what the kernel had not written back (30 s past the last sync, by default); the torn end is mended at the next start, the file opened at its last whole commit, and a file still unreadable is renamed to `<path>.broken.<seconds>`, never - deleted, and a new one begun. Live State is in the state file either way. + deleted, and a new one begun. + + A minute of drat-meout's play was 268 KB with the pointer moving every + frame (16 MB an hour), 164 KB idle (86 KB of ticks, the rest keyframes, + then whole States; a keyframe is about 5 KB now). - A minute of drat-meout's play is 268 KB with the pointer moving every - frame (16 MB an hour), 164 KB idle (86 KB of ticks, the rest keyframes). - Every commit leaves the nodes it copied behind, about a kilobyte; a clean - exit compacts the file once it is past twice what its sessions hold plus - 64 MiB. Nothing is compressed or forgotten yet. + **The cap.** A save is at most 64 MiB, and State half of that, so + history has room. A commit that leaves the file past it drops history + oldest first, keyframes' pages and the frames logged with them, and + compacts the file to three quarters of the cap: a hitch of about 170 ms + for a 48 MiB file in a Debug build, once every 16 MiB of history. The + present is never dropped, nor the keyframe of the newest mark of each + name, nor the newest clip of each name and its frames. What was dropped + says so when it is asked for (`load #K`, `play session N`). A mark of a + new name needs room for a whole State: when marks fill the save it is + refused, saying how to make room, by saving over a mark's name (the + older one then goes with history) or starting another save (`--state`). + Every commit leaves the nodes it copied behind, about a kilobyte, which + the compaction removes too. Playtests: `export-session [S] FILE` writes session S (this run's when none is given) with its marks and clips to a database of its own, for a @@ -942,9 +994,9 @@ a talk with a slider, a loop, a choice, two slides and `beside`. `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. 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; its sessions are in memory. + scripted `--fresh` run saves nothing: its sessions are in memory, and the + files it appends to are `<stem>.<pid>.<name>`, removed at exit, so two + builds running the same script at once do not share them. - **Export.** `--export DIR` plays the sketch headless, from fresh state, and saves every frame as `DIR/000000.png`, `000001.png`, ...; `--export -` writes them to stdout instead, as raw RGBA: @@ -964,8 +1016,8 @@ a talk with a slider, a loop, a choice, two slides and `beside`. hides its controls, plays through and quits. `--size WxH` is the room for the canvas (`in.window_width`/`height`, and the first canvas): a sketch that sets its canvas to the room exports at any size. An export - keeps state files of its own and removes them, so it can run beside a - player. `--export` plays no script. In a release build on an RTX 3050, + saves nothing, and the files it appends to are its own, removed at exit, + so it can run beside a player. `--export` plays no script. In a release build on an RTX 3050, an `anim` scene takes 6 ms a frame as raw RGBA and 21 as PNG at 1920x1080, 19 and 73 at 3840x2160; with ffmpeg encoding x264 from the pipe, 11 and 41. The PNG encoder is the slow part: pipe, when the frames @@ -1028,7 +1080,7 @@ pub fn build(b: *std.Build) void { } ``` -`addSteps` installs the executable and adds `run`, `lib`, `probe`, +`addSteps` installs the executable and adds `run`, `lib`, `export` (`zig build export -- frames --size 1920x1080`: what follows `--` is `--export`'s directory, or `-`, then its options), `e2e` and `test`, and with `.web = .{}` also `web` (the page into `zig-out/web`) and @@ -1047,7 +1099,6 @@ and returns plain `std.Build` objects: | `app.addRun(lib, .{})` | the generic host running the installed library, its files in `.sketchbook/` | | `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.addExport(exe, .{ .fps, .frames, .size })` | a headless export of the executable's frames, as PNGs in `.frames`, a directory of the cache | -| `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) | @@ -1057,8 +1108,8 @@ 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. -`sb.app(.{ ..., .record = true })` records sessions in every mode (see -The host); null, the default, records in Debug builds only. +`sb.app(.{ ..., .record = true })` keeps history in every mode (see +The host); null, the default, in Debug builds only. **Hot reload, checked.** `addReloadCheck` builds the app's library as written, and again from a copy of its sources with textual edits applied, @@ -1135,7 +1186,7 @@ and Pillow (the renderers against resvg), `ffmpeg` if there is one, and, for `zig build test-web`, Chrome. `sb.modules` (`abi`, `sketch`, `host`, `vector`, `scope`, `anim`), -`sb.host_exe` and `sb.probe_exe` are exposed for anything else. +`sb.host_exe` is exposed for anything else. Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`. ## Known limits @@ -1144,23 +1195,25 @@ Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`. `f.openFile` answers with a line of any length. - Every upload, compute dispatch and GPU pass is its own command buffer and submit. Fine at a handful per frame; batch them per frame if that grows. -- The store is not crash-safe: a crash in the middle of an allocation can - 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) and no +- A keyframe hashes all of State to find the pages that changed: about 70 + ms for 32 MiB in a Debug build, 3 ms in ReleaseFast, once a minute while + State changes and at every jump. +- On the web: nothing persists and no sessions are recorded, and multisampling is 4× at most. Every voice is silent there, whatever its sound (loaded, decoded or made with `newSound`), and so are groups' gains; `decodeSound` gives `.none`, and `loadSound` knows only sounds the page decoded (opened or dropped - files). What does sound: streams (`f.audio`) and the microphone, mixed - on the main thread (a ScriptProcessor), so a busy page can crackle. + files). What does sound: streams (`f.audio`, `f.audioBuffer`) and the + microphone, mixed on the main thread (a ScriptProcessor), so a busy page + can crackle. A GPU buffer streamed there arrives a frame or two later + (WebGPU reads back only asynchronously), counted as queued meanwhile, and + `in.lead` is a fixed 100 ms. The reusable GPU executor and the pardes integration are described in [docs/pardes-rendering.md](docs/pardes-rendering.md), including the remaining |
