diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 22:03:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 22:23:51 -0300 |
| commit | 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch) | |
| tree | 813596ea84318a7bae4fd7416ba463de8e3b7107 /core/FrameStats.zig | |
| parent | 92d553123673376adf6126ab90d49a22c5b833d2 (diff) | |
| download | pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip | |
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/FrameStats.zig')
| -rw-r--r-- | core/FrameStats.zig | 531 |
1 files changed, 531 insertions, 0 deletions
diff --git a/core/FrameStats.zig b/core/FrameStats.zig new file mode 100644 index 00000000..4fbe0735 --- /dev/null +++ b/core/FrameStats.zig @@ -0,0 +1,531 @@ +//! The frame-timing probe a game keeps: for every frame the pump draws, how +//! long its update, its render and its present took on the clock, the gap +//! since the frame before, and what the shell's own motion (a scroll's +//! picture) showed in it. A frame that something was +//! animating into and that came more than half a display period late is +//! jank: the eye sees the motion stop for a refresh. The records go in a +//! fixed ring embedded in `Pardes`, nothing allocated per frame, and cost +//! three reads of the monotonic clock a frame, so the probe is always on: +//! `Debug` shows the last second of it in its box, and `PARDES_FRAMES=path` +//! keeps a longer ring (`long_capacity`, from the first frame) and writes +//! it and its summary there when the session ends. +//! +//! Each frame also carries its input-to-present latency (from the first +//! input it answers, the shell's timestamp of the key or wheel event, to +//! the end of its present), where its work went (`Zone`: the core's body +//! text, rows and colours; the shell's instance build, word shaping and +//! glyph rasterizing) and the view it showed, so a spike is attributed and +//! a scroll's throughput is counted in rows actually presented. +//! +//! `PARDES_FRAMES_DEMO=<file>` runs a timed script of inputs (`parseScript`; +//! the ones the notes measured with are in tools/demos/) in a pixel shell +//! (the GUI feeds them through its own wheel and key paths) and then ends +//! the session: a timedemo, so two builds are compared on the same motion, +//! on a real display. +const std = @import("std"); +const pardes = @import("root.zig"); +const frame_ns = @import("root.zig").frame_ns; + +const FrameStats = @This(); + +/// The frames every core keeps (90 KB), what the Debug box reads: the +/// last second's, and the input latency over all of them. +pub const capacity = 1024; +/// The frames a core keeps with PARDES_FRAMES set: 4.5 minutes at 60 Hz, +/// so the longest timedemo fits whole (1.4 MB, allocated at the first). +pub const long_capacity = 16384; + +pub const Frame = struct { + /// When the frame's step began, the input that woke it read: the + /// monotonic clock, ns. + start_ns: u64 = 0, + /// Events, effects and the shell's poll; the core's render; the + /// shell's present (its instance build and GPU submission). µs. + update_us: u32 = 0, + render_us: u32 = 0, + present_us: u32 = 0, + /// From the previous drawn frame's present to this one's, µs. + gap_us: u32 = 0, + /// Something was moving into this frame: the gap should be a period. + moving: bool = false, + /// The shell had no image to draw into (a busy swapchain). + skipped: bool = false, + /// The shell's motion in it: a scroll's picture offset from the text, + /// rows (0 at rest), or a focused PDF's strip as drawn, pixels down + /// the document; and where it drew the caret, its top in rows (the + /// jitter check: a caret on a fixed row must not wobble). + scroll: f32 = 0, + caret: f32 = 0, + /// From the first input this frame answers to its present's end, µs; + /// 0 when it answers none. + latency_us: u32 = 0, + /// The focused pane's first line: with `scroll`, where the picture is. + view: i32 = 0, + /// µs a frame spent in each zone, and how many words the shell shaped + /// and glyphs it rasterized anew. + zones: [zone_count]u32 = @splat(0), + shaped: u16 = 0, + rastered: u16 = 0, + /// Bytes a cell shell wrote to its terminal for the frame. + bytes: u32 = 0, + /// PDF page rasters that landed in it (rendered on the loop, or taken + /// from a lane): the frame a page lands on. + landed: u16 = 0, +}; + +/// Where a frame's work goes, as a game's profiler splits its budget. +/// The gui's are nested: shape and raster inside build; a soft present's +/// wait for the GPU, its upload of the frame and its flip after it. +pub const Zone = enum(u8) { body_text, body_rows, body_color, gui_build, gui_shape, gui_raster, gui_wait, gui_upload, gui_flip }; +pub const zone_count = std.enums.values(Zone).len; + +ring: [capacity]Frame = @splat(.{}), +/// PARDES_FRAMES's ring, which takes the frames in place of `ring`. +long: ?*[long_capacity]Frame = null, +/// Frames recorded since the start; the ring holds the last of them. +count: u64 = 0, +/// The display's refresh period, as the shell knows it. +period_ns: u64 = frame_ns, +/// The end of the last drawn frame's present, and whether anything was +/// still moving then (the next frame was owed at once). +last_end_ns: u64 = 0, +armed: bool = false, +/// Since the start: frames that came late into a motion, and frames whose +/// own work (update, render, present) took longer than a period. +jank: u64 = 0, +over_budget: u64 = 0, +skipped: u64 = 0, +/// What the shell sets while it draws the frame (Frame.scroll), and the +/// pump (view). +scroll: f32 = 0, +caret: f32 = 0, +view: i32 = 0, +/// The first input not yet answered by a drawn frame, monotonic ns. +input_ns: u64 = 0, +/// This frame's zones so far. +zone_us: [zone_count]u32 = @splat(0), +shaped: u16 = 0, +rastered: u16 = 0, +bytes: u32 = 0, +landed: u16 = 0, +/// When the timedemo started, monotonic ns (0: none ran), and its steps. +demo_ns: u64 = 0, +demo: []const Step = &.{}, +/// The frame being timed: its marks, the monotonic clock's ns. +mark_start: u64 = 0, +mark_update: u64 = 0, +mark_render: u64 = 0, + +/// An input arrived at `at_ns`: the next drawn frame answers it. +pub fn input(stats: *FrameStats, at_ns: u64) void { + if (stats.input_ns == 0 or at_ns < stats.input_ns) stats.input_ns = at_ns; +} + +/// The pump had nothing to draw: what came in changed nothing on screen, +/// so no frame answers it. +pub fn idle(stats: *FrameStats) void { + stats.input_ns = 0; + // Nor was a frame owed after all (a motion that ended between frames): + // the next frame's gap is no motion's. + stats.armed = false; +} + +/// Adds the time since `from_ns` to `which`. +pub fn zone(stats: *FrameStats, which: Zone, from_ns: u64) void { + const us: u32 = @intCast(@min(std.math.maxInt(u32), (nowNs() -| from_ns) / std.time.ns_per_us)); + stats.zone_us[@backingInt(which)] +|= us; +} + +pub fn nowNs() u64 { + var ts: std.c.timespec = undefined; + if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; + return @as(u64, @intCast(ts.sec)) *| std.time.ns_per_s +| @as(u64, @intCast(ts.nsec)); +} + +/// Closes the frame whose marks are set: `end_ns` is when its present +/// returned, `moving` whether anything still moves (a frame is owed at +/// once), `skipped` whether the shell drew nothing. +pub fn record(stats: *FrameStats, end_ns: u64, moving: bool, skipped: bool) void { + const us = struct { + fn of(from: u64, to: u64) u32 { + return @intCast(@min(std.math.maxInt(u32), (to -| from) / std.time.ns_per_us)); + } + }; + const gap: u32 = if (stats.last_end_ns == 0) 0 else us.of(stats.last_end_ns, end_ns); + const frame: Frame = .{ + .start_ns = stats.mark_start, + .update_us = us.of(stats.mark_start, stats.mark_update), + .render_us = us.of(stats.mark_update, stats.mark_render), + .present_us = us.of(stats.mark_render, end_ns), + .gap_us = gap, + .moving = stats.armed, + .skipped = skipped, + .scroll = stats.scroll, + .caret = stats.caret, + .latency_us = if (stats.input_ns == 0) 0 else @max(1, us.of(stats.input_ns, end_ns)), + .view = stats.view, + .zones = stats.zone_us, + .shaped = stats.shaped, + .rastered = stats.rastered, + .bytes = stats.bytes, + .landed = stats.landed, + }; + stats.bytes = 0; + stats.landed = 0; + stats.input_ns = 0; + stats.zone_us = @splat(0); + stats.shaped = 0; + stats.rastered = 0; + // Half a period late is a refresh the motion missed. + if (stats.armed and @as(u64, gap) * std.time.ns_per_us * 2 > stats.period_ns * 3) stats.jank += 1; + if (@as(u64, frame.update_us + frame.render_us + frame.present_us) * std.time.ns_per_us > stats.period_ns) stats.over_budget += 1; + if (skipped) stats.skipped += 1; + if (stats.count == 0 and std.c.getenv("PARDES_FRAMES") != null) { + stats.long = std.heap.page_allocator.create([long_capacity]Frame) catch null; + } + const ring: []Frame = if (stats.long) |long| long else &stats.ring; + ring[@intCast(stats.count % ring.len)] = frame; + stats.count += 1; + stats.last_end_ns = end_ns; + stats.armed = moving; +} + +/// The last `n` frames, oldest first, as two slices of the ring. +pub fn last(stats: *const FrameStats, n: usize) [2][]const Frame { + const ring: []const Frame = if (stats.long) |long| long else &stats.ring; + const have: usize = @intCast(@min(stats.count, ring.len)); + const take = @min(n, have); + const end: usize = @intCast(stats.count % ring.len); + if (take <= end) return .{ ring[end - take .. end], &.{} }; + return .{ ring[ring.len - (take - end) ..], ring[0..end] }; +} + +/// Order statistics of one of a run of frames' times, µs: its median, +/// 99th percentile and worst; over the moving frames only for a gap. +pub const Spread = struct { + n: usize = 0, + p50: u32 = 0, + p90: u32 = 0, + p99: u32 = 0, + max: u32 = 0, + mean: f64 = 0, + + pub const What = enum { work, update, render, present, gap, latency }; + + pub fn of(frames: [2][]const Frame, comptime what: What) Spread { + var values: [long_capacity]u32 = undefined; + var n: usize = 0; + var sum: f64 = 0; + for (frames) |part| for (part) |f| { + const v: u32 = switch (what) { + .work => f.update_us + f.render_us + f.present_us, + .update => f.update_us, + .render => f.render_us, + .present => f.present_us, + .gap => if (f.moving) f.gap_us else continue, + .latency => if (f.latency_us != 0) f.latency_us else continue, + }; + values[n] = v; + n += 1; + sum += @floatFromInt(v); + }; + if (n == 0) return .{}; + std.mem.sortUnstable(u32, values[0..n], {}, std.sort.asc(u32)); + return .{ + .n = n, + .p50 = values[n / 2], + .p90 = values[@min(n - 1, n * 90 / 100)], + .p99 = values[@min(n - 1, n * 99 / 100)], + .max = values[n - 1], + .mean = sum / @as(f64, @floatFromInt(n)), + }; + } +}; + +/// The Debug box's lines: the last second's work, gaps and input latency, +/// and the jank counter since the start, in ms. +pub fn summary(stats: *const FrameStats, buf: *[summary_max]u8) []const u8 { + const recent = stats.last(@intCast(@max(1, std.time.ns_per_s / @max(1, stats.period_ns)))); + const work = Spread.of(recent, .work); + const gap = Spread.of(recent, .gap); + const latency = Spread.of(stats.last(capacity), .latency); + const ms = struct { + fn of(v: u32) f64 { + return @as(f64, @floatFromInt(v)) / 1000; + } + }; + return std.fmt.bufPrint(buf, "frame {d:.2}/{d:.2}/{d:.2} ms\ngap {d:.2}/{d:.2} ms jank {d}\ninput {d:.2}/{d:.2} ms", .{ + ms.of(work.p50), ms.of(work.p99), ms.of(work.max), ms.of(gap.p50), ms.of(gap.max), stats.jank, ms.of(latency.p50), ms.of(latency.p90), + }) catch unreachable; // summary_max holds the widest +} + +/// `summary`'s widest: its words, seven u32 µs in ms with two places +/// (`4294967.30`) and a u64. +pub const summary_max = 132; + +/// Writes the summary and every frame the ring holds to `path`: a header +/// of `# ` lines, then one tab-separated line a frame. The long ring goes. +pub fn dump(stats: *FrameStats, path: [:0]const u8) void { + defer if (stats.long) |long| { + std.heap.page_allocator.destroy(long); + stats.long = null; + }; + const fd = std.c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(std.c.mode_t, 0o644)); + if (fd < 0) return; + defer _ = std.c.close(fd); + var buf: [256]u8 = undefined; + const all = stats.last(long_capacity); + const write = struct { + fn line(f: c_int, b: []u8, comptime fmt: []const u8, args: anytype) void { + const text = std.fmt.bufPrint(b, fmt, args) catch return; + _ = std.c.write(f, text.ptr, text.len); + } + }; + write.line(fd, &buf, "# frames {d} period_us {d} jank {d} over_budget {d} skipped {d}\n", .{ stats.count, stats.period_ns / std.time.ns_per_us, stats.jank, stats.over_budget, stats.skipped }); + inline for (comptime std.enums.values(Spread.What)) |what| { + const s = Spread.of(all, what); + write.line(fd, &buf, "# {t} n {d} mean {d:.0} p50 {d} p90 {d} p99 {d} max {d}\n", .{ what, s.n, s.mean, s.p50, s.p90, s.p99, s.max }); + } + const t0 = if (all[0].len != 0) all[0][0].start_ns else 0; + // The monotonic clock is the machine's: a driver lines its own times + // up with the frames' by this. + write.line(fd, &buf, "# t0_ns {d}\n", .{t0}); + // The timedemo's phases, on the frames' clock. + for (stats.demo) |step| switch (step.act) { + .phase => |name| write.line(fd, &buf, "# phase {s} {d:.1}\n", .{ name, @as(f64, @floatFromInt((stats.demo_ns + @as(u64, step.at_ms) * std.time.ns_per_ms) -| t0)) / std.time.ns_per_ms }), + else => {}, + }; + write.line(fd, &buf, "# start_ms\tupdate_us\trender_us\tpresent_us\tgap_us\tmoving\tskipped\tscroll\tcaret\tlatency_us\tview", .{}); + inline for (comptime std.enums.values(Zone)) |which| write.line(fd, &buf, "\t{t}_us", .{which}); + write.line(fd, &buf, "\tshaped\trastered\tbytes\tlanded\n", .{}); + for (all) |part| for (part) |f| { + write.line(fd, &buf, "{d:.3}\t{d}\t{d}\t{d}\t{d}\t{d}\t{d}\t{d:.4}\t{d:.4}\t{d}\t{d}", .{ + @as(f64, @floatFromInt(f.start_ns -| t0)) / std.time.ns_per_ms, f.update_us, f.render_us, f.present_us, f.gap_us, + @intFromBool(f.moving), @intFromBool(f.skipped), f.scroll, f.caret, f.latency_us, f.view, + }); + for (f.zones) |us| write.line(fd, &buf, "\t{d}", .{us}); + write.line(fd, &buf, "\t{d}\t{d}\t{d}\t{d}\n", .{ f.shaped, f.rastered, f.bytes, f.landed }); + }; +} + +/// One input of a timedemo, `at_ms` after the first frame. +pub const Step = struct { + at_ms: u32, + act: union(enum) { + /// Wheel notches, down positive, as a mouse's. + wheel: i8, + /// A touchpad's scroll, lines down, a fraction (no notch). + touch: f32, + key: pardes.Key, + /// A named stretch of the run starts (the dump lists them). + phase: []const u8, + /// A press and release of `button` over the focused pane, `at` of + /// the way down its body, on its rail or in its text. + click: struct { button: pardes.Mouse.Button, at: f32, rail: bool }, + /// Wheel notches over the focused pane's rail (the gutter). + rail_wheel: i8, + /// Text pasted (bracketed, as a terminal's paste arrives). + paste: []const u8, + /// A line run as Exec runs it, in the focused pane (a builtin, a + /// setting, else a shell command), the pane it opens focused: what + /// opens the other kinds of pane. + exec: []const u8, + /// The run is over: the session ends. + end, + }, +}; + +/// A timedemo's script, the file PARDES_FRAMES_DEMO names (tools/demos/): an +/// input a line, `<ms> <action> [<arg>]` at `ms` after the first frame, or +/// `<ms> <n>x<every> <action> [<arg>]` for n of them `every` ms apart; a +/// line that starts with `#` says what the script is. The actions: `wheel +/// <notches>` (down positive), `touch <lines>`, `key <k>`, `keys <k>...` +/// (its keys in turn, each `every` ms after the one before, n times over), +/// `phase <name>`, `click <button> <at> rail` or `text`, `rail_wheel +/// <notches>`, `paste <text>` and `exec <line>` (in both `\n` is a newline +/// and `\\` a backslash), and `end`. A key is a character (its text typed), +/// `space`, `^<c>` (with Ctrl) or a pardes.Key name (enter, page_down, ...). +/// The steps' strings are `text`'s, or `arena`'s where an escape was undone. +pub fn parseScript(arena: std.mem.Allocator, text: []const u8) error{ OutOfMemory, BadScript }![]Step { + var steps: std.ArrayList(Step) = .empty; + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |raw| { + const line = std.mem.trimEnd(u8, raw, "\r"); + if (line.len == 0 or line[0] == '#') continue; + var words = std.mem.tokenizeScalar(u8, line, ' '); + const at = std.fmt.parseInt(u32, words.next() orelse return error.BadScript, 10) catch return error.BadScript; + var word = words.next() orelse return error.BadScript; + var count: u32 = 1; + var every: u32 = 0; + if (std.ascii.isDigit(word[0])) { + const x = std.mem.indexOfScalar(u8, word, 'x') orelse return error.BadScript; + count = std.fmt.parseInt(u32, word[0..x], 10) catch return error.BadScript; + every = std.fmt.parseInt(u32, word[x + 1 ..], 10) catch return error.BadScript; + word = words.next() orelse return error.BadScript; + } + const arg = words.rest(); + if (std.mem.eql(u8, word, "keys")) { + var k: u32 = 0; + for (0..count) |_| { + var names = std.mem.tokenizeScalar(u8, arg, ' '); + while (names.next()) |name| : (k += 1) try steps.append(arena, .{ .at_ms = at + k * every, .act = .{ .key = keyOf(name) orelse return error.BadScript } }); + } + continue; + } + const Act = @FieldType(Step, "act"); + const act: Act = switch (std.meta.stringToEnum(std.meta.Tag(Act), word) orelse return error.BadScript) { + .wheel => .{ .wheel = std.fmt.parseInt(i8, arg, 10) catch return error.BadScript }, + .rail_wheel => .{ .rail_wheel = std.fmt.parseInt(i8, arg, 10) catch return error.BadScript }, + .touch => .{ .touch = std.fmt.parseFloat(f32, arg) catch return error.BadScript }, + .key => .{ .key = keyOf(arg) orelse return error.BadScript }, + .phase => .{ .phase = arg }, + .click => click: { + var parts = std.mem.tokenizeScalar(u8, arg, ' '); + const button = std.meta.stringToEnum(pardes.Mouse.Button, parts.next() orelse "") orelse return error.BadScript; + const where = std.fmt.parseFloat(f32, parts.next() orelse "") catch return error.BadScript; + const on = std.meta.stringToEnum(enum { rail, text }, parts.next() orelse "") orelse return error.BadScript; + break :click .{ .click = .{ .button = button, .at = where, .rail = on == .rail } }; + }, + .paste => .{ .paste = try unescaped(arena, arg) }, + .exec => .{ .exec = try unescaped(arena, arg) }, + .end => .end, + }; + for (0..count) |i| try steps.append(arena, .{ .at_ms = at + @as(u32, @intCast(i)) * every, .act = act }); + } + if (steps.items.len == 0) return error.BadScript; + return steps.toOwnedSlice(arena); +} + +/// A script's key: `<c>`, `space`, `^<c>` or a pardes.Key name. +fn keyOf(word: []const u8) ?pardes.Key { + if (std.mem.eql(u8, word, "space")) return .{ .cp = ' ', .text = " " }; + if (word.len == 2 and word[0] == '^') return .{ .cp = word[1], .ctrl = true }; + if (word.len == 1) return .{ .cp = word[0], .text = word }; + inline for (@typeInfo(pardes.Key).@"struct".decl_names) |name| { + if (@TypeOf(@field(pardes.Key, name)) == u21 and std.mem.eql(u8, word, name)) return .{ .cp = @field(pardes.Key, name) }; + } + return null; +} + +/// `text` with `\n` a newline and `\\` a backslash. +fn unescaped(arena: std.mem.Allocator, text: []const u8) error{OutOfMemory}![]const u8 { + if (std.mem.indexOfScalar(u8, text, '\\') == null) return text; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < text.len) : (i += 1) { + if (text[i] == '\\' and i + 1 < text.len) { + i += 1; + try out.append(arena, if (text[i] == 'n') '\n' else text[i]); + } else try out.append(arena, text[i]); + } + return out.items; +} + +/// The script at `path` (PARDES_FRAMES_DEMO), read and parsed into `arena`. +pub fn readScript(arena: std.mem.Allocator, io: std.Io, path: []const u8) ![]Step { + return parseScript(arena, try std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 22))); +} + +test "frame stats: gaps into a motion count as jank, idle gaps do not, and the ring keeps the last frames" { + var stats: FrameStats = .{ .period_ns = 16 * std.time.ns_per_ms }; + const ms = std.time.ns_per_ms; + var t: u64 = 1000 * ms; + // An idle frame, then a second of nothing: no jank, nothing was moving. + stats.mark_start = t; + stats.mark_update = t + ms; + stats.mark_render = t + 2 * ms; + stats.record(t + 3 * ms, false, false); + t += 1000 * ms; + // A frame after the pause starts a motion; then one on time, then one + // two periods late. + for ([_]u64{ 16, 16, 33 }) |late| { + t += late * ms; + stats.mark_start = t - ms; + stats.mark_update = t - ms; + stats.mark_render = t - ms; + stats.record(t, true, false); + } + try std.testing.expectEqual(@as(u64, 1), stats.jank); + try std.testing.expectEqual(@as(u64, 4), stats.count); + const recent = stats.last(3); + try std.testing.expectEqual(@as(u32, 1_013_000), recent[0][0].gap_us); + try std.testing.expect(!recent[0][0].moving and recent[0][1].moving); + try std.testing.expectEqual(@as(u32, 33_000), recent[0][2].gap_us); + // Only the frames something moved into have a gap that counts. + const gap = Spread.of(stats.last(capacity), .gap); + try std.testing.expectEqual(@as(usize, 2), gap.n); + try std.testing.expectEqual(@as(u32, 33_000), gap.max); + // Round the ring: still the last ones, oldest first. + for (0..capacity + 5) |i| { + stats.mark_start = t; + stats.mark_update = t; + stats.mark_render = t; + t += 16 * ms; + stats.scroll = @floatFromInt(i); + stats.record(t, true, false); + } + const tail = stats.last(10); + try std.testing.expectEqual(@as(usize, 10), tail[0].len + tail[1].len); + const newest = if (tail[1].len != 0) tail[1][tail[1].len - 1] else tail[0][tail[0].len - 1]; + try std.testing.expectEqual(@as(f32, capacity + 4), newest.scroll); + // An input is answered by the next drawn frame, and only by it. + stats.input(t - 2 * ms); + stats.mark_start = t; + stats.mark_update = t; + stats.mark_render = t; + stats.record(t + 3 * ms, false, false); + try std.testing.expectEqual(@as(u32, 5000), stats.last(1)[0][0].latency_us); + stats.record(t + 4 * ms, false, false); + try std.testing.expectEqual(@as(u32, 0), stats.last(1)[0][0].latency_us); +} + +test "frame stats: the Debug box's lines hold the widest numbers, never blank" { + var stats: FrameStats = .{}; + const most = std.math.maxInt(u32); + for (&stats.ring) |*f| f.* = .{ .update_us = most, .gap_us = most, .moving = true, .latency_us = most }; + stats.count = capacity; + stats.jank = std.math.maxInt(u64); + var buf: [summary_max]u8 = undefined; + const said = stats.summary(&buf); + try std.testing.expect(std.mem.endsWith(u8, said, " ms")); + try std.testing.expect(std.mem.indexOf(u8, said, "jank 18446744073709551615\n") != null); +} + +test "frame stats: PARDES_FRAMES's long ring takes every frame, up to long_capacity" { + const long = try std.testing.allocator.create([long_capacity]Frame); + defer std.testing.allocator.destroy(long); + var stats: FrameStats = .{ .long = long }; + for (0..capacity * 3) |i| { + stats.scroll = @floatFromInt(i); + stats.record(i + 1, false, false); + } + const all = stats.last(long_capacity); + try std.testing.expectEqual(@as(usize, capacity * 3), all[0].len + all[1].len); + try std.testing.expectEqual(@as(f32, 0), all[0][0].scroll); + try std.testing.expectEqual(@as(usize, capacity), stats.last(capacity)[0].len); +} + +test "every script in tools/demos reads, its steps in time order, and ends the run" { + const io = std.testing.io; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var dir = try std.Io.Dir.cwd().openDir(io, "tools/demos", .{ .iterate = true }); + defer dir.close(io); + var it = dir.iterate(); + var scripts: usize = 0; + while (try it.next(io)) |entry| { + const steps = try parseScript(arena.allocator(), try dir.readFileAlloc(io, entry.name, arena.allocator(), .limited(1 << 22))); + try std.testing.expect(steps[steps.len - 1].act == .end); + for (steps[1..], steps[0 .. steps.len - 1]) |b, a| try std.testing.expect(b.at_ms >= a.at_ms); + scripts += 1; + } + try std.testing.expect(scripts > 0); + // A line it cannot read is refused, not skipped. + try std.testing.expectError(error.BadScript, parseScript(arena.allocator(), "100 key\n200 end\n")); + try std.testing.expectError(error.BadScript, parseScript(arena.allocator(), "# nothing\n")); + const typed = try parseScript(arena.allocator(), "10 2x5 keys a ^n\n30 paste x\\ny\n"); + try std.testing.expectEqual(@as(usize, 5), typed.len); + try std.testing.expectEqual(@as(u32, 25), typed[3].at_ms); + try std.testing.expect(typed[3].act.key.ctrl and typed[3].act.key.cp == 'n'); + try std.testing.expectEqualStrings("x\ny", typed[4].act.paste); +} |
