diff options
Diffstat (limited to 'build.zig')
| -rw-r--r-- | build.zig | 586 |
1 files changed, 530 insertions, 56 deletions
@@ -6,7 +6,7 @@ //! //! const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); //! const app = sb.app(.{ .name = "demo", .root_source_file = b.path("src/main.zig") }); -//! _ = app.addSteps(.{}); // run, lib, probe, e2e, test, install; +//! _ = app.addSteps(.{}); // run, lib, e2e, test, install; //! // web and serve with `.web = .{}` //! //! or pick the pieces: `app.addLibrary()`, `app.addExecutable()`, @@ -30,22 +30,96 @@ pub fn build(b: *Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + const gltf = gltfModule(b, target, optimize); + b.modules.put(b.graph.arena, "gltf", gltf) catch @panic("OOM"); + const gltf_generator = b.addExecutable(.{ + .name = "gltf-bindings", + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/gltf_bindings.zig"), + .target = b.graph.host, + .optimize = .ReleaseSafe, + .imports = &.{.{ .name = "gltf", .module = gltfModule(b, b.graph.host, .ReleaseSafe) }}, + }), + }); + b.installArtifact(gltf_generator); + // Target-free: they compile for whatever imports them, native or wasm. - const abi = b.addModule("abi", .{ .root_source_file = b.path("src/abi.zig") }); + // abi.hash's layout half, computed by a program once per change of the + // abi sources rather than at comptime in every sketch's compile. + const abi_hash = b.addRunArtifact(b.addExecutable(.{ .name = "abi-hash", .root_module = b.createModule(.{ + .root_source_file = b.path("src/abi_hash.zig"), + .target = b.graph.host, + .imports = &.{.{ .name = "abi", .module = b.createModule(.{ .root_source_file = b.path("src/abi.zig") }) }}, + }) })).captureStdOut(.{ .basename = "abi_hash.zig" }); + const abi = b.addModule("abi", .{ .root_source_file = b.path("src/abi.zig"), .imports = &.{.{ .name = "abi_hash", .module = b.createModule(.{ .root_source_file = abi_hash }) }} }); + const gpu = b.addModule("gpu", .{ .root_source_file = b.path("src/gpu/Executor.zig"), .imports = &.{.{ .name = "abi", .module = abi }} }); + _ = b.addModule("gpu_scene", .{ .root_source_file = b.path("src/gpu/scene.zig"), .imports = &.{.{ .name = "abi", .module = abi }} }); + // The cell renderer's shaders (src/gpu/Cells.zig): embedders compile the + // GLSL or embed these committed copies; this refreshes the copies. + const update_shaders = b.addUpdateSourceFiles(); + for ([_][]const u8{ "ui.vert", "ui.frag", "decor.frag", "overlay.vert", "overlay.frag", "image.vert", "image.frag" }) |name| { + const glslc = b.addSystemCommand(&.{ "glslc", b.fmt("-fshader-stage={s}", .{if (std.mem.endsWith(u8, name, ".vert")) "vertex" else "fragment"}) }); + glslc.addFileArg(b.path(b.fmt("src/gpu/shaders/{s}.glsl", .{name}))); + glslc.addArg("-o"); + update_shaders.addCopyFileToSource(glslc.addOutputFileArg(b.fmt("{s}.spv", .{name})), b.fmt("src/gpu/shaders/prebuilt/{s}.spv", .{name})); + } + b.step("shaders", "refresh the committed src/gpu/shaders/prebuilt/*.spv (glslc)").dependOn(&update_shaders.step); + // Embedders provide their existing SDL translation and device. + if (b.option(bool, "gpu-only", "export GPU modules without building the sketch host") orelse false) return; + // The host's session database (src/host/Sessions.zig). + const xitdb = (b.lazyDependency("xitdb", .{}) orelse return).module("xitdb"); // 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 tracy_path = b.option([]const u8, "tracy", "Enable Tracy with this source checkout (disabled by default)") orelse ""; + const profile_options = b.addOptions(); + profile_options.addOption(bool, "enabled", tracy_path.len > 0); + const tracy = b.addModule("tracy", .{ .root_source_file = b.path("src/tracy.zig"), .target = target, .optimize = optimize }); + tracy.addOptions("profile_options", profile_options); + if (tracy_path.len > 0) { + tracy.addIncludePath(.{ .cwd_relative = tracy_path }); + tracy.addCSourceFile(.{ + .file = .{ .cwd_relative = b.pathJoin(&.{ tracy_path, "public", "TracyClient.cpp" }) }, + .flags = &.{ "-DTRACY_ENABLE=1", "-DTRACY_NO_SAMPLING", "-DTRACY_NO_CALLSTACK", "-DTRACY_NO_SYSTEM_TRACING", "-DTRACY_NO_CRASH_HANDLER", "-DTRACY_NO_CODE_TRANSFER", "-fno-sanitize=undefined" }, + }); + tracy.link_libcpp = true; + } + const text_library = textLibrary(b, target, optimize) orelse return; + b.installArtifact(text_library); const c = cModule(b, target, optimize); + c.linkLibrary(text_library); + gpu.addImport("c", c); + // pardes's glyph atlas, for its ink boxes (the host packs its own: see + // src/host/Glyphs.zig) and the comparison with pardes's raster. + const font_atlas = b.createModule(.{ .root_source_file = b.path("src/font/Atlas.zig"), .imports = &.{.{ .name = "c", .module = c }} }); // 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 cloud9 = b.dependency("cloud9", .{ .target = target, .optimize = optimize }).module("cloud9"); + b.modules.put(b.graph.arena, "cloud9", cloud9) catch @panic("OOM"); const host = b.addModule("host", .{ .root_source_file = b.path("src/host/root.zig"), .target = target, - .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c } }, + .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 }, .{ .name = "xitdb", .module = xitdb }, .{ .name = "font_atlas", .module = font_atlas } }, }); + b.step("test-control", "Test 9P control validation and screenshot snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "control writes", "9P reads", "the State as files", "a row of scalars" } })).step); + b.step("test-timing", "Test display clock, recorded ticks, timing history and console controls").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "timing", "presentation", "frames are whole", "a tick's dt" } })).step); + + b.step("test-sessions", "Test the sessions database: frames, keyframes, marks, clips").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"session"} })).step); + b.step("test-presentation", "Test presentation feedback, pacing and trace snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"presentation"} })).step); + // The sketch library's tests measure text with no host: through + // sketchbook-text, as an app's tests do (`App.addTest`). + const sketch_tests = b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }); + sketch_tests.linkLibrary(text_library); + const test_audio = b.step("test-audio", "Test sound: the voice mixer (reconciling, limiting, pitch, groups), sfxr, and a made sound played as a voice"); + test_audio.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "voice", "mixer" } })).step); + test_audio.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = sketch_tests, .filters = &.{"sfxr"} })).step); + + const setup_tests = b.step("test-setup", "Test resource setup lifecycle and arguments"); + for ([_]*Build.Module{ host, sketch_tests }) |module| setup_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"setup"} })).step); + const host_exe = b.addExecutable(.{ .name = "sketchbook", .root_module = b.createModule(.{ @@ -57,18 +131,7 @@ pub fn build(b: *Build) void { }); b.installArtifact(host_exe); - const probe = b.addExecutable(.{ - .name = "sketchbook-probe", - .root_module = b.createModule(.{ - .root_source_file = b.path("src/host/probe.zig"), - .target = target, - .optimize = optimize, - .imports = &.{.{ .name = "abi", .module = abi }}, - }), - }); - b.installArtifact(probe); - - var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined, .scope = undefined, .anim = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .script_optimize = optimize, .shared = .create(b) }; + var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf, .cloud9 = cloud9 }, .host_exe = host_exe, .text = text_library, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .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. @@ -116,16 +179,34 @@ pub fn build(b: *Build) void { sb.modules.scope = b.addModule("scope", .{ .root_source_file = b.path("src/scope/root.zig"), .imports = scope_imports }); const test_step = b.step("test", "Run unit tests and the reload end-to-end test"); + const gltf_tests = b.addRunArtifact(b.addTest(.{ .root_module = gltf })); + b.step("test-gltf", "Test glTF parsing, extras and accessor reads").dependOn(&gltf_tests.step); + test_step.dependOn(&gltf_tests.step); + const scene_tests = b.createModule(.{ .root_source_file = b.path("src/gpu/scene.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "abi", .module = abi }} }); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = scene_tests })).step); for ([_]*Build.Module{ b.createModule(.{ .root_source_file = b.path("src/vector/root.zig"), .target = target, .optimize = optimize, .imports = vector_imports }), b.createModule(.{ .root_source_file = b.path("src/scope/root.zig"), .target = target, .optimize = optimize, .imports = scope_imports }), - b.createModule(.{ .root_source_file = b.path("src/anim/root.zig"), .target = target, .optimize = optimize, .imports = anim_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 = sketch_imports }), + sketch_tests, 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 } } }), + b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 }, .{ .name = "xitdb", .module = xitdb }, .{ .name = "font_atlas", .module = font_atlas } } }), }) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); + // A State bigger than a save holds is a compile error that says what to do. + const too_big = b.addObject(.{ .name = "too_big", .root_module = b.createModule(.{ + .root_source_file = b.addWriteFiles().add("too_big.zig", "comptime { _ = @import(\"abi\").layout.of(struct { bytes: [(32 << 20) + 1]u8 }, .state); }"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "abi", .module = abi }}, + }) }); + too_big.expect_errors = .{ .contains = "may be 32 MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session." }; + test_step.dependOn(&too_big.step); + // The anim module alone: its unit tests, and below the player's scenes. + const test_anim = b.step("test-anim", "Test the anim module: its unit tests and the player on its test scenes"); + const anim_tests = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/anim/root.zig"), .target = target, .optimize = optimize, .imports = anim_imports }) })); + test_anim.dependOn(&anim_tests.step); + test_step.dependOn(&anim_tests.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 @@ -150,6 +231,9 @@ pub fn build(b: *Build) void { // 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(); + // v2 through the linker `-fincremental` uses, whose 0.17.1 libraries + // glibc loads only after the host's fixup (`withoutVersym`). + v2.use_new_linker = true; // 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`). @@ -184,18 +268,91 @@ pub fn build(b: *Build) void { test_web.dependOn(&render_web.step); // `Host.textSize` against the text drawn (test/text.zig). const text = sb.app(.{ .name = "text", .root_source_file = b.path("test/text.zig") }); - test_step.dependOn(&text.addScript(text.addExecutable(), b.path("test/text.script"), .{}).step); + const text_script = text.addScript(text.addExecutable(), b.path("test/text.script"), .{}); + test_step.dependOn(&text_script.step); + const test_text = b.step("test-text", "Test text: layout (sketch.text), the atlas's rasters against pardes's, and test/text.script"); + test_text.dependOn(&text_script.step); + test_text.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = sketch_tests, .filters = &.{"paragraph"} })).step); + test_text.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"pardes's"} })).step); + // A sound the sketch made, as a voice: once per serial, not again on a + // replay (test/voices.zig). + const voices = sb.app(.{ .name = "voices", .root_source_file = b.path("test/voices.zig") }); + const voices_script = voices.addScript(voices.addExecutable(), b.path("test/voices.script"), .{}); + test_step.dependOn(&voices_script.step); + test_audio.dependOn(&voices_script.step); + // And for the web, whose host keeps made sounds but plays no voices. + test_audio.dependOn(&voices.addWeb(.{}).wasm.step); // The anim module's player on its test scenes: a live one with a // custom object between vector objects, and a compiled one, which is // also exported, at half size. const live = sb.addScene(.{ .root_source_file = b.path("test/scene_live.zig") }); - test_step.dependOn(&live.app.addScript(live.app.addExecutable(), b.path("test/scene_live.script"), .{}).step); + const live_script = live.app.addScript(live.app.addExecutable(), b.path("test/scene_live.script"), .{}); + test_step.dependOn(&live_script.step); + test_anim.dependOn(&live_script.step); const compiled = sb.addScene(.{ .root_source_file = b.path("test/scene_compiled.zig") }); const compiled_exe = compiled.app.addExecutable(); const compiled_script = compiled.app.addScript(compiled_exe, b.path("test/scene_compiled.script"), .{}); compiled_script.addArg("--define"); compiled_script.addPrefixedDirectoryArg("frames=", compiled.app.addExport(compiled_exe, .{ .fps = 30, .size = .{ 640, 360 }, .frames = 200 }).frames); test_step.dependOn(&compiled_script.step); + test_anim.dependOn(&compiled_script.step); + // Holes through morphs, on the GPU and the CPU renderer (vector/morph.zig). + const morph = sb.addScene(.{ .root_source_file = b.path("test/scene_morph.zig") }); + const morph_script = morph.app.addScript(morph.app.addExecutable(), b.path("test/scene_morph.script"), .{}); + test_step.dependOn(&morph_script.step); + test_anim.dependOn(&morph_script.step); + + // The talk example: a Deck in a sketch's own State, stepped, sent back, + // jumped by slides, clicked on its slider, reloaded mid-wait with its + // first step retimed, and exported twice, with the same frames. + const talk_imports: []const Build.Module.Import = &.{ .{ .name = "anim", .module = sb.modules.anim }, .{ .name = "sketch", .module = sketch } }; + const talk = sb.app(.{ .name = "talk", .root_source_file = b.path("examples/talk.zig"), .imports = &.{ + .{ .name = "anim", .module = sb.modules.anim }, + .{ .name = "typst", .module = sb.addTypst(b.createModule(.{ .root_source_file = b.path("examples/talk.zig"), .imports = talk_imports })) }, + } }); + const talk_check = talk.addReloadCheck(.{ .script = b.path("test/talk.script"), .edits = &.{.{ + .file = "examples/talk.zig", + .old = "s.play(.{ title.write(), law.write() }, .{});", + .new = "s.play(.{ title.write(), law.write() }, .{ .seconds = 3 });", + }} }); + const talk_exe = talk.addExecutable(); + for ([_][]const u8{ "a", "b" }, [_]u64{ 400, 401 }) |define, frames| { + talk_check.run.addArg("--define"); + talk_check.run.addPrefixedDirectoryArg(b.fmt("{s}=", .{define}), talk.addExport(talk_exe, .{ .fps = 30, .frames = frames, .size = .{ 640, 360 } }).frames); + } + // `zig build talk` shows it in a window; `zig build talk-lib --watch` + // beside it reloads every edit in place. + const talk_lib = talk.addLibrary(); + b.step("talk", "Run the talk example in a window (reload edits with `zig build talk-lib --watch`)").dependOn(&talk.addRun(talk_lib, .{ .state = ".zig-cache/talk.state" }).step); + b.step("talk-lib", "Build and install the talk example's hot-reloadable library").dependOn(&b.addInstallArtifact(talk_lib, .{}).step); + const test_talk = b.step("test-talk", "Play the talk example: steps, back, slides, its slider, a reload mid-wait and its export"); + test_talk.dependOn(&talk_check.run.step); + test_step.dependOn(&talk_check.run.step); + + // The manual example: Figure 2-1 of the Intel SDM, Vol. 2, page 31, as + // a talk in the stock player. The PDF is named, never committed: built + // without it, the scene says so, and only its script needs it. + const pdf = b.option([]const u8, "manual", "The Intel SDM Vol. 2 PDF for the manual example (default ~/01-resources/intel-devref-ii.pdf)") orelse + b.pathJoin(&.{ b.graph.environ_map.get("HOME") orelse "/", "01-resources", "intel-devref-ii.pdf" }); + const have_pdf = if (std.Io.Dir.cwd().access(b.graph.io, pdf, .{})) true else |_| false; + const manual_options = b.addOptions(); + manual_options.addOption(?[]const u8, "pdf", if (have_pdf) pdf else null); + const manual = sb.addScene(.{ .root_source_file = b.path("examples/manual.zig"), .imports = &.{.{ .name = "manual", .module = manual_options.createModule() }} }); + const manual_lib = manual.app.addLibrary(); + b.step("manual", "Play the manual example in a window (-Dmanual=PDF, Vol. 2 of the Intel SDM)").dependOn(&manual.app.addRun(manual_lib, .{ .state = ".zig-cache/manual.state" }).step); + test_step.dependOn(&manual_lib.step); + if (have_pdf) { + const manual_exe = manual.app.addExecutable(); + const manual_script = manual.app.addScript(manual_exe, b.path("test/manual.script"), .{}); + // Two exports (a frame cap apiece, so the build runs both), which + // quit at the end, as the stock player does. + for ([_][]const u8{ "a", "b" }, [_]u64{ 1000, 1001 }) |define, cap| { + manual_script.addArg("--define"); + manual_script.addPrefixedDirectoryArg(b.fmt("{s}=", .{define}), manual.app.addExport(manual_exe, .{ .fps = 10, .frames = cap, .size = .{ 640, 360 } }).frames); + } + b.step("test-manual", "Play the manual example through its steps, and export it twice").dependOn(&manual_script.step); + test_step.dependOn(&manual_script.step); + } // Both vector renderers against resvg, through the host (tools/svgdiff.py). const svgview = sb.app(.{ .name = "svgview", .root_source_file = b.path("test/svgview.zig"), .imports = &.{.{ .name = "vector", .module = sb.modules.vector }} }); @@ -221,11 +378,13 @@ pub fn build(b: *Build) void { .{ .name = "anim", .module = sb.modules.anim }, .{ .name = "scene", .module = compiled.module }, .{ .name = "typst", .module = compiled.typst }, + .{ .name = "manual", .module = manual.module }, + .{ .name = "manual_typst", .module = manual.typst }, }, }), })); bench.has_side_effects = true; - b.step("bench", "Time parsing and drawing a scene's Typst (release mode, must be under 1ms)").dependOn(&bench.step); + b.step("bench", "Time parsing and drawing scenes' Typst (release mode: a simple object under 1ms, a PDF page in its own budget)").dependOn(&bench.step); // After the tests above, not beside them: it measures time. for (test_step.dependencies.items) |step| bench.step.dependOn(step); test_step.dependOn(&bench.step); @@ -251,7 +410,8 @@ pub fn build(b: *Build) void { exported.addArg("--define"); exported.addPrefixedDirectoryArg("b=", export_b.addExport(export_b.addExecutable(), export_options).frames); test_step.dependOn(&exported.step); - const raw = b.addSystemCommand(&.{ "sh", "-c", + const raw = b.addSystemCommand(&.{ + "sh", "-c", \\set -e \\test "$("$0" --state "$1" --export - --fps 30 --size 320x180 | wc -c)" = $((320 * 180 * 4 * 8)) \\command -v ffmpeg >/dev/null && command -v ffprobe >/dev/null || exit 0 @@ -275,6 +435,184 @@ pub fn build(b: *Build) void { reload.expectExitCode(0); test_step.dependOn(&reload.step); + // A session survives a kill -9 up to its last commit: 255 frames + // played, four commits of 60 made, the fifth lost with the process; the + // next run starts from frame 240's State, replayed. Its sketch records + // in every mode, so the test does in release builds too; and a sketch + // that does not record keeps its present all the same. + const recorded = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = true }).addLibrary(); + const unrecorded = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = false }).addLibrary(); + const killed = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\db="${3%.state}.xitdb" + \\for lib in "$4" "$5"; do + \\rm -f "$db" + \\if "$0" --headless --script "$1" --state "$3" "$lib"; then echo "killed run exited"; exit 1; else test $? = 137; fi + \\"$0" --headless --script "$2" --state "$3" "$lib" + \\test "$(stat -c %s "$db")" -lt 1048576 + \\rm -f "$db" + \\done + }); + killed.setName("a session survives kill -9"); + killed.addArtifactArg(host_exe); + killed.addFileArg(b.path("test/kill.script")); + killed.addFileArg(b.path("test/killed.script")); + _ = killed.addOutputFileArg("kill.state"); + killed.addArtifactArg(recorded); + killed.addArtifactArg(unrecorded); + killed.has_side_effects = true; + killed.expectExitCode(0); + test_step.dependOn(&killed.step); + b.step("test-kill", "A session survives kill -9 up to its last commit").dependOn(&killed.step); + + // A past session plays again: from its start to a mark, the same + // State leaf by leaf; two seconds in, from the keyframe before; and, + // built from edited code, it diverges before the mark, says so once, + // and goes on from the mark's State. + const edited = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = true }).addReloadCheck(.{ + .script = b.path("test/past_diverged.script"), + .edits = &.{.{ .file = "test/replay.zig", .old = "@splat(0.01)", .new = "@splat(0.02)" }}, + }); + const past = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\db="${4%.state}.xitdb" + \\rm -f "$4" "$db" + \\"$0" --headless --script "$1" --state "$4" "$5" + \\"$0" --headless --script "$2" --state "$4" "$5" + \\"$0" --headless --script "$3" --state "$4" "$6" + \\test "$(stat -c %s "$db")" -lt 1048576 + \\rm -f "$4" "$db" + }); + past.setName("past sessions replay"); + past.addArtifactArg(host_exe); + past.addFileArg(b.path("test/past.script")); + past.addFileArg(b.path("test/past_replay.script")); + past.addFileArg(b.path("test/past_diverged.script")); + _ = past.addOutputFileArg("past.state"); + past.addArtifactArg(recorded); + past.addArtifactArg(edited.edited); + past.has_side_effects = true; + past.expectExitCode(0); + test_step.dependOn(&past.step); + b.step("test-past", "Replay past sessions, to a time and across a code change").dependOn(&past.step); + + // A session exported from one database and imported into another plays + // there to the same State: at the mark it carries, and two seconds in. + const moved = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\mkdir -p "$4"; d=$(realpath "$4"); rm -f "$d"/* + \\"$0" --headless --script "$1" --state "$d/a.state" "$5" + \\"$0" --headless --script "$2" --state "$d/a.state" --define file="$d/one.xitdb" "$5" + \\"$0" --headless --script "$3" --state "$d/z.state" --define file="$d/one.xitdb" "$5" + \\test "$(stat -c %s "$d/one.xitdb")" -lt 1048576 + \\rm -f "$d"/* + }); + moved.setName("export and import a session"); + moved.addArtifactArg(host_exe); + moved.addFileArg(b.path("test/past.script")); + moved.addFileArg(b.path("test/session_export.script")); + moved.addFileArg(b.path("test/session_import.script")); + _ = moved.addOutputDirectoryArg("import"); + moved.addArtifactArg(recorded); + moved.has_side_effects = true; + moved.expectExitCode(0); + test_step.dependOn(&moved.step); + b.step("test-import", "Export a session from one database, import it into another, replay it").dependOn(&moved.step); + + // A script run twice records the same database but for the wall clock's + // times: the log and the keyframes follow from the script alone. From + // fresh state it records in memory: no file at all. + const same_sessions = b.addExecutable(.{ .name = "same_sessions", .root_module = b.createModule(.{ + .root_source_file = b.path("test/same_sessions.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "Sessions", .module = b.createModule(.{ .root_source_file = b.path("src/host/Sessions.zig"), .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "xitdb", .module = xitdb } } }) }}, + }) }); + const twice = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\mkdir -p "$3"; d=$(realpath "$3"); rm -f "$d"/* + \\"$0" --headless --script "$1" --state "$d/a.state" "$4" + \\"$0" --headless --script "$1" --state "$d/b.state" "$4" + \\"$2" "$d/a.xitdb" "$d/b.xitdb" + \\"$0" --headless --fresh --script "$1" --state "$d/c.state" "$4" + \\test ! -e "$d/c.state"; test ! -e "$d/c.xitdb" + \\rm -f "$d"/* + }); + twice.setName("a script recorded twice"); + twice.addArtifactArg(host_exe); + twice.addFileArg(b.path("test/past.script")); + twice.addArtifactArg(same_sessions); + _ = twice.addOutputDirectoryArg("twice"); + twice.addArtifactArg(recorded); + twice.has_side_effects = true; + twice.expectExitCode(0); + test_step.dependOn(&twice.step); + b.step("test-same", "A script run twice records the same database but for times").dependOn(&twice.step); + + // Where files go. Without --state: the XDG data directory, one file. In + // .sketchbook/ (`zig build run`'s): a .gitignore and the save, whose + // present the next run starts from; an older build's state file beside + // it is moved in, once, never over a file there, and never deleted. + const paths = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\exe=$(realpath "$0"); lib=$(realpath "$1"); mkdir -p "$2"; d=$(realpath "$2") + \\rm -rf "$d"/* "$d"/.sketchbook; cd "$d" + \\XDG_DATA_HOME="$d/data" "$exe" --headless --console quit "$lib" + \\test "$(ls -A data/replay)" = replay.xitdb + \\"$exe" --headless --state .sketchbook/replay.xitdb --console "set updates 7" --console quit "$lib" + \\test "$(ls -A .sketchbook | tr '\n' ' ')" = ".gitignore replay.xitdb "; grep -qx '*' .sketchbook/.gitignore + \\printf 'expect updates 7\n' >check.script + \\"$exe" --headless --state .sketchbook/replay.xitdb --script check.script "$lib" + \\printf 'not a state file' >old.state + \\"$exe" --headless --state .sketchbook/old.xitdb --console quit "$lib" 2>err + \\grep -q moved err; test ! -e old.state; test "$(cat .sketchbook/old.state)" = 'not a state file' + \\printf 'not a state file' >old.state + \\"$exe" --headless --state .sketchbook/old.xitdb --console quit "$lib" 2>err + \\grep -q 'both exist' err; test -e old.state + \\rm -rf "$d"/* "$d"/.sketchbook + }); + paths.setName("where the save goes"); + paths.addArtifactArg(host_exe); + paths.addArtifactArg(recorded); + _ = paths.addOutputDirectoryArg("paths"); + paths.has_side_effects = true; + paths.expectExitCode(0); + test_step.dependOn(&paths.step); + b.step("test-paths", "Check where the save goes").dependOn(&paths.step); + + // The tree by name and the fs verbs, live and with the sketch closed. + const tree = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\exe=$(realpath "$0"); lib=$(realpath "$1"); mkdir -p "$2"; d=$(realpath "$2") + \\rm -rf "$d"/*; cd "$d"; rt=$(mktemp -d /tmp/sketchbook-fs.XXXXXX) + \\unset PARDES_PID PARDES_9P PARDES_PANE PARDES_MOUNT NINE_MOUNT NINE_MNTGEN + \\export XDG_RUNTIME_DIR="$rt" XDG_DATA_HOME="$d/data" + \\fs() { "$exe" --9p fstest "$lib" fs "$@"; } + \\"$exe" --headless --fresh --state live.xitdb --9p fstest "$lib" & pid=$! + \\trap 'kill $pid 2>/dev/null || true; rm -rf "$rt"' EXIT + \\i=0; while ! test -S "$rt"/9p/sketchbook/fstest; do i=$((i+1)); test $i -lt 500; sleep 0.01; done + \\fs ls | grep -qx 'state/' + \\fs write state/dots/buffer/2/kind big; test "$(fs read state/dots/buffer/2/kind)" = .big + \\! fs write state/dots/buffer/2/kind huge 2>err; grep -q InvalidValue err + \\fs write ctl 'click 30 40' + \\test "$(fs read screen.png | head -c 4 | tail -c 3)" = PNG + \\fs help state/dots | grep -q '^state/dots/len ' + \\fs help ctl | grep -q '^ click X Y ' + \\fs write ctl quit; wait $pid + \\test ! -e "$rt"/9p/sketchbook/fstest + \\test "$(fs read state/dots/buffer/2/kind 2>err)" = .small; grep -q 'replay is not running' err + \\! fs read status 2>err; grep -q 'replay is not running' err + \\rm -rf "$d"/* + }); + tree.setName("the tree by name, live and closed"); + tree.addArtifactArg(host_exe); + tree.addArtifactArg(recorded); + _ = tree.addOutputDirectoryArg("tree"); + tree.has_side_effects = true; + tree.expectExitCode(0); + test_step.dependOn(&tree.step); + b.step("test-fs", "Drive a sketch's tree by name with the fs verbs, running and closed").dependOn(&tree.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); @@ -287,6 +625,21 @@ pub fn build(b: *Build) void { test_step.dependOn(&replay.step); } +fn gltfModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *Build.Module { + const translator: translate_c.Translator = .init(b.dependency("translate_c", .{}), .{ + .c_source_file = b.path("vendor/cgltf.h"), + .target = target, + .optimize = optimize, + }); + translator.mod.addCSourceFile(.{ .file = b.path("vendor/cgltf.c"), .flags = &.{"-std=c99"} }); + return b.createModule(.{ + .root_source_file = b.path("src/gltf.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "cgltf_c", .module = translator.mod }}, + }); +} + 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"); @@ -298,6 +651,11 @@ fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Optimi \\#include <SDL3/SDL.h> \\#include "codecs.h" \\#include "text.h" + \\#if defined(__linux__) + \\#include <time.h> + \\#include <wayland-client.h> + \\#include "presentation-time-client-protocol.h" + \\#endif ), .target = target, .optimize = optimize, @@ -306,13 +664,58 @@ fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Optimi translator.addIncludePath(b.path("vendor")); translator.mod.addCSourceFile(.{ .file = b.path("vendor/codecs.c"), .flags = &.{"-fno-sanitize=undefined"} }); if (target.result.os.tag == .linux) { - translator.mod.addCSourceFile(.{ .file = b.path("vendor/text.c"), .flags = &.{"-std=c23"} }); - translator.mod.linkSystemLibrary("pangocairo-1.0", .{ .use_pkg_config = .force }); - translator.mod.linkSystemLibrary("pangoft2-1.0", .{ .use_pkg_config = .force }); + const protocol = b.path("vendor/presentation-time/presentation-time.xml"); + const header = b.addSystemCommand(&.{ "wayland-scanner", "client-header" }); + header.addFileArg(protocol); + translator.addIncludePath(header.addOutputFileArg("presentation-time-client-protocol.h").dirname()); + const source = b.addSystemCommand(&.{ "wayland-scanner", "private-code" }); + source.addFileArg(protocol); + translator.mod.addCSourceFile(.{ .file = source.addOutputFileArg("presentation-time-protocol.c"), .flags = &.{"-std=c99"} }); + translator.mod.linkSystemLibrary("wayland-client", .{ .use_pkg_config = .force }); } return translator.mod; } +/// `sketchbook-text`: vendor/text.c over pardes's vendor/font.c, FreeType +/// and HarfBuzz, the packages and flags pardes builds its window with. The +/// host links it, and so do a sketch's tests (`App.addTest`), which measure +/// text with no host; a sketch's library never does. Null until the lazy +/// packages are fetched. +fn textLibrary(b: *Build, target: Build.ResolvedTarget, mode: std.builtin.OptimizeMode) ?*Build.Step.Compile { + // FreeType and HarfBuzz are not what a Debug build debugs, and at -O0 a + // layout costs four to six times as much (a screen of source text laid + // out twice a frame: 2.9 ms against 0.6): optimised in every mode. + const optimize: std.builtin.OptimizeMode = if (mode == .debug) .ReleaseFast else mode; + const freetype = (b.lazyDependency("freetype", .{ .target = target, .optimize = optimize, .@"enable-libpng" = false }) orelse return null).artifact("freetype"); + const harfbuzz = b.lazyDependency("harfbuzz", .{}) orelse return null; + const lib = b.addLibrary(.{ .name = "sketchbook-text", .linkage = .static, .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .link_libc = true, + .link_libcpp = true, + }) }); + lib.root_module.linkLibrary(freetype); + lib.root_module.addIncludePath(harfbuzz.path("src")); + lib.root_module.addCSourceFile(.{ .file = harfbuzz.path("src/harfbuzz.cc"), .flags = &.{ + "-DHAVE_STDBOOL_H", + "-DHAVE_UNISTD_H", + "-DHAVE_SYS_MMAN_H", + "-DHAVE_PTHREAD=1", + "-DHAVE_FREETYPE=1", + "-DHAVE_FT_GET_VAR_BLEND_COORDINATES=1", + "-DHAVE_FT_SET_VAR_BLEND_COORDINATES=1", + "-DHAVE_FT_DONE_MM_VAR=1", + "-DHAVE_FT_GET_TRANSFORM=1", + "-Dhb_malloc_impl=ui_malloc", + "-Dhb_calloc_impl=ui_calloc", + "-Dhb_realloc_impl=ui_realloc", + "-Dhb_free_impl=ui_free", + } }); + lib.root_module.addCSourceFile(.{ .file = b.path("vendor/font.c") }); + lib.root_module.addCSourceFile(.{ .file = b.path("vendor/text.c"), .flags = &.{"-std=c23"} }); + return lib; +} + /// SDL 3.4.14 gives its pthread TLS key no destructor, so threads SDL did not /// create (PipeWire's) leave error storage behind when they exit. Compile the /// original backend with an exit destructor; the pinned package is untouched. @@ -362,7 +765,9 @@ fn fixSdlThreadCleanup(b: *Build, sdl: *Build.Module, source: Build.LazyPath) vo /// far went to the old texture and the rest to the copy, which shows the /// previous frame under it (seen after a large texture was freed, at /// 1920x1080 and up). Freed memory is still reused; it is only not -/// compacted. +/// compacted. With relocation disabled, small transfer buffers can also +/// suballocate safely instead of freeing hundreds of dedicated Vulkan +/// allocations during presentation. fn fixSdlVulkanAllocationLeak(b: *Build, sdl: *Build.Module, source: Build.LazyPath) void { const file = "src/gpu/vulkan/SDL_gpu_vulkan.c"; var found = false; @@ -388,6 +793,7 @@ fn fixSdlVulkanAllocationLeak(b: *Build, sdl: *Build.Module, source: Build.LazyP }) }); const edit = b.addRunArtifact(tool); edit.setName("patch SDL_gpu_vulkan.c"); + edit.addFileInput(source.path(b, "gpu/vulkan/SDL_gpu_vulkan.c")); edit.addDirectoryArg(source.path(b, "gpu/vulkan")); const out = edit.addOutputDirectoryArg("vulkan"); edit.addArgs(&.{ @@ -397,6 +803,9 @@ fn fixSdlVulkanAllocationLeak(b: *Build, sdl: *Build.Module, source: Build.LazyP "SDL_gpu_vulkan.c", " VULKAN_INTERNAL_MarkAllocationsForDefrag(renderer);\n", " (void)VULKAN_INTERNAL_MarkAllocationsForDefrag;\n", + "SDL_gpu_vulkan.c", + " VULKAN_BUFFER_TYPE_TRANSFER,\n true, // Dedicated allocations preserve the data even if a defrag is triggered.\n", + " VULKAN_BUFFER_TYPE_TRANSFER,\n false, // Sketchbook disables defrag, so small transfers can share allocations.\n", }); // The copy's relative includes (`../SDL_sysgpu.h`) resolve from the // original directory. @@ -413,6 +822,8 @@ pub const Options = struct { optimize: std.builtin.OptimizeMode, /// This package's name in the app's build.zig.zon. dependency: []const u8 = "sketchbook", + /// An existing Tracy checkout; null leaves native profiling compiled out. + tracy: ?[]const u8 = null, /// 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 @@ -422,7 +833,7 @@ pub const Options = struct { }; pub fn init(b: *Build, options: Options) Sketchbook { - const dep = b.dependency(options.dependency, .{ .target = options.target, .optimize = options.optimize }); + const dep = b.dependency(options.dependency, .{ .target = options.target, .optimize = options.optimize, .tracy = options.tracy orelse "" }); const shared: *Shared = .create(b); for ([_][]const u8{ "vector_shaders", "scope_shaders" }) |name| { shared.web_twins.put(b.graph.arena, dep.module(name), dep.module(b.fmt("{s}_web", .{name}))) catch @panic("OOM"); @@ -431,13 +842,15 @@ pub fn init(b: *Build, options: Options) Sketchbook { .b = b, .target = options.target, .optimize = options.optimize, - .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim") }, + .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim"), .gltf = dep.module("gltf"), .cloud9 = dep.module("cloud9") }, .host_exe = dep.artifact("sketchbook"), - .probe_exe = dep.artifact("sketchbook-probe"), + .text = dep.artifact("sketchbook-text"), + .gltf_generator = dep.artifact("gltf-bindings"), .web = dep.path("web"), .glsl = dep.path("src/glsl.zig"), .tools = dep.path("tools"), .anim_dir = dep.path("src/anim"), + .gltf_render_dir = dep.path("src/gltf_render"), .script_optimize = options.script_optimize orelse options.optimize, .shared = shared, }; @@ -458,6 +871,9 @@ const Shared = struct { openssl: ?Build.LazyPath = null, /// A self-signed certificate and its key, for `addServe`. certificate: ?Certificate = null, + /// `source`, the revision the build's sketches are made from (see + /// `buildInfo`). + build_info: ?*Build.Module = null, const Certificate = struct { cert: Build.LazyPath, key: Build.LazyPath }; const Recipe = union(enum) { glsl: Sketchbook.ShaderOptions, zig: Sketchbook.ZigShaderOptions }; @@ -476,11 +892,15 @@ pub const Sketchbook = struct { /// `vector`: SVG, cubic geometry, and CPU and GPU renderers. `scope`: /// waveform, spectrogram, spectrum and oscilloscope views of a sound. /// `anim`: manim-style scenes as code (see `addScene`). - modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module }, + /// `gltf`: native glTF/GLB documents, accessors and extras through cgltf. + /// `cloud9` is the 9P library the host serves its tree with: its `Fsys` + /// dials a sketch's executable from the app's own tests. + modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module, gltf: *Build.Module, cloud9: *Build.Module }, /// The generic host: loads and hot-reloads a sketch library. host_exe: *Build.Step.Compile, - /// Prints any sketch's state file. - probe_exe: *Build.Step.Compile, + /// FreeType, HarfBuzz and vendor/text.c: what the host measures text + /// with, linked into an app's tests (`App.addTest`) so they measure too. + text: *Build.Step.Compile, /// `host.js` and the `index.html` template. web: Build.LazyPath, /// The GLSL declaration generator (see `addGlslLayouts`). @@ -495,6 +915,34 @@ pub const Sketchbook = struct { script_optimize: std.builtin.OptimizeMode, shared: *Shared, + /// Host executable; stays native even when the consumer is cross-compiled. + gltf_generator: *Build.Step.Compile, + gltf_render_dir: Build.LazyPath, + + /// Opaque native glTF rendering, with shader layouts generated from Zig types. + pub fn addGltfRenderer(sb: Sketchbook) *Build.Module { + const b = sb.b; + const types = b.createModule(.{ .root_source_file = sb.gltf_render_dir.path(b, "types.zig") }); + const shaders = sb.addShaders(.{ .layouts = .{ .module = types, .types = &.{"Transform"} }, .sources = &.{ + sb.gltf_render_dir.path(b, "basic.vert"), sb.gltf_render_dir.path(b, "basic.frag"), + } }); + const module = b.createModule(.{ .root_source_file = sb.gltf_render_dir.path(b, "root.zig"), .imports = &.{ + .{ .name = "sketch", .module = sb.modules.sketch }, .{ .name = "gltf", .module = sb.modules.gltf }, + .{ .name = "types", .module = types }, .{ .name = "shaders", .module = shaders.module }, + } }); + sb.shared.web_twins.put(b.graph.arena, module, b.createModule(.{ .root_source_file = sb.gltf_render_dir.path(b, "web.zig") })) catch @panic("OOM"); + return module; + } + + /// A cached generator run writes Zig source first; consumers compile it next. + /// Exact glTF labels become declarations; duplicate labels fail generation. + pub fn addGltf(sb: Sketchbook, source: Build.LazyPath) *Build.Module { + const run = sb.b.addRunArtifact(sb.gltf_generator); + run.addFileArg(source); + const generated = run.addOutputFileArg("gltf_bindings.zig"); + return sb.b.createModule(.{ .root_source_file = generated }); + } + pub const GlslLayouts = struct { run: *Build.Step.Run, /// `<Name>.glsl` for each type: pass it to `addGlslc` as an include. @@ -857,6 +1305,30 @@ pub const Sketchbook = struct { return b.createModule(.{ .root_source_file = dir.path(b, "typst.zig") }); } + /// The module `build_info`: `source`, the revision of the repository + /// the build runs in, read once per build. + // ponytail: one `jj log -r @` (else git, else nothing) per build, on the + // critical path of every sketch compile: 10-20 ms, a `snapshot working + // copy` op in the user's op log per build, and `sh` only. Upgrade, once + // incremental builds make 10 ms matter: the development host asks the + // repository at load time instead, off the compile path. Never fails a + // build: any error is "no source". + fn buildInfo(sb: Sketchbook) *Build.Module { + if (sb.shared.build_info) |module| return module; + const b = sb.b; + const run = b.addSystemCommand(&.{ "sh", "-c", + \\r=$(jj log --no-graph -r @ -T 'commit_id ++ " " ++ change_id' 2>/dev/null) && r="jj:$r" || + \\ { r=$(git rev-parse HEAD 2>/dev/null) && { git diff --quiet HEAD 2>/dev/null || r="$r+dirty"; } && r="git:$r"; } || + \\ r="" + \\printf 'pub const source = "%s";\n' "$r" + }); + run.setCwd(b.path(".")); + run.setName("source revision"); + run.has_side_effects = true; + sb.shared.build_info = b.createModule(.{ .root_source_file = run.captureStdOut(.{ .basename = "build_info.zig" }) }); + return sb.shared.build_info.?; + } + pub fn app(sb: Sketchbook, options: App.Options) App { const imports = sb.b.allocator.alloc(Build.Module.Import, options.imports.len + 1) catch @panic("OOM"); imports[0] = .{ .name = "sketch", .module = sb.modules.sketch }; @@ -866,6 +1338,7 @@ pub const Sketchbook = struct { .name = options.name, .root_source_file = options.root_source_file, .imports = imports, + .record = options.record, // No target: every artifact compiles it for its own. .module = sb.b.createModule(.{ .root_source_file = options.root_source_file, .imports = imports }), }; @@ -879,6 +1352,7 @@ pub const App = struct { imports: []const Build.Module.Import, /// The app's root, importing `sketch` and the app's own imports. module: *Build.Module, + record: ?bool, pub const Options = struct { name: []const u8, @@ -886,16 +1360,24 @@ pub const App = struct { /// Imports for the app's root module, besides `sketch`: for example /// `sb.modules.vector`, or shaders from `addSpirvModule`. imports: []const Build.Module.Import = &.{}, + /// Keep every run's history in the save, the newest 64 MiB of it + /// (src/host/Sessions.zig); without, the save keeps the present and + /// the marks only. Null: in Debug builds only. A + /// playtest build of a release opts in with one line, + /// `.record = b.option(bool, "record", "collect sessions in a release build")`. + record: ?bool = null, }; - /// A root module around the app: `source` sees `app`, `sketch` and `host`. + /// A root module around the app: `source` sees `app`, `sketch` and `host`, + /// and `{made}` in it becomes the app's `sketch.Build`. fn wrap(app: App, source: []const u8, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *Build.Module { const b = app.sb.b; + const made = b.fmt(".{{ .source = @import(\"build_info\").source, .record = {} }}", .{app.record orelse (optimize == .debug)}); const root = b.createModule(.{ - .root_source_file = b.addWriteFiles().add("root.zig", source), + .root_source_file = b.addWriteFiles().add("root.zig", std.mem.replaceOwned(u8, b.allocator, source, "{made}", made) catch @panic("OOM")), .target = target, .optimize = optimize, - .imports = &.{ .{ .name = "app", .module = app.module }, .{ .name = "sketch", .module = app.sb.modules.sketch } }, + .imports = &.{ .{ .name = "app", .module = app.module }, .{ .name = "sketch", .module = app.sb.modules.sketch }, .{ .name = "build_info", .module = app.sb.buildInfo() } }, }); if (std.mem.indexOf(u8, source, "\"host\"") != null) root.addImport("host", app.sb.modules.host); return root; @@ -906,7 +1388,7 @@ pub const App = struct { return app.sb.b.addLibrary(.{ .name = app.name, .linkage = .dynamic, - .root_module = app.wrap("comptime { @import(\"sketch\").exportSketch(@import(\"app\")); }", app.sb.target, app.sb.optimize), + .root_module = app.wrap("comptime { @import(\"sketch\").exportSketch(@import(\"app\"), {made}); }", app.sb.target, app.sb.optimize), }); } @@ -928,7 +1410,7 @@ pub const App = struct { .root_module = app.wrap( \\const std = @import("std"); \\pub fn main(init: std.process.Init) !void { - \\ return @import("host").main(init, @import("sketch").sketch(@import("app"))); + \\ return @import("host").main(init, @import("sketch").sketch(@import("app"), {made})); \\} , app.sb.target, optimize), }); @@ -1079,7 +1561,8 @@ pub const App = struct { } pub const RunOptions = struct { - /// State file, relative to the working directory. + /// The save, relative to the working directory; + /// `.sketchbook/<name>.xitdb` by default, ignored by git and jj. state: ?[]const u8 = null, /// Where relative asset paths resolve; the project root by default. cwd: ?Build.LazyPath = null, @@ -1092,7 +1575,7 @@ pub const App = struct { const install = b.addInstallArtifact(library, .{}); const run = b.addRunArtifact(app.sb.host_exe); run.step.dependOn(&install.step); - run.addArgs(&.{ "--state", options.state orelse b.fmt("{s}.state", .{app.name}) }); + run.addArgs(&.{ "--state", options.state orelse b.fmt(".sketchbook/{s}.xitdb", .{app.name}) }); run.addFileArg(b.graph.path(.install_lib, library.out_filename)); run.setCwd(options.cwd orelse b.path(".")); run.stdio = .inherit; @@ -1106,7 +1589,7 @@ pub const App = struct { cwd: ?Build.LazyPath = null, }; - /// Plays a script headless, with a throwaway state file, against + /// Plays a script headless, from fresh state and saving nothing, against /// `artifact`: the executable (`addExecutable`), or the hot-reloadable /// library (`addLibrary`) through the generic host, which scripts can /// `reload`. Fails when an expectation or a console line does. @@ -1118,7 +1601,7 @@ pub const App = struct { run.addFileArg(script); run.addArg("--state"); // Named per script: runs of one app may share an output directory. - _ = run.addOutputFileArg(b.fmt("{s}-{s}.state", .{ app.name, std.fs.path.stem(script.getDisplayName()) })); + _ = run.addOutputFileArg(b.fmt("{s}-{s}.xitdb", .{ app.name, std.fs.path.stem(script.getDisplayName()) })); for (options.defines) |pair| run.addArgs(&.{ "--define", b.fmt("{s}={s}", .{ pair[0], pair[1] }) }); if (library) run.addArtifactArg(artifact); run.setCwd(options.cwd orelse b.path(".")); @@ -1148,7 +1631,7 @@ pub const App = struct { const b = app.sb.b; const run = b.addRunArtifact(exe); run.addArg("--state"); - _ = run.addOutputFileArg(b.fmt("{s}-export.state", .{app.name})); + _ = run.addOutputFileArg(b.fmt("{s}-export.xitdb", .{app.name})); run.addArg("--export"); const frames = run.addOutputDirectoryArg("frames"); run.addArgs(&.{ "--fps", b.fmt("{d}", .{options.fps}) }); @@ -1159,17 +1642,6 @@ pub const App = struct { return .{ .run = run, .frames = frames }; } - /// Prints the app's live state; `zig build probe -- --watch` follows it. - pub fn addProbe(app: App, state: ?[]const u8) *Build.Step.Run { - const b = app.sb.b; - const run = b.addRunArtifact(app.sb.probe_exe); - run.addArg(state orelse b.fmt("{s}.state", .{app.name})); - run.setCwd(b.path(".")); - run.stdio = .inherit; - run.addPassthruArgs(); - return run; - } - /// Tests in `root_source_file` (the app's root by default), with the /// app's imports and the app itself importable as `app`. pub fn addTest(app: App, options: struct { root_source_file: ?Build.LazyPath = null }) *Build.Step.Compile { @@ -1181,6 +1653,7 @@ pub const App = struct { .imports = app.imports, }); if (options.root_source_file != null) module.addImport("app", app.module); + module.linkLibrary(app.sb.text); return b.addTest(.{ .root_module = module }); } @@ -1414,7 +1887,7 @@ pub const App = struct { /// The conventional wiring. Installs the executable, and adds: /// `run` (host + hot reload), `lib` (rebuild the library; use `--watch`), - /// `web` and `serve` (with `web` options), `probe`, `export` (frames + /// `web` and `serve` (with `web` options), `export` (frames /// for ffmpeg), `e2e` (scripts) and `test`. pub fn addSteps(app: App, options: StepsOptions) Steps { const b = app.sb.b; @@ -1425,7 +1898,6 @@ pub const App = struct { const run = app.addRun(library, .{}); b.step("run", "Run with hot reload (rebuild with `zig build lib --watch`)").dependOn(&run.step); b.step("lib", "Build and install the hot-reloadable library").dependOn(&b.addInstallArtifact(library, .{}).step); - b.step("probe", "Print the live state (-- --watch to follow)").dependOn(&app.addProbe(null).step); const web = if (options.web) |web_options| blk: { const web = app.addWeb(web_options); @@ -1437,7 +1909,7 @@ pub const App = struct { // `--export` takes the first argument after `--`. const exporting = b.addRunArtifact(exe); - exporting.addArgs(&.{ "--state", b.fmt("{s}.state", .{app.name}), "--export" }); + exporting.addArgs(&.{ "--state", b.fmt(".sketchbook/{s}.xitdb", .{app.name}), "--export" }); exporting.addPassthruArgs(); exporting.setCwd(b.path(".")); exporting.stdio = .inherit; @@ -1460,6 +1932,8 @@ pub const App = struct { /// whose display name would be "generated". fn fileName(path: Build.LazyPath) []const u8 { return switch (path) { + .dependency => |d| std.fs.path.basename(d.sub_path), + .relative => |r| std.fs.path.basename(r.sub_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()), }; |
