From c07af484b6f2688a64e850562d1f804c76c5ac52 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:53:53 -0300 Subject: anim 1: a game's frame probe, FrameStats: every drawn frame's update, render and present times, the gap since the last, jank and over-budget counters, in the Debug box and dumped by PARDES_FRAMES; PARDES_FRAMES_DEMO runs a scroll timedemo in the GUI --- src/FrameStats.zig | 327 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 327 insertions(+) create mode 100644 src/FrameStats.zig (limited to 'src/FrameStats.zig') diff --git a/src/FrameStats.zig b/src/FrameStats.zig new file mode 100644 index 00000000..74f875df --- /dev/null +++ b/src/FrameStats.zig @@ -0,0 +1,327 @@ +//! 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` +//! writes the whole ring and its summary there when the session ends. +//! +//! `PARDES_FRAMES_DEMO=scroll` runs `demo`, a timed script of scroll +//! inputs, 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("pardes.zig"); +const animation = @import("animation.zig"); + +const FrameStats = @This(); + +/// 68 s at 60 Hz: a scripted run fits whole. +/// ponytail: a fixed ring, a file-backed log if a session's whole history matters. +pub const capacity = 4096; + +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). + scroll: f32 = 0, +}; + +ring: [capacity]Frame = @splat(.{}), +/// Frames recorded since the start; the ring holds the last `capacity`. +count: u64 = 0, +/// The display's refresh period, as the shell knows it. +period_ns: u64 = animation.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). +scroll: f32 = 0, +/// The frame being timed: its marks, the monotonic clock's ns. +mark_start: u64 = 0, +mark_update: u64 = 0, +mark_render: u64 = 0, + +pub fn nowNs() u64 { + if (comptime !pardes.hosted) return 0; + 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, + }; + // 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; + stats.ring[stats.count % capacity] = 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 have: usize = @intCast(@min(stats.count, capacity)); + const take = @min(n, have); + const end: usize = @intCast(stats.count % capacity); + if (take <= end) return .{ stats.ring[end - take .. end], &.{} }; + return .{ stats.ring[capacity - (take - end) ..], stats.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 }; + + pub fn of(frames: [2][]const Frame, comptime what: What) Spread { + var values: [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, + }; + 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 and gaps, and the +/// counters since the start, in ms. +pub fn summary(stats: *const FrameStats, buf: []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); + return std.fmt.bufPrint(buf, "frame {d:.2}/{d:.2}/{d:.2} ms\ngap {d:.2}/{d:.2} ms jank {d}", .{ + @as(f64, @floatFromInt(work.p50)) / 1000, @as(f64, @floatFromInt(work.p99)) / 1000, @as(f64, @floatFromInt(work.max)) / 1000, + @as(f64, @floatFromInt(gap.p50)) / 1000, @as(f64, @floatFromInt(gap.max)) / 1000, stats.jank, + }) catch ""; +} + +/// Writes the summary and every frame the ring holds to `path`: a header +/// of `# ` lines, then one tab-separated line a frame. +pub fn dump(stats: *const FrameStats, path: [:0]const u8) void { + if (comptime !pardes.hosted) return; + 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(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 }); + } + write.line(fd, &buf, "# start_ms\tupdate_us\trender_us\tpresent_us\tgap_us\tmoving\tskipped\tscroll\n", .{}); + const t0 = if (all[0].len != 0) all[0][0].start_ns else 0; + 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}\n", .{ + @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, + }); + }; +} + +/// One input of the scroll 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, + key: pardes.Key, + /// The run is over: the session ends. + end, + }, +}; + +/// Every kind of scroll a user makes, on a long file from its top: single +/// notches, a fast spin of the wheel both ways (notches 8 ms apart, two a +/// frame: each retargets the one before), half pages, pages, the far jumps +/// to the end and back, half pages faster than they settle, and the cursor +/// moving a line, a word and, in insert mode, a column at a time. +pub const demo = blk: { + @setEvalBranchQuota(20_000); + var steps: [128]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + for (0..10) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .wheel = 1 } }; + n += 1; + t += 150; + } + t += 400; + for ([_]i8{ 1, -1 }) |dir| { + for (0..24) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .wheel = dir } }; + n += 1; + t += 8; + } + t += 800; + } + const ctrl = struct { + fn key(cp: u21) pardes.Key { + return .{ .cp = cp, .ctrl = true }; + } + }; + for ([_]u21{ 'd', 'd', 'd', 'u', 'u', 'f', 'b' }) |cp| { + steps[n] = .{ .at_ms = t, .act = .{ .key = ctrl.key(cp) } }; + n += 1; + t += 600; + } + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = 'G', .text = "G" } } }; + n += 1; + t += 800; + for (0..2) |i| { + steps[n] = .{ .at_ms = t + 20 * i, .act = .{ .key = .{ .cp = 'g', .text = "g" } } }; + n += 1; + } + t += 800; + for (0..4) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .key = ctrl.key('d') } }; + n += 1; + t += 80; + } + t += 700; + for ([_]struct { u21, []const u8, u32 }{ .{ 'j', "j", 60 }, .{ 'w', "w", 90 } }) |run| { + for (0..10) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = run[0], .text = run[1] } } }; + n += 1; + t += run[2]; + } + t += 400; + } + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = 'i', .text = "i" } } }; + n += 1; + t += 300; + for ([_]struct { u21, u32 }{ .{ pardes.Key.right, 60 }, .{ pardes.Key.down, 100 } }) |run| { + for (0..8) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = run[0] } } }; + n += 1; + t += run[1]; + } + t += 300; + } + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = pardes.Key.escape } } }; + steps[n + 1] = .{ .at_ms = t + 1000, .act = .end }; + n += 2; + const out = steps[0..n].*; + break :blk out; +}; + +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); + // The demo ends, and its steps are in time order. + try std.testing.expect(demo[demo.len - 1].act == .end); + for (demo[1..], demo[0 .. demo.len - 1]) |b, a| try std.testing.expect(b.at_ms >= a.at_ms); +} -- cgit v1.3 From 93d901ec5b80c36cb6c9d9027a8b39de5adafaca Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 14:09:45 -0300 Subject: anim 1b: the probe measures input-to-present latency, where each frame's work goes (zones: body rows and colours, the GUI's build, shaping, rasterizing, a soft present's GPU wait, upload and flip) and the view presented; timedemos for throughput (stress), every file kind of a corpus (kinds) and every kind of pane (panes) --- src/FrameStats.zig | 619 +++++++++++++++++++++++++++++++++++++++++++++++++++-- src/body_layer.zig | 6 + src/draw.zig | 2 +- src/gui/gui.zig | 118 +++++++++- src/pardes.zig | 3 +- src/tty/tty.zig | 10 + 6 files changed, 725 insertions(+), 33 deletions(-) (limited to 'src/FrameStats.zig') diff --git a/src/FrameStats.zig b/src/FrameStats.zig index 74f875df..0b252ff9 100644 --- a/src/FrameStats.zig +++ b/src/FrameStats.zig @@ -9,19 +9,25 @@ //! `Debug` shows the last second of it in its box, and `PARDES_FRAMES=path` //! writes the whole ring and its summary there when the session ends. //! -//! `PARDES_FRAMES_DEMO=scroll` runs `demo`, a timed script of scroll -//! inputs, 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. +//! 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=scroll` (or `stress`) runs a timed script of scroll +//! inputs (`named`) 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("pardes.zig"); const animation = @import("animation.zig"); const FrameStats = @This(); -/// 68 s at 60 Hz: a scripted run fits whole. -/// ponytail: a fixed ring, a file-backed log if a session's whole history matters. -pub const capacity = 4096; +/// 4.5 minutes at 60 Hz: the longest timedemo fits whole (1.3 MB). +pub const capacity = 16384; pub const Frame = struct { /// When the frame's step began, the input that woke it read: the @@ -41,8 +47,26 @@ pub const Frame = struct { /// The shell's motion in it: a scroll's picture offset from the text, /// rows (0 at rest). scroll: 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, }; +/// 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(.{}), /// Frames recorded since the start; the ring holds the last `capacity`. count: u64 = 0, @@ -57,13 +81,45 @@ armed: bool = false, jank: u64 = 0, over_budget: u64 = 0, skipped: u64 = 0, -/// What the shell sets while it draws the frame (Frame.scroll). +/// What the shell sets while it draws the frame (Frame.scroll), and the +/// pump (view). scroll: 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, +/// When the timedemo started, monotonic ns (0: none ran), and which. +demo_ns: u64 = 0, +demo_name: []const u8 = "", /// 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 { if (comptime !pardes.hosted) return 0; var ts: std.c.timespec = undefined; @@ -90,7 +146,18 @@ pub fn record(stats: *FrameStats, end_ns: u64, moving: bool, skipped: bool) void .moving = stats.armed, .skipped = skipped, .scroll = stats.scroll, + .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, }; + stats.bytes = 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; @@ -120,7 +187,7 @@ pub const Spread = struct { max: u32 = 0, mean: f64 = 0, - pub const What = enum { work, update, render, present, gap }; + pub const What = enum { work, update, render, present, gap, latency }; pub fn of(frames: [2][]const Frame, comptime what: What) Spread { var values: [capacity]u32 = undefined; @@ -133,6 +200,7 @@ pub const Spread = struct { .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; @@ -151,15 +219,20 @@ pub const Spread = struct { } }; -/// The Debug box's lines: the last second's work and gaps, and the -/// counters since the start, in ms. +/// 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: []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); - return std.fmt.bufPrint(buf, "frame {d:.2}/{d:.2}/{d:.2} ms\ngap {d:.2}/{d:.2} ms jank {d}", .{ - @as(f64, @floatFromInt(work.p50)) / 1000, @as(f64, @floatFromInt(work.p99)) / 1000, @as(f64, @floatFromInt(work.max)) / 1000, - @as(f64, @floatFromInt(gap.p50)) / 1000, @as(f64, @floatFromInt(gap.max)) / 1000, stats.jank, + const latency = Spread.of(stats.last(capacity / 16), .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 ""; } @@ -185,11 +258,21 @@ pub fn dump(stats: *const FrameStats, path: [:0]const u8) void { } write.line(fd, &buf, "# start_ms\tupdate_us\trender_us\tpresent_us\tgap_us\tmoving\tskipped\tscroll\n", .{}); const t0 = if (all[0].len != 0) all[0][0].start_ns else 0; + // The timedemo's phases, on the frames' clock. + if (stats.demo_ns != 0) if (named(stats.demo_name)) |steps| for (steps) |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\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\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}\n", .{ + write.line(fd, &buf, "{d:.3}\t{d}\t{d}\t{d}\t{d}\t{d}\t{d}\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, + @intFromBool(f.moving), @intFromBool(f.skipped), f.scroll, 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}\n", .{ f.shaped, f.rastered, f.bytes }); }; } @@ -200,6 +283,19 @@ pub const Step = struct { /// Wheel notches, down positive, as a mouse's. wheel: i8, 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, }, @@ -208,19 +304,41 @@ pub const Step = struct { /// Every kind of scroll a user makes, on a long file from its top: single /// notches, a fast spin of the wheel both ways (notches 8 ms apart, two a /// frame: each retargets the one before), half pages, pages, the far jumps -/// to the end and back, half pages faster than they settle, and the cursor +/// to the end (ge) and back (gg), half pages faster than they settle, and the cursor /// moving a line, a word and, in insert mode, a column at a time. +/// The timedemo PARDES_FRAMES_DEMO names, if any. +pub fn named(name: []const u8) ?[]const Step { + if (std.mem.eql(u8, name, "scroll")) return &demo; + if (std.mem.eql(u8, name, "stress")) return &stress; + if (std.mem.eql(u8, name, "kinds")) return &kinds; + if (std.mem.eql(u8, name, "panes")) return &panes; + if (std.mem.eql(u8, name, "one")) return &one; + if (std.mem.eql(u8, name, "jumps")) return &jumps; + if (std.mem.eql(u8, name, "longlines")) return &longlines; + if (std.mem.eql(u8, name, "clip-flick")) return &clip_flick; + if (std.mem.eql(u8, name, "clip-far")) return &clip_far; + if (std.mem.eql(u8, name, "clip-cursor")) return &clip_cursor; + if (std.mem.eql(u8, name, "clip-query")) return &clip_query; + if (std.mem.eql(u8, name, "clip-terminal")) return &clip_terminal; + if (std.mem.eql(u8, name, "clip-pages")) return &clip_pages; + return null; +} + pub const demo = blk: { @setEvalBranchQuota(20_000); var steps: [128]Step = undefined; var n: usize = 0; var t: u32 = 1500; + steps[n] = .{ .at_ms = t, .act = .{ .phase = "notches" } }; + n += 1; for (0..10) |_| { steps[n] = .{ .at_ms = t, .act = .{ .wheel = 1 } }; n += 1; t += 150; } t += 400; + steps[n] = .{ .at_ms = t, .act = .{ .phase = "spin" } }; + n += 1; for ([_]i8{ 1, -1 }) |dir| { for (0..24) |_| { steps[n] = .{ .at_ms = t, .act = .{ .wheel = dir } }; @@ -234,25 +352,33 @@ pub const demo = blk: { return .{ .cp = cp, .ctrl = true }; } }; + steps[n] = .{ .at_ms = t, .act = .{ .phase = "pages" } }; + n += 1; for ([_]u21{ 'd', 'd', 'd', 'u', 'u', 'f', 'b' }) |cp| { steps[n] = .{ .at_ms = t, .act = .{ .key = ctrl.key(cp) } }; n += 1; t += 600; } - steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = 'G', .text = "G" } } }; - n += 1; + for ([_]u21{ 'g', 'e' }, [_][]const u8{ "g", "e" }, 0..) |cp, text, i| { + steps[n] = .{ .at_ms = t + 20 * i, .act = .{ .key = .{ .cp = cp, .text = text } } }; + n += 1; + } t += 800; for (0..2) |i| { steps[n] = .{ .at_ms = t + 20 * i, .act = .{ .key = .{ .cp = 'g', .text = "g" } } }; n += 1; } t += 800; + steps[n] = .{ .at_ms = t, .act = .{ .phase = "retarget" } }; + n += 1; for (0..4) |_| { steps[n] = .{ .at_ms = t, .act = .{ .key = ctrl.key('d') } }; n += 1; t += 80; } t += 700; + steps[n] = .{ .at_ms = t, .act = .{ .phase = "cursor" } }; + n += 1; for ([_]struct { u21, []const u8, u32 }{ .{ 'j', "j", 60 }, .{ 'w', "w", 90 } }) |run| { for (0..10) |_| { steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = run[0], .text = run[1] } } }; @@ -279,6 +405,444 @@ pub const demo = blk: { break :blk out; }; +/// The scrolls every kind of text and pane is put through (`kinds`, +/// `panes`), from `t`: notches, a spin, half pages, PageDown held, the far +/// jumps, the cursor down a held j. 7.5 s. +fn scrollSet(steps: []Step, n: *usize, t: *u32) void { + const at = struct { + fn add(s: []Step, k: *usize, ms: u32, act: @FieldType(Step, "act")) void { + s[k.*] = .{ .at_ms = ms, .act = act }; + k.* += 1; + } + }; + for (0..6) |_| { + at.add(steps, n, t.*, .{ .wheel = 1 }); + t.* += 150; + } + for (0..100) |_| { + at.add(steps, n, t.*, .{ .wheel = 1 }); + t.* += 8; + } + t.* += 500; + for (0..3) |_| { + at.add(steps, n, t.*, .{ .key = .{ .cp = 'd', .ctrl = true } }); + t.* += 400; + } + for (0..45) |_| { + at.add(steps, n, t.*, .{ .key = .{ .cp = pardes.Key.page_down } }); + t.* += 33; + } + t.* += 400; + for ([_][]const u8{ "e", "g" }) |second| { + at.add(steps, n, t.*, .{ .key = .{ .cp = 'g', .text = "g" } }); + at.add(steps, n, t.* + 20, .{ .key = .{ .cp = second[0], .text = second } }); + t.* += 600; + } + for (0..30) |_| { + at.add(steps, n, t.*, .{ .key = .{ .cp = 'j', .text = "j" } }); + t.* += 33; + } + t.* += 500; +} + +/// `scrollSet` alone, on the file the session opened: one kind, for a +/// profiler's run. +pub const one = blk: { + @setEvalBranchQuota(20_000); + var steps: [512]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + steps[n] = .{ .at_ms = t, .act = .{ .phase = "one" } }; + n += 1; + scrollSet(&steps, &n, &t); + steps[n] = .{ .at_ms = t, .act = .end }; + n += 1; + const out = steps[0..n].*; + break :blk out; +}; + +/// The samples' scenes (docs/next-anim.md), a few seconds each, recorded +/// with PARDES_FRAMES_CAPTURE: a wheel spun hard; Ctrl-d held then ge and +/// gg; j held then the thin caret typing and arrowing; a `/` typed and its +/// places stepped with Ctrl-n; a command's output then the wheel over it; +/// Ctrl-f a page at a time. +fn clipSteps(comptime which: usize, steps: *[256]Step) usize { + @setEvalBranchQuota(100_000); + var n: usize = 0; + var t: u32 = 1200; + const add = struct { + fn step(s: []Step, k: *usize, at: *u32, gap: u32, act: @FieldType(Step, "act")) void { + s[k.*] = .{ .at_ms = at.*, .act = act }; + k.* += 1; + at.* += gap; + } + }; + switch (which) { + 0 => for (0..150) |_| add.step(steps, &n, &t, 12, .{ .wheel = 1 }), + 1 => { + for (0..36) |_| add.step(steps, &n, &t, 33, .{ .key = .{ .cp = 'd', .ctrl = true } }); + t += 600; + add.step(steps, &n, &t, 20, .{ .key = .{ .cp = 'g', .text = "g" } }); + add.step(steps, &n, &t, 900, .{ .key = .{ .cp = 'e', .text = "e" } }); + add.step(steps, &n, &t, 20, .{ .key = .{ .cp = 'g', .text = "g" } }); + add.step(steps, &n, &t, 900, .{ .key = .{ .cp = 'g', .text = "g" } }); + }, + 2 => { + for (0..45) |_| add.step(steps, &n, &t, 33, .{ .key = .{ .cp = 'j', .text = "j" } }); + t += 300; + add.step(steps, &n, &t, 300, .{ .key = .{ .cp = 'i', .text = "i" } }); + for ("the quick brown fox jumps") |ch| add.step(steps, &n, &t, 60, .{ .key = .{ .cp = ch, .text = &.{ch} } }); + for (0..10) |_| add.step(steps, &n, &t, 70, .{ .key = .{ .cp = pardes.Key.left } }); + for (0..4) |_| add.step(steps, &n, &t, 90, .{ .key = .{ .cp = pardes.Key.up } }); + add.step(steps, &n, &t, 400, .{ .key = .{ .cp = pardes.Key.escape } }); + }, + 3 => { + for ("/pane.") |ch| add.step(steps, &n, &t, 180, .{ .key = .{ .cp = ch, .text = &.{ch} } }); + t += 300; + for (0..8) |_| add.step(steps, &n, &t, 300, .{ .key = .{ .cp = 'n', .ctrl = true } }); + }, + 4 => { + add.step(steps, &n, &t, 1800, .{ .exec = "cat stress.zig" }); + for (0..60) |_| add.step(steps, &n, &t, 16, .{ .wheel = -1 }); + t += 400; + for (0..12) |_| add.step(steps, &n, &t, 150, .{ .wheel = 1 }); + }, + else => for (0..8) |_| add.step(steps, &n, &t, 450, .{ .key = .{ .cp = 'f', .ctrl = true } }), + } + t += 800; + add.step(steps, &n, &t, 0, .end); + return n; +} + +const clip_flick = blk: { + var steps: [256]Step = undefined; + const n = clipSteps(0, &steps); + const out = steps[0..n].*; + break :blk out; +}; +const clip_far = blk: { + var steps: [256]Step = undefined; + const n = clipSteps(1, &steps); + const out = steps[0..n].*; + break :blk out; +}; +const clip_cursor = blk: { + var steps: [256]Step = undefined; + const n = clipSteps(2, &steps); + const out = steps[0..n].*; + break :blk out; +}; +const clip_query = blk: { + var steps: [256]Step = undefined; + const n = clipSteps(3, &steps); + const out = steps[0..n].*; + break :blk out; +}; +const clip_terminal = blk: { + var steps: [256]Step = undefined; + const n = clipSteps(4, &steps); + const out = steps[0..n].*; + break :blk out; +}; +const clip_pages = blk: { + var steps: [256]Step = undefined; + const n = clipSteps(5, &steps); + const out = steps[0..n].*; + break :blk out; +}; + +/// The cursor along long lines (a minified JS, a one-line JSON, six 360 KB +/// lines), Wrap on and then off (off, the view scrolls sideways): w and e +/// held, l held, $ and 0, f and t, gl and gh, typing at a line's end and in +/// its middle, a selection swept with held L and W. +pub const longlines = blk: { + @setEvalBranchQuota(1_000_000); + var steps: [8192]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + const add = struct { + fn step(s: []Step, k: *usize, at: *u32, gap: u32, act: @FieldType(Step, "act")) void { + s[k.*] = .{ .at_ms = at.*, .act = act }; + k.* += 1; + at.* += gap; + } + fn keys(s: []Step, k: *usize, at: *u32, gap: u32, text: []const u8, times: usize) void { + for (0..times) |_| for (text, 0..) |_, i| step(s, k, at, gap, .{ .key = .{ .cp = text[i], .text = text[i .. i + 1] } }); + } + }; + for ([_][]const u8{ "wrap", "nowrap" }) |mode| { + if (std.mem.eql(u8, mode, "nowrap")) add.step(&steps, &n, &t, 300, .{ .exec = "Wrap" }); + for ([_][]const u8{ "minified.js", "oneline.json", "hugelines.txt" }) |file| { + add.step(&steps, &n, &t, 1500, .{ .exec = "Look kinds/" ++ file }); + const tag = file ++ "-" ++ mode; + add.keys(&steps, &n, &t, 400, "gg", 1); + add.step(&steps, &n, &t, 0, .{ .phase = "w-held-" ++ tag }); + add.keys(&steps, &n, &t, 33, "w", 60); + add.step(&steps, &n, &t, 0, .{ .phase = "e-held-" ++ tag }); + add.keys(&steps, &n, &t, 33, "e", 60); + add.step(&steps, &n, &t, 0, .{ .phase = "l-held-" ++ tag }); + add.keys(&steps, &n, &t, 33, "l", 90); + add.step(&steps, &n, &t, 0, .{ .phase = "dollar-zero-" ++ tag }); + add.keys(&steps, &n, &t, 600, "$0", 2); + add.step(&steps, &n, &t, 0, .{ .phase = "f-t-" ++ tag }); + add.keys(&steps, &n, &t, 150, "f,", 8); + add.keys(&steps, &n, &t, 150, "t ", 8); + add.step(&steps, &n, &t, 0, .{ .phase = "gl-gh-" ++ tag }); + add.keys(&steps, &n, &t, 500, "glgh", 3); + add.step(&steps, &n, &t, 0, .{ .phase = "insert-end-" ++ tag }); + add.keys(&steps, &n, &t, 300, "$a", 1); + add.keys(&steps, &n, &t, 45, "typed at the end ", 2); + add.step(&steps, &n, &t, 300, .{ .key = .{ .cp = pardes.Key.escape } }); + add.step(&steps, &n, &t, 0, .{ .phase = "insert-middle-" ++ tag }); + add.keys(&steps, &n, &t, 40, "0", 1); + add.keys(&steps, &n, &t, 40, "40000l", 1); + add.keys(&steps, &n, &t, 300, "i", 1); + add.keys(&steps, &n, &t, 45, "typed in the middle ", 2); + add.step(&steps, &n, &t, 300, .{ .key = .{ .cp = pardes.Key.escape } }); + add.step(&steps, &n, &t, 0, .{ .phase = "sweep-L-W-" ++ tag }); + add.keys(&steps, &n, &t, 33, "L", 40); + add.keys(&steps, &n, &t, 33, "W", 30); + // Del twice: the second throws the typing away. + add.step(&steps, &n, &t, 300, .{ .exec = "Del" }); + add.step(&steps, &n, &t, 600, .{ .exec = "Del" }); + } + } + add.step(&steps, &n, &t, 0, .end); + const out = steps[0..n].*; + break :blk out; +}; + +/// What insert mode's paste pastes: 200 lines. +const pasted = blk: { + const line = "a pasted line, one of two hundred\n"; + var out: [line.len * 200]u8 = undefined; + for (0..200) |i| @memcpy(out[i * line.len ..][0..line.len], line); + break :blk out; +}; + +/// Every other way a view moves, each its own phase, on the session's file +/// (a big one) and then on a small one: the counted jumps (12G, 9000G, gg), +/// the upward pages, a search's n/N, a query's Ctrl-n moving its owner's +/// view, `*`, Looks at `:40`, at a far line and at another file (a new +/// pane: nothing to glide from), the jumplist both ways, the rail's +/// buttons and the wheel over it, and insert mode: typing, arrows, Enter at +/// the bottom of the view, a 200-line paste. +pub const jumps = blk: { + @setEvalBranchQuota(400_000); + var steps: [2048]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + const add = struct { + fn step(s: []Step, k: *usize, at: *u32, gap: u32, act: @FieldType(Step, "act")) void { + s[k.*] = .{ .at_ms = at.*, .act = act }; + k.* += 1; + at.* += gap; + } + fn text(s: []Step, k: *usize, at: *u32, gap: u32, keys: []const u8) void { + for (keys, 0..) |_, i| step(s, k, at, gap, .{ .key = .{ .cp = keys[i], .text = keys[i .. i + 1] } }); + } + fn key(s: []Step, k: *usize, at: *u32, gap: u32, cp: u21, ctrl: bool, times: usize) void { + for (0..times) |_| step(s, k, at, gap, .{ .key = .{ .cp = cp, .ctrl = ctrl } }); + } + }; + for ([_][]const u8{ "big", "small" }) |size| { + if (std.mem.eql(u8, size, "small")) add.step(&steps, &n, &t, 1200, .{ .exec = "Look kinds/guide.typ" }); + add.step(&steps, &n, &t, 0, .{ .phase = "counted-G-" ++ size }); + for ([_][]const u8{ "12G", "300G", "9000G", "gg", "ge", "gg" }) |keys| { + add.text(&steps, &n, &t, 20, keys); + t += 700; + } + add.step(&steps, &n, &t, 0, .{ .phase = "pages-up-" ++ size }); + add.text(&steps, &n, &t, 700, "ge"); + add.key(&steps, &n, &t, 500, 'u', true, 3); + add.key(&steps, &n, &t, 500, 'b', true, 3); + add.key(&steps, &n, &t, 500, pardes.Key.page_up, false, 3); + add.step(&steps, &n, &t, 0, .{ .phase = "search-n-" ++ size }); + add.text(&steps, &n, &t, 700, "gg"); + add.text(&steps, &n, &t, 120, "/const "); + add.key(&steps, &n, &t, 600, pardes.Key.enter, false, 1); + add.text(&steps, &n, &t, 400, "nnnnnnNNNNNN"); + add.step(&steps, &n, &t, 0, .{ .phase = "rail-" ++ size }); + add.text(&steps, &n, &t, 700, "ge"); + for ([_]pardes.Mouse.Button{ .left, .left, .right, .right, .middle }, [_]f32{ 0.8, 0.3, 0.6, 0.9, 0.5 }) |button, at| + add.step(&steps, &n, &t, 600, .{ .click = .{ .button = button, .at = at, .rail = true } }); + for (0..8) |_| add.step(&steps, &n, &t, 120, .{ .rail_wheel = 1 }); + t += 500; + add.step(&steps, &n, &t, 0, .{ .phase = "query-ctrl-n-" ++ size }); + add.text(&steps, &n, &t, 120, "/pub fn"); + add.key(&steps, &n, &t, 250, 'n', true, 8); + add.key(&steps, &n, &t, 250, 'p', true, 4); + add.key(&steps, &n, &t, 700, pardes.Key.escape, false, 1); + add.step(&steps, &n, &t, 0, .{ .phase = "star-" ++ size }); + add.text(&steps, &n, &t, 300, "ggww*"); + add.text(&steps, &n, &t, 500, "nnnn"); + add.step(&steps, &n, &t, 0, .{ .phase = "look-" ++ size }); + add.step(&steps, &n, &t, 900, .{ .exec = "Look :40" }); + add.step(&steps, &n, &t, 900, .{ .exec = "Look :7000" }); + add.step(&steps, &n, &t, 900, .{ .exec = "Look :200" }); + add.step(&steps, &n, &t, 0, .{ .phase = "jumplist-" ++ size }); + add.key(&steps, &n, &t, 600, 'o', true, 3); + add.key(&steps, &n, &t, 600, 'i', true, 3); + add.text(&steps, &n, &t, 40, " jo"); + t += 600; + add.text(&steps, &n, &t, 40, " ji"); + t += 600; + add.step(&steps, &n, &t, 0, .{ .phase = "insert-" ++ size }); + add.text(&steps, &n, &t, 300, "ggi"); + for (0..4) |_| add.text(&steps, &n, &t, 45, "the quick brown fox "); + add.key(&steps, &n, &t, 60, pardes.Key.left, false, 12); + add.key(&steps, &n, &t, 60, pardes.Key.right, false, 12); + add.key(&steps, &n, &t, 60, pardes.Key.down, false, 6); + // Enter after Enter until the view has to follow, a line at a time. + add.key(&steps, &n, &t, 70, pardes.Key.enter, false, 60); + add.step(&steps, &n, &t, 600, .{ .paste = &pasted }); + add.key(&steps, &n, &t, 700, pardes.Key.escape, false, 1); + } + add.step(&steps, &n, &t, 0, .{ .phase = "look-new-pane" }); + add.step(&steps, &n, &t, 1500, .{ .exec = "Look ../../src/layout.zig:9000" }); + add.step(&steps, &n, &t, 0, .end); + const out = steps[0..n].*; + break :blk out; +}; + +/// Each file of the corpus (`.scratch/tools/corpus.sh`) is opened by name, +/// relative to the first file's directory, and put through `scrollSet`; +/// the long-line ones a second time with Wrap off. +pub const kinds = blk: { + @setEvalBranchQuota(200_000); + var steps: [4096]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + const files = [_][]const u8{ "generated-parser.c", "commands.rs", "tables.py", "jquery.js", "minified.js", "grammar.json", "oneline.json", "CHANGELOG.md", "cascade.html", "simdutf.cpp", "parser.ts", "fcnal-test.sh", "data.go", "guide.typ", "unicode.txt", "big.log", "words.txt", "hugelines.txt" }; + for (files ++ [_][]const u8{ "minified.js!", "oneline.json!", "hugelines.txt!" }) |file| { + const unwrapped = file[file.len - 1] == '!'; + const name = if (unwrapped) file[0 .. file.len - 1] else file; + // Wrap goes off once, before the second round. + if (unwrapped and std.mem.eql(u8, name, "minified.js")) { + steps[n] = .{ .at_ms = t, .act = .{ .exec = "Wrap" } }; + n += 1; + t += 200; + } + steps[n] = .{ .at_ms = t, .act = .{ .exec = "Look kinds/" ++ name } }; + n += 1; + t += 1200; + steps[n] = .{ .at_ms = t, .act = .{ .phase = file } }; + n += 1; + scrollSet(&steps, &n, &t); + steps[n] = .{ .at_ms = t, .act = .{ .exec = "Del" } }; + n += 1; + t += 400; + } + steps[n] = .{ .at_ms = t, .act = .end }; + n += 1; + const out = steps[0..n].*; + break :blk out; +}; + +/// The other kinds of pane, opened from the first file's directory, each +/// put through `scrollSet`: a command's fast output (the stress file, then +/// `yes`), a +Pager, a directory, a PDF, a picture, Help's output pane, a +/// +Diff, and the query pane typed into (its rows refilled each key, its +/// owner's places drawn). +pub const panes = blk: { + @setEvalBranchQuota(200_000); + var steps: [4096]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + const Kind = struct { name: []const u8, open: []const u8, settle: u32 }; + for ([_]Kind{ + .{ .name = "command-cat", .open = "cat stress.zig", .settle = 300 }, + .{ .name = "command-yes", .open = "yes | head -200000", .settle = 300 }, + .{ .name = "pager", .open = "cat stress.zig | pardes -", .settle = 2500 }, + .{ .name = "directory", .open = "Look kinds/", .settle = 1200 }, + .{ .name = "pdf", .open = "Look ../../docs/design.pdf", .settle = 2000 }, + .{ .name = "image", .open = "Look ../../docs/screenshots/atelier.png", .settle = 1200 }, + .{ .name = "help", .open = "Help", .settle = 1200 }, + .{ .name = "changelog", .open = "Changelog", .settle = 1200 }, + }) |kind| { + steps[n] = .{ .at_ms = t, .act = .{ .phase = kind.name } }; + n += 1; + steps[n] = .{ .at_ms = t, .act = .{ .exec = kind.open } }; + n += 1; + // A command's output streams in while it is scrolled. + t += kind.settle; + scrollSet(&steps, &n, &t); + steps[n] = .{ .at_ms = t, .act = .{ .exec = "Del" } }; + n += 1; + t += 600; + } + steps[n] = .{ .at_ms = t, .act = .{ .phase = "query-typing" } }; + n += 1; + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = '/', .text = "/" } } }; + n += 1; + t += 300; + for ("pane.vie") |ch| { + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = ch, .text = &.{ch} } } }; + n += 1; + t += 150; + } + for (0..12) |_| { + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = 'n', .ctrl = true } } }; + n += 1; + t += 120; + } + steps[n] = .{ .at_ms = t, .act = .{ .key = .{ .cp = pardes.Key.escape } } }; + n += 1; + t += 800; + steps[n] = .{ .at_ms = t, .act = .end }; + n += 1; + const out = steps[0..n].*; + break :blk out; +}; + +/// Throughput on a big file (layout.zig x23, 30k lines): each input held +/// for three seconds at a keyboard's repeat (33 ms) or a wheel spun hard (a +/// notch every 8 ms), so the picture has to keep up with more than it can +/// show: a spin, held Ctrl-d, held j, held PageDown, then the far jumps. +pub const stress = blk: { + @setEvalBranchQuota(100_000); + var steps: [1024]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + const Held = struct { name: []const u8, key: ?pardes.Key, every: u32 }; + for ([_]Held{ + .{ .name = "spin", .key = null, .every = 8 }, + .{ .name = "held-ctrl-d", .key = .{ .cp = 'd', .ctrl = true }, .every = 33 }, + .{ .name = "held-j", .key = .{ .cp = 'j', .text = "j" }, .every = 33 }, + .{ .name = "held-pagedown", .key = .{ .cp = pardes.Key.page_down }, .every = 33 }, + }) |held| { + // Each from the top. + for ([_]u32{ 0, 20 }) |dt| { + steps[n] = .{ .at_ms = t + dt, .act = .{ .key = .{ .cp = 'g', .text = "g" } } }; + n += 1; + } + t += 800; + steps[n] = .{ .at_ms = t, .act = .{ .phase = held.name } }; + n += 1; + const end = t + 3000; + while (t < end) : (t += held.every) { + steps[n] = .{ .at_ms = t, .act = if (held.key) |key| .{ .key = key } else .{ .wheel = 1 } }; + n += 1; + } + t += 1000; + } + steps[n] = .{ .at_ms = t, .act = .{ .phase = "far" } }; + n += 1; + for (0..3) |_| { + for ([_][]const u8{ "e", "g" }) |second| { + for ([_][]const u8{ "g", second }, 0..) |text, i| { + steps[n] = .{ .at_ms = t + 20 * @as(u32, i), .act = .{ .key = .{ .cp = text[0], .text = text } } }; + n += 1; + } + t += 700; + } + } + steps[n] = .{ .at_ms = t + 500, .act = .end }; + n += 1; + const out = steps[0..n].*; + break :blk out; +}; + 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; @@ -321,7 +885,18 @@ test "frame stats: gaps into a motion count as jank, idle gaps do not, and the r 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); - // The demo ends, and its steps are in time order. - try std.testing.expect(demo[demo.len - 1].act == .end); - for (demo[1..], demo[0 .. demo.len - 1]) |b, a| try std.testing.expect(b.at_ms >= a.at_ms); + // Each timedemo ends, and its steps are in time order. + for ([_][]const Step{ &demo, &stress, &kinds, &panes, &one, &jumps, &longlines }) |steps| { + 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); + } + // 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); } diff --git a/src/body_layer.zig b/src/body_layer.zig index 3684605f..d4ca6d69 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -255,7 +255,9 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane .bg = pane_bg, }; const tz_body = tracy.zone(@src(), "bodyText"); + const probe_text = pardes.FrameStats.nowNs(); const body = built orelse try bodyText(p, arena, pane); + p.frames.zone(.body_text, probe_text); tz_body.end(); // A select sweep begun on the tag and dragged into the body marks the // body rows it crossed only where no text is: it is laid down before @@ -268,6 +270,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // this is what writes it into the surface. const tz_rows = tracy.zone(@src(), "paneBodyRows"); defer tz_rows.end(); + const probe_rows = pardes.FrameStats.nowNs(); + defer p.frames.zone(.body_rows, probe_rows); var it = std.mem.splitScalar(u8, body, '\n'); var i: u16 = 0; while (it.next()) |line| : (i += 1) { @@ -277,6 +281,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane } const tz_color = tracy.zone(@src(), "paneRecolor"); + const probe_color = pardes.FrameStats.nowNs(); + defer p.frames.zone(.body_color, probe_color); // File layout is independent of whether its producer requests colors. if (pane.file) |*f| { panes.File.drawGutter(p, s, pane, r, tx, tw, body_h, active); diff --git a/src/draw.zig b/src/draw.zig index b4fc3a2c..3ba5801f 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -756,7 +756,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { // wide enough for the longest theme name compiled in, which is the // only row here whose width is not ours to choose const ow: u16 = 38; - const oh: u16 = 12; + const oh: u16 = 13; const ox: u16 = if (s.cols > ow) s.cols - ow else 0; if (ox + ow <= s.cols and p.topBarHeight() + oh <= s.rows) { s.addRegion(.{ .kind = .debug, .rect = .{ .x = ox, .y = p.topBarHeight(), .w = ow, .h = oh } }); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 125f53cf..0a3f3340 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1475,8 +1475,10 @@ const Gui = struct { /// owns the wheel (terminal.ownsWheel). program_wheel: f32 = 0, glide: Glide = .{}, - /// PARDES_FRAMES_DEMO: the scroll timedemo's next step and when it - /// started (FrameStats.demo); null when none runs. + /// PARDES_FRAMES_DEMO: the timedemo (FrameStats.named), its next step + /// and when it started; null when none runs. + demo: []const pardes.FrameStats.Step = &.{}, + demo_name: []const u8 = "", demo_next: ?usize = null, demo_start_ns: u64 = 0, /// G9 and G11: the selection's and the hovered word's glow blocks as @@ -2160,7 +2162,9 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, .capture_dir = capture_dir orelse "", .soft_present = soft_present, - .demo_next = if (env.get("PARDES_FRAMES_DEMO") != null) 0 else null, + .demo = if (env.get("PARDES_FRAMES_DEMO")) |name| pardes.FrameStats.named(name) orelse &.{} else &.{}, + .demo_name = env.get("PARDES_FRAMES_DEMO") orelse "", + .demo_next = if (env.get("PARDES_FRAMES_DEMO")) |name| (if (pardes.FrameStats.named(name) != null) @as(?usize, 0) else null) else null, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, }; @@ -2323,6 +2327,8 @@ fn localSession( defer shell.shaders.deinit(gpa, inotify_fd, &watches); // A virtual clock never blinks: goldens and feel series hold still. g.no_blink = shell.test_clock != null; + frame_probe = &core.frames; + frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; const host = shell.host(); core.host = host; @@ -3128,6 +3134,13 @@ const Input = struct { }; fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { + // An input's time, for its latency to the frame that answers it + // (FrameStats): SDL's stamp, moved onto the monotonic clock. + switch (sev.type) { + c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_WHEEL => if (frame_probe) |probe| + probe.input(monoNs() -| (c.SDL_GetTicksNS() -| sev.common.timestamp)), + else => {}, + } // What the post chain sees of the pointer and the focus. switch (sev.type) { c.SDL_EVENT_MOUSE_MOTION => { @@ -4202,11 +4215,36 @@ fn pollFrame(ctx: ?*anyopaque) void { /// Frames drawn for a blink alone, with no core render (tests, tracing). var blink_redraws: u64 = 0; +/// PARDES_FRAMES_CAPTURE's directory, and how many frames it has. +var frame_capture_dir: ?[]const u8 = null; +var frame_capture_count: u32 = 0; + +fn captureSeries(dir: []const u8, pixels: []const u8, w: u32, h: u32) void { + var path_buf: [4096]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{d:0>6}.bgra", .{ dir, frame_capture_count }, 0) catch return; + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return; + _ = libc.write(fd, pixels.ptr, pixels.len); + _ = libc.close(fd); + const times = std.fmt.bufPrintSentinel(&path_buf, "{s}/times.txt", .{dir}, 0) catch return; + const tf = libc.open(times, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, @as(libc.mode_t, 0o644)); + if (tf < 0) return; + var line_buf: [96]u8 = undefined; + const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}\n", .{ frame_capture_count, monoNs(), w, h }) catch ""; + _ = libc.write(tf, line.ptr, line.len); + _ = libc.close(tf); + frame_capture_count += 1; +} + +/// The core's frame probe (FrameStats), for the latency of the inputs the +/// shell reads and the zones its own work goes in; null in tests. +var frame_probe: ?*pardes.FrameStats = null; + /// How long until the timedemo's next step, ms; null when none runs. fn demoDue(g: *const Gui) ?c_int { const next = g.demo_next orelse return null; - if (g.demo_start_ns == 0 or next >= pardes.FrameStats.demo.len) return 0; - const at = g.demo_start_ns + @as(u64, pardes.FrameStats.demo[next].at_ms) * std.time.ns_per_ms; + if (g.demo_start_ns == 0 or next >= g.demo.len) return 0; + const at = g.demo_start_ns + @as(u64, g.demo[next].at_ms) * std.time.ns_per_ms; return @intCast(@min(std.math.maxInt(c_int), (at -| monoNs()) / std.time.ns_per_ms)); } @@ -4215,16 +4253,56 @@ fn demoDue(g: *const Gui) ?c_int { /// focused pane's body; its clock starts at the first loop. Its end /// ends the session (PARDES_FRAMES has the timings then). fn runDemo(g: *Gui, in: *Input, core: *pardes.Pardes) void { - const steps = pardes.FrameStats.demo; + const steps = g.demo; var next = g.demo_next orelse return; const now = monoNs(); - if (g.demo_start_ns == 0) g.demo_start_ns = now; + if (g.demo_start_ns == 0) { + g.demo_start_ns = now; + core.frames.demo_ns = now; + core.frames.demo_name = g.demo_name; + } defer g.demo_next = next; while (next < steps.len and g.demo_start_ns + @as(u64, steps[next].at_ms) * std.time.ns_per_ms <= now) : (next += 1) { const r = core.rects[core.active]; switch (steps[next].act) { - .wheel => |notches| wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }), - .key => |key| in.post(.{ .key = key }), + .wheel => |notches| { + core.frames.input(now); + wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); + }, + .key => |key| { + core.frames.input(now); + in.post(.{ .key = key }); + }, + .phase => {}, + .click => |click| { + core.frames.input(now); + const pane = core.panes[core.active] orelse continue; + const top = core.bodyTop(pane, r); + const row: u16 = top + @as(u16, @intFromFloat(click.at * @as(f32, @floatFromInt(r.h -| pane.tag_rows -| 1)))); + const col: u16 = if (click.rail) r.x else r.x + config.GUTTER + 4; + for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| in.post(.{ .mouse = .{ .button = click.button, .kind = kind, .col = col, .row = row } }); + }, + .rail_wheel => |notches| { + core.frames.input(now); + wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x, .row = r.y + r.h / 2 }); + }, + .paste => |text| { + core.frames.input(now); + in.post(.{ .paste = text }); + }, + .exec => |line| { + core.frames.input(now); + var newest: u32 = 0; + for (core.panes) |slot| if (slot) |pane| { + newest = @max(newest, pane.serial); + }; + _ = pardes.exec.executeFrom(core, core.active, line, false); + // What it opened is what the next steps scroll. + for (core.panes, 0..) |slot, id| if (slot) |pane| if (pane.serial > newest) { + core.active = id; + core.needs_frame = true; + }; + }, .end => in.close(), } } @@ -5922,6 +6000,7 @@ fn renderFrame( // The frame's CPU side: groups, decor, cover and every instance, up to // their upload. const build_zone = tracy.zone(@src(), "gui frame build"); + const probe_build = monoNs(); var building = true; defer if (building) build_zone.end(); const layout = fixedCellLayout(g); @@ -6265,6 +6344,7 @@ fn renderFrame( build_zone.end(); building = false; + if (frame_probe) |probe| probe.zone(.gui_build, probe_build); const rp = c.SDL_BeginGPURenderPass(cmd, &color_target, 1, null); pushLayerOpacity(cmd, rp, background_opacity); const whole = c.SDL_Rect{ .x = 0, .y = 0, .w = @intCast(sw), .h = @intCast(sh) }; @@ -7572,6 +7652,11 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: // A new word (a hash collision takes the map entry over). Runs of one // face are shaped in that face; fallback faces shape like the primary. + const probe_shape = monoNs(); + defer if (frame_probe) |probe| { + probe.zone(.gui_shape, probe_shape); + probe.shaped +|= 1; + }; const n = text.len; words.slots.ensureUnusedCapacity(gpa, n) catch { words.text.shrinkRetainingCapacity(text_start); @@ -7769,6 +7854,11 @@ fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { g.pen_y += g.cell_h; } if (g.pen_y + g.cell_h > atlas_h) return null; // atlas full: fall back + const probe_raster = monoNs(); + defer if (frame_probe) |probe| { + probe.zone(.gui_raster, probe_raster); + probe.rastered +|= 1; + }; const s = Slot{ .u = g.pen_x, .v = g.pen_y }; const out = g.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u; const face = if (key.face == 0) g.font else g.fallbacks[key.face - 1].?.face; @@ -8367,21 +8457,31 @@ fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTex const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; defer c.SDL_ReleaseGPUFence(g.device, fence); var fences = [_]*c.SDL_GPUFence{fence}; + const probe_wait = monoNs(); if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit; + if (frame_probe) |probe| probe.zone(.gui_wait, probe_wait); const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap; defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer); const texture = try ensureSoftTexture(g, sw, sh); const renderer = g.soft_renderer orelse return error.GpuCreate; + const probe_upload = monoNs(); + defer if (frame_probe) |probe| probe.zone(.gui_upload, probe_upload); if (!c.SDL_UpdateTexture(texture, null, mapped, @intCast(sw * bpp))) return error.GpuMap; + // PARDES_FRAMES_CAPTURE: every presented frame's pixels as they went + // out, and when, for a recording at the frames' own times (the + // samples of docs/next-anim.md). One write a frame; nothing else. + if (frame_capture_dir) |dir| captureSeries(dir, @as([*]const u8, @ptrCast(mapped))[0..size], sw, sh); // The cell shader already produced premultiplied backgrounds with opaque // foreground ink. Copy that alpha unchanged; never modulate the full frame. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255); _ = c.SDL_RenderClear(renderer); _ = c.SDL_RenderTexture(renderer, texture, null, null); + const probe_flip = monoNs(); _ = c.SDL_RenderPresent(renderer); + if (frame_probe) |probe| probe.zone(.gui_flip, probe_flip); } fn backgroundOpacity(percent: u8) f32 { diff --git a/src/pardes.zig b/src/pardes.zig index 22b43a51..df6d347f 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5968,13 +5968,14 @@ pub const Pardes = struct { // rendering and nothing else. // A shell with a clock draws what `advance` stepped; one without // steps its own `.tick`s and draws while anything animates. - if (!p.needs_frame and !p.continuous() and (v.now != null or !p.animationActive())) return; + if (!p.needs_frame and !p.continuous() and (v.now != null or !p.animationActive())) return p.frames.idle(); // No one to see it: the frame stays owed (needs_frame), not drawn. // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. if (v.watched) |f| if (!f(h.ctx)) return; _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); p.frames.mark_update = FrameStats.nowNs(); + p.frames.view = if (p.panes[p.active]) |pane| pane.scroll() else 0; const surface = try p.render(p.frame_arena.allocator()); p.frames.mark_render = FrameStats.nowNs(); if (v.present) |f| f(h.ctx, surface); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 572a6f2a..efe8c752 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1619,6 +1619,13 @@ const Shell = struct { const core = s.core; const tz_event = tracy.zone(@src(), "event"); defer tz_event.end(); + // A key's or a click's time, for its latency to the frame that + // answers it (FrameStats): when the loop takes it in. + switch (event) { + .key_press => core.frames.input(pardes.FrameStats.nowNs()), + .mouse => |m| if (m.type == .press) core.frames.input(pardes.FrameStats.nowNs()), + else => {}, + } switch (event) { .nop => {}, .wake => if (s.test_clock) |*virtual| { @@ -1877,6 +1884,9 @@ const Shell = struct { const tz_render = tracy.zone(@src(), "vx.render"); const before = s.tty.tty_writer.pos + s.tty.writer().end; vx.render(s.tty.writer()) catch {}; + // The frame's cost to the terminal (FrameStats.Frame.bytes): what + // vaxis's diff of the cells wrote. + s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), s.tty.tty_writer.pos + s.tty.writer().end -| before)); if (s.tty.tty_writer.pos + s.tty.writer().end != before) FrameAck.ask(s.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); tz_render.end(); } -- cgit v1.3 From 0dc2dc053af20d6811bfbe09ab31b762862a53a6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 21:30:52 -0300 Subject: anim 10: the caret is its own body: drawn from its own springs only, never carried by the text's glide (the ride-along deleted); its target is its cell as the view will settle, so a page leaves it still, a scroll that carries its line moves it there whole at the view's pace, a jump is one ease, a stream of steps lands each --- docs/next-anim.md | 25 ++++++++++++++++ src/FrameStats.zig | 12 +++++--- src/animation.zig | 42 +++++++++++++++++++-------- src/draw.zig | 73 +++++++++++++++++++++++++++++++++++++++------- src/gui/gui.zig | 85 +++++++++++++++++++++++++++++++++++------------------- 5 files changed, 181 insertions(+), 56 deletions(-) (limited to 'src/FrameStats.zig') diff --git a/docs/next-anim.md b/docs/next-anim.md index 1acdeacf..a64bfaf4 100644 --- a/docs/next-anim.md +++ b/docs/next-anim.md @@ -182,6 +182,31 @@ absorbed by what the system is doing: | moving | an input the other way | the stream ends; the spring turns it through zero from its speed | | moving | a jump past what two frames share | its rows are added (the stitched slide); the speed carries on | +The caret is its own body (anim 10): its state is its own springs +(`CursorGlide`, screen cells as floats), integrated on the same tick, and +it is drawn from that state only, never from the text's glide (the ride +that lifted it with the glide's fractional lag is deleted: every motion +of the text had leaked into it). Its only coupling to the view is its +target: its cell in the view as it will be once settled (the core's view +is that one). + +| an input | the caret's target | it does | +|---|---|---| +| a page or half page, a scroll that keeps its screen row (Ctrl-f/b/d/u, PageDown/Up, a j or k at the edge row) | unchanged | not a pixel's move while the text slides under it | +| a move in a still view (h/j/k/l, w, a click, a typed character) | the new cell | the short ease | +| a stream of such moves (a held key, typing) | each new cell | lands on each, at the keys' rate | +| a scroll that carries its line (the wheel, Ctrl-o to a far place in view) | where its line will be | moves there whole, at the view's pace, and lands exactly | +| a jump that moves both (G, a Look) | the final cell | one ease, no trip with the old page | +| a terminal's output | its cell | lands with the output (which does not glide) | +| Motion off | the cell | there at once | + +While a glide moves the text the caret is drawn as its quad (from its +springs), not as a cell of the moving rows. Invariants, checked over every +frame of the scripted scroll and held-key runs (`GlideRun.checkCaret`): +while its cell stays and it is on it, its drawn row is identical frame to +frame; it only closes on its cell; it lands within half a second of its +last change. The blink keys off the last key or click, never a frame. + So a held j, a spun wheel and a held Ctrl-d are the same case (a stream), a single j or notch the same ease as before. Every input, a repeat too, is still drawn at once: in a stream the picture is on the stream's diff --git a/src/FrameStats.zig b/src/FrameStats.zig index 0b252ff9..ee5ee3f2 100644 --- a/src/FrameStats.zig +++ b/src/FrameStats.zig @@ -45,8 +45,10 @@ pub const Frame = struct { /// 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). + /// rows (0 at rest), 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, @@ -84,6 +86,7 @@ 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, @@ -146,6 +149,7 @@ pub fn record(stats: *FrameStats, end_ns: u64, moving: bool, skipped: bool) void .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, @@ -263,13 +267,13 @@ pub fn dump(stats: *const FrameStats, path: [:0]const u8) void { .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\tlatency_us\tview", .{}); + 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\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}\t{d}", .{ + 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.latency_us, f.view, + @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}\n", .{ f.shaped, f.rastered, f.bytes }); diff --git a/src/animation.zig b/src/animation.zig index 63a40cbf..ae6f9ca0 100644 --- a/src/animation.zig +++ b/src/animation.zig @@ -964,6 +964,8 @@ pub const CursorGlide = struct { target: Box = .{}, from_centre: [2]f32 = .{ 0, 0 }, placed: bool = false, + /// When the last step (a move of a cell or less) came. + step_ns: u64 = 0, /// How much faster than the flavour's own pace a cursor moves: it /// follows input (§8.1: settles in 90-150 ms on the default). @@ -972,6 +974,9 @@ pub const CursorGlide = struct { pub const arc_from: f32 = 8; /// How much stiffer a step's spring is than a jump's. pub const step_pace: f32 = 1.5; + /// Steps this close are a stream (a held key, typing): each lands, the + /// caret at the keys' own rate, as an eased step a key would bounce. + pub const stream_ns: u64 = 150 * std.time.ns_per_ms; fn cornersOf(box: Box) [4][2]f32 { return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } }; @@ -982,16 +987,27 @@ pub const CursorGlide = struct { } /// Heads for `box` at `now_ns`. - pub fn aim(glide: *CursorGlide, box: Box, now_ns: u64, motion: Motion, snap: bool) void { + /// How a new mark is gone to: eased (a step, or a jump's smear and + /// bow), landed at once, or moved whole at a scroll's pace (the text + /// moved under it, not the caret). + pub const How = enum { ease, land, rigid }; + + pub fn aim(glide: *CursorGlide, box: Box, now_ns: u64, motion: Motion, how: How) void { // The same mark: nothing to do, unless a snap lands a glide under way. - if (glide.placed and std.meta.eql(box, glide.target) and !(snap and glide.moving())) return; + if (glide.placed and std.meta.eql(box, glide.target) and !(how == .land and glide.moving())) return; const to = cornersOf(box); const from_c = if (glide.placed) glide.centreAt(now_ns) else centre(box); const to_c = centre(box); const dx = to_c[0] - from_c[0]; const dy = to_c[1] - from_c[1]; const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01; - const land = !glide.placed or snap or motion.instant; + // A step is measured mark to mark, not from where an ease under way + // has got to (a held key's steps read as jumps from there). + const last = centre(glide.target); + const one_step = glide.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01; + const streaming = one_step and glide.step_ns != 0 and now_ns -| glide.step_ns < stream_ns; + if (one_step) glide.step_ns = now_ns; + const land = !glide.placed or how == .land or motion.instant or streaming; glide.from_centre = from_c; glide.target = box; glide.placed = true; @@ -999,9 +1015,11 @@ pub const CursorGlide = struct { // Leading: the corner ahead of the move, on the side it goes. const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy; var own = motion; - own.omega *= if (jump) pace * (if (ahead > 0) 1 else motion.follow) else pace * step_pace; - // A step neither winds up nor overshoots: it is a caret moving. - if (!jump) { + own.omega *= if (how == .rigid) 1.5 else if (jump) pace * (if (ahead > 0) 1 else motion.follow) else pace * step_pace; + // A step neither winds up nor overshoots: it is a caret moving; + // nor a whole move with the text (rigid: at the view's pace, + // Glide's 1.5x, its corners together). + if (!jump or how == .rigid) { own.zeta = 1; own.anticipate = 0; } @@ -1121,10 +1139,10 @@ test "a cursor eases a cell at a time, keeps up with typing, and glides a jump, const smooth_motion = Motion.of(.smooth); var glide: CursorGlide = .{}; const cell: Box = .{ .x = 3, .y = 4, .w = 1, .h = 1 }; - glide.aim(cell, 0, smooth_motion, false); + glide.aim(cell, 0, smooth_motion, .ease); try std.testing.expect(!glide.moving()); // One cell over: eases there whole, no wider than a cell, in ~60 ms. - glide.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, ms, smooth_motion, false); + glide.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, ms, smooth_motion, .ease); try std.testing.expect(glide.moving()); var step_t: u64 = ms; while (glide.step(step_t)) : (step_t += ms) { @@ -1132,21 +1150,21 @@ test "a cursor eases a cell at a time, keeps up with typing, and glides a jump, try std.testing.expect(q[1][0] - q[0][0] <= 1.0 + 1e-3 and q[0][0] >= 3 - 1e-3 and q[0][0] <= 4 + 1e-3); } try std.testing.expect(step_t - ms >= 30 * ms and step_t - ms <= 90 * ms); - // At a keyboard's repeat it keeps up: about half a cell behind. + // At a keyboard's repeat the steps are a stream: each lands. var typed: f32 = 4; var key_t: u64 = step_t; for (0..20) |_| { typed += 1; - glide.aim(.{ .x = typed, .y = 4, .w = 1, .h = 1 }, key_t, smooth_motion, false); + glide.aim(.{ .x = typed, .y = 4, .w = 1, .h = 1 }, key_t, smooth_motion, .ease); key_t += 33 * ms; try std.testing.expect(typed - glide.sample(key_t, smooth_motion)[0][0] <= 0.6); } while (glide.step(key_t)) key_t += ms; // A jump of 30 cells: glides, the leading edge ahead of the trailing one. - glide.aim(cell, key_t, smooth_motion, true); + glide.aim(cell, key_t, smooth_motion, .land); const j0 = key_t; const far: Box = .{ .x = 34, .y = 4, .w = 1, .h = 1 }; - glide.aim(far, j0 + 2 * ms, smooth_motion, false); + glide.aim(far, j0 + 2 * ms, smooth_motion, .ease); try std.testing.expect(glide.moving()); const mid = glide.sample(j0 + 40 * ms, smooth_motion); const width = mid[1][0] - mid[0][0]; diff --git a/src/draw.zig b/src/draw.zig index 265e07c1..e3ab9f2a 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -239,8 +239,8 @@ fn glideCursor(p: *Pardes, s: *Surface) void { }; const motion = animation.Motion.of(p.settings.motion); // The thin insert-mode caret glides as the block does (a jump smears - // and bows, a step eases); only a scroll, below, lands it. - var snap = false; + // and bows, a step eases); a scroll moves it rigidly, below. + var how: animation.CursorGlide.How = .ease; var frame: PaneFrame = .{}; // In a column's or the workspace's tag the cursor is not the pane's, // and does not move with it. @@ -259,14 +259,14 @@ fn glideCursor(p: *Pardes, s: *Surface) void { // The pane moved in the layout: the springs move with it (its // own cursor's; one in a column's tag stays). if (inside) p.cursor_glide.shift(origin[0] - view.origin[0], origin[1] - view.origin[1]); - // Scrolled (a file's view, a terminal's output): the quad moves - // with the text and lands, never gliding against text that - // jumped (every Enter at a prompt scrolls one and moves the - // other). - if (inside and line != view.line) { - p.cursor_glide.shift(0, @floatFromInt(view.line - line)); - snap = true; - } + // Scrolled (a file's view, a terminal's output): the caret is its + // own body, drawn from its own springs only, never from the text's + // glide. Its mark is where it will be once the view settles (its + // cell now: the core's view is that one), so a page that keeps its + // row leaves it still, and a scroll that carries its line moves + // it there whole, at the view's pace, not as a jump's smear. A + // terminal's output scrolls it with no glide: it lands with it. + if (inside and line != view.line) how = if (pane.isTerminal()) .land else .rigid; } else if (view.serial != 0 and p.cursor_glide.placed) { // Focus moved (to another pane, or between a pane and a // column's or the workspace's tag): the glide starts where the @@ -290,7 +290,7 @@ fn glideCursor(p: *Pardes, s: *Surface) void { // A click that took focus places the cursor on its release; aimed at // the pane's old cursor meanwhile, it would glide there first. if (p.drag != .select) p.cursor_held = false; - if (!p.cursor_held) p.cursor_glide.aim(box, p.now_ns, motion, snap); + if (!p.cursor_held) p.cursor_glide.aim(box, p.now_ns, motion, how); _ = p.cursor_glide.step(p.now_ns); const moving = p.cursor_glide.moving(); if (!moving and !p.cursor_held) p.cursor_crossing = false; @@ -1971,6 +1971,57 @@ test "each Motion flavour reaches the lift as its own trajectory" { try std.testing.expect(peaks[2] <= 1.001 and peaks[3] > 1.25 and peaks[4] > peaks[3]); } +test "the caret is its own body: a page leaves it still under the moving text, a wheel scroll moves it whole to its line's new row" { + if (!builtins.capabilities.lift) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 30 }); + defer p.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(std.testing.allocator); + for (0..400) |i| try text.print(std.testing.allocator, "line {d}\n", .{i}); + const pane = try p.setTestFile(text.items); + p.settings.cursor_blink = false; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var now: u64 = std.time.ns_per_s; + p.advance(now); + // Mid-file, where a half page keeps the caret's row. + for ("200G") |ch| p.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + _ = try p.render(arena.allocator()); + now += std.time.ns_per_s; + p.advance(now); + _ = arena.reset(.retain_capacity); + _ = try p.render(arena.allocator()); + // Ctrl-d: the caret moves with the view and keeps its screen row: it + // does not ride the glide, and it does not move. + const row_before = (try p.render(arena.allocator())).cursor.?.y; + p.update(.{ .key = .{ .cp = 'd', .ctrl = true } }); + now += 16 * std.time.ns_per_ms; + p.advance(now); + _ = arena.reset(.retain_capacity); + var s = try p.render(arena.allocator()); + try std.testing.expect(pane.file.?.scroll > 0); + try std.testing.expectEqual(row_before, s.cursor.?.y); + try std.testing.expectEqual(@as(u8, 0), s.chrome.cursor_glide & 1); + try std.testing.expectEqual(@as(f32, @floatFromInt(row_before)), s.chrome.cursor_quad[1]); + // The view scrolled with the caret on its line: it heads for the + // line's new row whole (every corner the same way), and lands on it. + pane.scrollBy(-3); + now += 16 * std.time.ns_per_ms; + p.advance(now); + _ = arena.reset(.retain_capacity); + s = try p.render(arena.allocator()); + const mark: f32 = @floatFromInt(s.cursor.?.y); + try std.testing.expect(s.chrome.cursor_glide & 1 != 0 and s.chrome.cursor_quad[1] < mark); + try std.testing.expectApproxEqAbs(s.chrome.cursor_quad[3] - s.chrome.cursor_quad[1], s.chrome.cursor_quad[5] - s.chrome.cursor_quad[7], 1e-4); + while (p.continuous()) { + now += 7 * std.time.ns_per_ms; + p.advance(now); + _ = arena.reset(.retain_capacity); + s = try p.render(arena.allocator()); + } + try std.testing.expectEqual(mark, s.chrome.cursor_quad[1]); +} + test "the focused cursor glides a jump, eases a step, the thin caret too, and is exact at rest" { if (!builtins.capabilities.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 30 }); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 8163581a..3f7dd7ca 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -5428,8 +5428,6 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde shifted.y_off -= glide.offset * layout.h; const kept = holdContext(g, surface, glide.pane, held, bh, layout); shifted.y_off += kept.lift; - const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); - const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; // Only the rows the scissor shows: lagging a body or more, every body // row is past the edge, and drawing them all was twice the frame's @@ -5442,8 +5440,9 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; var col = x0; while (col < x0 + bw) : (col += 1) { - const sidx: u32 = @as(u32, row) * surface.cols + col; - emitInstance(g, instances, base + n, col, row, shifted, win_w, win_h, null, cellFontRole(surface.at(col, row)), line, col, row_cursor, false, sidx == cursor_idx and !cursor_bar, page); + // No caret among the moving rows: it is drawn from its own + // springs (the quad), never carried by the text's glide. + emitInstance(g, instances, base + n, col, row, shifted, win_w, win_h, null, cellFontRole(surface.at(col, row)), line, col, row_cursor, false, false, page); n += 1; } } @@ -5545,6 +5544,8 @@ const GlideRun = struct { const Step = struct { frame: usize, key: pardes.Key }; offsets: [600]f32 = undefined, lines: [600]i64 = undefined, + carets: [600]f32 = undefined, + cells: [600]f32 = undefined, frames: usize = 0, fn play(seq: *GlideRun, g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator, arena: *std.heap.ArenaAllocator, script: []const Step, frames: usize) !void { @@ -5561,10 +5562,27 @@ const GlideRun = struct { if (g.glide.moving()) g.glide.advance(g.glide.now_ns, g.glide.motion); seq.offsets[frame] = g.glide.offset; seq.lines[frame] = @intCast(core.panes[core.active].?.file.?.scroll); + seq.carets[frame] = caretRow(g, s) orelse -1; + seq.cells[frame] = if (s.cursor) |cu| @floatFromInt(cu.y) else -1; } seq.frames = frames; } + /// The caret's invariants over the run: while its cell stays and it is + /// on it, it does not move a pixel; it only ever closes on its cell (a + /// twentieth of a row of play for a jump's bow); it lands within half a + /// second of its last change. + fn checkCaret(seq: *const GlideRun) !void { + var changed: usize = 0; + for (1..seq.frames) |k| { + if (seq.cells[k] < 0 or seq.cells[k - 1] < 0) continue; + if (seq.cells[k] != seq.cells[k - 1]) changed = k; + if (seq.cells[k] == seq.cells[k - 1] and seq.carets[k - 1] == seq.cells[k - 1]) try std.testing.expectEqual(seq.carets[k - 1], seq.carets[k]); + try std.testing.expect(@abs(seq.carets[k] - seq.cells[k]) <= @abs(seq.carets[k - 1] - seq.cells[k]) + 0.05); + if (k - changed == 30) try std.testing.expectEqual(seq.cells[k], seq.carets[k]); + } + } + /// Frames from `from` until the picture is still: the scroll's glide. fn settle(seq: *const GlideRun, from: usize) usize { var k = from; @@ -5618,6 +5636,7 @@ test "every scroll glides on one law: a half page, a page, the far jumps, a run }; var seq: GlideRun = .{}; try seq.play(&g, core, gpa, &arena, &script, 240); + try seq.checkCaret(); // Every one moves the picture on the frame it is drawn in, and the // picture lags by what the core moved (a far jump, by one body). var longest: usize = 0; @@ -5692,9 +5711,24 @@ test "a held key moves the view at the stream's own rate, never a bounce a line, most = @max(most, step); } try std.testing.expect(seq.lines[89] > 0 and least > 0.4 and most < 0.6); + // The caret stays on its row, the text moving under it: not a pixel's + // wobble (the glide's fractional lag never reaches it). + for (90..110) |k| try std.testing.expectEqual(seq.carets[89], seq.carets[k]); // It comes to rest once the keys stop, never past its mark. for (110..200) |k| try std.testing.expect(seq.offsets[k] <= 0); try std.testing.expectEqual(@as(f32, 0), seq.offsets[199]); + // Ctrl-d held, then PageDown held: the caret keeps its row the whole + // way, the pages moving under it. + var pages: [40]GlideRun.Step = undefined; + for (&pages, 0..) |*step, i| step.* = .{ .frame = 10 + 2 * i, .key = if (i < 20) .{ .cp = 'd', .ctrl = true } else .{ .cp = pardes.Key.page_down } }; + var held: GlideRun = .{}; + try held.play(&g, core, gpa, &arena, &pages, 100); + try held.checkCaret(); + try seq.checkCaret(); + // (The first of each may move it, one ease: from the last row to where + // a half page keeps it, and from there to a page's.) + for (30..50) |k| try std.testing.expectEqual(held.carets[30], held.carets[k]); + for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]); } fn resetScroll(g: *Gui) void { @@ -6427,12 +6461,15 @@ fn renderFrame( // while it glides or blinks. One or the other every frame (none only at // a blink's off half). const blink_alpha: f32 = if (blinkNow(g, chrome)) |b| b.alpha else 1; - const quad_mode = chrome.cursor_glide & 2 != 0 and (chrome.cursor_glide & 1 != 0 or blink_alpha < 1); + // While a glide moves the text, the caret is its quad, drawn from its + // own springs, not a cell of the moving rows. + const quad_mode = chrome.cursor_glide & 2 != 0 and (chrome.cursor_glide & 1 != 0 or blink_alpha < 1 or g.glide.offset != 0); g.cursor_quad_alpha = if (quad_mode) chrome.cursor_alpha * blink_alpha else 0; // The probe's view of this frame's motion (FrameStats.Frame). if (core) |p| { const probe = &@constCast(p).frames; probe.scroll = g.glide.offset; + probe.caret = caretRow(g, surface) orelse 0; } const cursors_shown = groups.tracks == 0 and !quad_mode; var overlay_count = buildOverlay(g, core, surface, sw, sh, debug_on); @@ -10713,37 +10750,32 @@ fn postSpare(surface: *const pardes.Surface, layout: CellLayout, out: *[Post.max const CursorBox = Post.Frame.Cursor; const max_cursors = 1 + pardes.MAX_PANES + pardes.MAX_TAG_LAYERS; +/// Where the frame draws the focused caret, its top in grid rows: from its +/// own springs (the quad's, while it moves or while a glide moves the text) +/// or its cell; never from the text's glide. The probe records it and the +/// glide tests hold its invariants. +fn caretRow(g: *const Gui, surface: *const pardes.Surface) ?f32 { + const chrome = &surface.chrome; + const cursor = surface.cursor orelse return null; + const quad = chrome.cursor_glide & 2 != 0 and (chrome.cursor_glide & 1 != 0 or g.glide.offset != 0); + return if (quad) chrome.cursor_quad[1] else @floatFromInt(cursor.y); +} + /// Every cursor on the frame where it is drawn, in window pixels: the grid's /// where no layer has its cell, and each layer's at that layer's pitch. A bar /// is an eighth of its cell wide, a block the whole cell. -/// Where a scroll's glide draws grid cell (col, row): its pixels down from -/// where the grid has it (the picture lags the text), and whether it is -/// still in the gliding body at all; nothing moved off a glide. -fn glideLift(g: *const Gui, col: f32, row: f32, layout: CellLayout) struct { px: f32, shown: bool } { - const glide = &g.glide; - if (glide.offset == 0) return .{ .px = 0, .shown = true }; - const r = glide.rect; - const top: f32 = @floatFromInt(glide.body_y); - const bottom = top + @as(f32, @floatFromInt(glide.body_h)); - if (col < @as(f32, @floatFromInt(r.x + config.GUTTER)) or col >= @as(f32, @floatFromInt(r.x + r.w)) or row < top or row >= bottom) return .{ .px = 0, .shown = true }; - const at = row - glide.offset; - return .{ .px = -glide.offset * layout.h, .shown = at >= top and at + 1 <= bottom + 0.5 }; -} - fn cursorBoxes(g: *const Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, out: *[max_cursors]CursorBox) usize { const chrome = &surface.chrome; const page = chrome.page orelse bg_default; var n: usize = 0; if (surface.cursor) |cursor| { - // A scroll's glide carries the cursor with the text it is in. - const lift = glideLift(g, @floatFromInt(cursor.x), @floatFromInt(cursor.y), layout); - if (lift.shown and cursor.x < surface.cols and cursor.y < surface.rows and bodyLayerAt(surface, cursor.x, cursor.y) == null and tagLayerIn(surface.tagLayers(), cursor.x, cursor.y) == null) { + if (cursor.x < surface.cols and cursor.y < surface.rows and bodyLayerAt(surface, cursor.x, cursor.y) == null and tagLayerIn(surface.tagLayers(), cursor.x, cursor.y) == null) { const cell = &surface.cells[@as(usize, cursor.y) * surface.cols + cursor.x]; const role = cellFontRole(cell); const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; const height = std.math.clamp(if (role == .tagline) @as(f32, @floatFromInt(g.tagline_height)) else layout.h, 1.0, layout.h); const x0 = @as(f32, @floatFromInt(cursor.x)) * layout.w; - const y0 = @as(f32, @floatFromInt(cursor.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(cursor.y, win_h, @intFromFloat(layout.h), @intFromFloat(height)))) + lift.px; + const y0 = @as(f32, @floatFromInt(cursor.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(cursor.y, win_h, @intFromFloat(layout.h), @intFromFloat(height)))); out[n] = .{ .x0 = x0, .y0 = y0, .x1 = x0 + if (cursor.bar) @max(dp(1), width / 8.0) else width, .y1 = y0 + height, .rgb = cursorColor(chrome, cell, role), .text = page, .bar = cursor.bar }; n += 1; } @@ -10816,13 +10848,8 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, builder: *OverlayB const layout = fixedCellLayout(g); var px: [4][2]f32 = undefined; var centre: [2]f32 = .{ 0, 0 }; - // A scroll's glide carries the quad with the text, by where its centre is. - var cell_centre: [2]f32 = .{ 0, 0 }; - for (0..4) |i| cell_centre = .{ cell_centre[0] + chrome.cursor_quad[i * 2] / 4, cell_centre[1] + chrome.cursor_quad[i * 2 + 1] / 4 }; - const lift = glideLift(g, cell_centre[0], cell_centre[1], layout); - if (!lift.shown) return; for (&px, 0..) |*point, i| { - point.* = .{ chrome.cursor_quad[i * 2] * layout.w, chrome.cursor_quad[i * 2 + 1] * layout.h + lift.px }; + point.* = .{ chrome.cursor_quad[i * 2] * layout.w, chrome.cursor_quad[i * 2 + 1] * layout.h }; centre[0] += point[0] / 4; centre[1] += point[1] / 4; } -- cgit v1.3 From 6e8a6a63d45b2caef7b649d358f836e6cc4134d6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 22:50:15 -0300 Subject: anim 11: a PDF's strip moves in the text's motion system: the integrator is animation.Follow (the Glide's, moved out), here the strip's lag behind document_scroll_y in pixels; whatever moves the core's position (a notch, a spin, PageDown, Ctrl-d/f, ge/gg, a Look at a page, Back, the rail) kicks it, a touchpad's fraction and a relayout move it directly; the pages a glide crosses render in its input's frame, a far jump's only where it comes to rest; a slow stream eases onto its mark (it ran into it at speed and passed it); pictures neither scroll nor pan --- docs/next-anim.md | 125 ++++++++++++++++++++++++++++++++++- src/FrameStats.zig | 73 +++++++++++++++++++- src/animation.zig | 137 ++++++++++++++++++++++++++++++++++++++ src/detached/wire.zig | 8 ++- src/gui/gui.zig | 158 ++++++++++++++------------------------------ src/pardes.zig | 8 ++- src/pdf_view.zig | 180 ++++++++++++++++++++++++++++++++++++++++++++++---- test/pdf.zig | 14 ++-- 8 files changed, 568 insertions(+), 135 deletions(-) (limited to 'src/FrameStats.zig') diff --git a/docs/next-anim.md b/docs/next-anim.md index a64bfaf4..9c9610e7 100644 --- a/docs/next-anim.md +++ b/docs/next-anim.md @@ -25,6 +25,9 @@ Positions, not a verdict: argue with them. | anim 6 `xykrnoql` | the tty paced too, its acks and output waited through | | anim 7 `powlyrxv` | what the probe found: the spin, glide measure and emission, far-jump and long-line paints, the caret's sideways scroll, no join on the loop, pictures decoded off the loop | | anim 8 | this note | +| anim 9 `nqznmskw` | the view's motion is one system: a stream of inputs moves it at its own rate, the spring only settles it | +| anim 10 `umnwnrvn` | the caret is its own body: drawn from its own springs, never carried by the text's glide | +| anim 11 `knzzzknu` | the integrator is `animation.Follow`; a PDF's strip moves in it, in pixels; a slow stream eases onto its mark | Tests (one check each, `-Dtest-filter`): "frame stats: gaps into a motion count as jank ...", "every scroll glides on one law ...", "a cursor eases @@ -213,6 +216,64 @@ is still drawn at once: in a stream the picture is on the stream's straight line wherever a frame samples it (tried: holding repeats to the next tick cost a held key 7 ms of latency for no evenness one could see). +### A PDF's strip, the same system (anim 11) + +The integrator is `animation.Follow` now (the Glide's state and rules, +moved out; the text's Glide holds one, in rows). A PDF pane's strip holds +another, in pixels: the core's position is `document_scroll_y` as every +input leaves it, and the strip is drawn `follow.offset` from it +(`pdf_view.stripAt`, each frame at the core's clock). Whatever moved the +core's position since the last frame kicks it, so every way a PDF moves is +one input to the same rules, the text's table above unchanged: + +| input | the strip | +|---|---| +| a wheel notch (a line's pixels), a spin | eases; a spin is a stream, at its rate | +| PageDown/Up, Ctrl-d/u/f/b, held | a stream, at its rate (to the 15 bodies a second cap) | +| ge, gg, a Look at `file.pdf:12`, Back, a section in the outline | a jump: past a body, one body's slide, as a text's far jump | +| a click on the rail, a tick | eases | +| a touchpad's fraction (`pdf_scroll.glide` false) | follows, drawn where the core is the same frame | +| a resize, a fit or zoom change (a relayout) | there at once | +| a search's reveal (it moves the strip as it draws) | there at once | +| Motion off | there at once | + +Rendering stays on the loop (MuPDF; its first-frame and context work is +the open item it was). So that no frame of a glide waits on it, the pages +a glide crosses to its mark are rendered in its input's frame, where the +instant move rendered its destination; a jump past a body (`far`) renders +only where it comes to rest, and its slide comes in over what is there +(the page above the mark is not drawn for a slide of a tenth of a second: +that page was the input frame's whole extra cost). Drawn at the strip's +position, rounded only by the draw (`pixel_offset_y` keeps the +fraction). Pictures are fit to their body and neither scroll nor pan: +nothing there to move. + +**Why the slow PDF scroll read as jumps**: a wheel notch moved the strip a +whole line's pixels (25 here) in the one frame after it, and nothing in +between: at a slow turn, one 25 px jump a notch. The touchpad path was +never quantized (fractions all the way to the placement). Now a notch is +a kick, and the strip eases over ~6 frames. + +### Coming to rest (anim 9, 11) + +Found while measuring the PDF: a slow stream (notches 150 ms apart, just +inside the stream window) ran its constant rate into the mark, stopping +from 2.6 px a frame, and its last speed, never zeroed, then carried it +0.04 row past the mark and back. A stream is now never faster than the +spring's own pace from where it is (omega a unit of lag a second): it eases +onto each mark. The check: "a follow comes to rest without a snap" (a +spin, a page, and notches 144 ms apart: toward the mark only, onto it from +under a third of a pixel, past its fastest frame each step no longer than +the last); it fails on the old rule. + +Measured on every settle the runs have (frames after an input until the +view is still, speeds normalized by the frame's own time): before anim 9 +the old spring's tails were already monotonic; the anim 9+10 stream rule +had one rising tail in the scroll demo's notches (the stop from 2.6 px) +and a last step of 0.88 px; now, over the scroll, stress and PDF runs +(ReleaseSafe and Debug), no tail rises after its fastest frame and the +last step before rest is at most 0.06 px (text) and 0.05 px (PDF). + ### The cursor (anim 4) The thin caret glides as the block does. A step of a cell or less eases @@ -250,7 +311,7 @@ while the view stands still, nor for stretches over 512 KB. | a 200-line paste | one body's slide | a long jump | | terminal output | snaps | a stream would always lag | | terminal under the wheel | glides | the wheel's; keys in its normal mode snap (position 4) | -| PDF | its own scroll | untouched here | +| PDF | glides (its strip, in pixels, anim 11); a touchpad follows | the same rules as text | | no-wrap sideways scroll | snaps | horizontal glides were not asked; position 6 | ## Ponytail pass (on the stack, amended in place) @@ -853,6 +914,68 @@ the 2 s ones were few, the max falls 2801 -> 319. | all | before | 26.1/43.9/74.5/78.0 | 2.1/22.9/44.8/77.5 | 2.1/2.3/15.7/40.8 | 2189 | 1 | 108/15264 | | | after | 24.5/37.8/63.1/70.3 | 4.9/27.5/42.9/68.7 | 15.7/18.5/24.2/39.9 | 2175 | 1 | 101/15264 | +#### GUI: `pdf-scroll` (anim 11), before = anim 10 with the scenario, after = anim 11 + +ReleaseSafe, run 1 of 2 (`.scratch/runs9/v1-*`; run 2 within a few ms but far-jump max): + +| scenario | | latency ms p50/p90/p99/max | frame work ms | present gap ms (moving) | rows/s | late | +|---|---|---|---|---|---|---| +| spin | before | 4.7/9.2/33.4/33.4 | 4.7/9.2/33.4/33.4 | - | 1073 | 0 | +| | after | 2.0/6.8/22.0/22.0 | 1.7/6.9/17.2/22.0 | 12.9/16.7/21.8/28.4 | 1009 | 1 | +| held-pagedown | before | 15.3/29.4/31.1/31.1 | 15.2/29.3/31.0/31.0 | - | 9092 | 0 | +| | after | 1.8/19.2/26.8/26.8 | 1.7/9.6/26.7/26.7 | 16.6/20.5/33.9/33.9 | 6359 | 5 | +| far-jump | before | 16.5/32.8/32.8/32.8 | 6.8/18.0/32.7/32.7 | 17.0/17.2/19.1/19.1 | 24126 | 0 | +| | after | 22.6/32.1/32.1/32.1 | 5.8/7.1/32.0/32.0 | 16.6/16.8/18.8/18.8 | 23744 | 0 | +| slow-notches | before | 7.1/7.1/7.1/7.1 | 8.8/9.8/9.8/9.8 | 16.8/17.4/17.4/17.4 | 83 | 0 | +| | after | 6.9/7.0/7.0/7.0 | 1.7/6.7/6.9/6.9 | 16.6/16.8/17.3/17.3 | 87 | 0 | +| slow-touch | before | 6.9/10.7/12.3/12.3 | 6.8/10.6/12.2/12.2 | - | 94 | 0 | +| | after | 6.8/11.0/12.4/12.5 | 6.7/10.9/12.4/12.4 | - | 94 | 0 | + +Debug (`w1-*`): + +| scenario | | latency ms p50/p90/p99/max | frame work ms | present gap ms (moving) | rows/s | late | +|---|---|---|---|---|---|---| +| spin | before | 4.8/12.7/148.2/148.2 | 4.7/12.3/148.1/148.1 | - | 1074 | 0 | +| | after | 3.2/7.7/140.4/140.4 | 2.7/7.6/71.8/140.3 | 16.4/16.8/72.2/141.1 | 995 | 2 | +| held-pagedown | before | 78.5/115.5/115.5/115.5 | 78.3/115.3/115.3/115.3 | - | 8296 | 0 | +| | after | 10.1/121.7/127.6/127.6 | 6.5/98.4/127.5/127.5 | 16.6/98.6/141.2/141.2 | 6106 | 4 | +| far-jump | before | 45.4/84.2/84.2/84.2 | 6.2/45.1/83.9/83.9 | 16.6/17.7/18.7/18.7 | 24172 | 0 | +| | after | 51.4/86.9/86.9/86.9 | 6.1/8.5/86.7/86.7 | 16.6/17.5/20.8/20.8 | 23525 | 0 | +| slow-notches | before | 11.4/13.1/13.1/13.1 | 7.5/12.6/12.6/12.6 | 15.6/19.2/19.2/19.2 | 83 | 0 | +| | after | 18.3/19.0/19.0/19.0 | 2.7/11.9/18.5/18.5 | 16.6/16.9/19.2/19.2 | 88 | 0 | +| slow-touch | before | 7.3/11.8/14.1/17.8 | 7.0/11.5/13.8/17.3 | - | 94 | 0 | +| | after | 7.2/11.0/12.5/15.4 | 7.0/10.5/12.3/15.1 | - | 94 | 0 | + +The `panes` timedemo's pdf phase (`u1-*`, RS then Debug): + +| scenario | | latency ms p50/p90/p99/max | frame work ms | present gap ms (moving) | rows/s | late | +|---|---|---|---|---|---|---| +| pdf | before | 6.9/14.8/44.1/46.3 | 6.7/14.5/30.6/44.0 | 16.7/16.8/16.9/16.9 | 4678 | 0 | +| | after | 2.0/7.4/34.8/37.8 | 1.8/6.6/18.4/34.7 | 16.6/16.8/27.2/32.9 | 4678 | 9 | +| pdf | before | 7.6/57.1/149.4/158.8 | 6.3/18.0/142.1/149.3 | 16.6/16.8/17.9/17.9 | 4663 | 0 | +| | after | 3.2/16.2/144.5/155.5 | 2.8/7.2/125.0/144.4 | 16.5/16.8/134.0/149.4 | 4655 | 7 | + +Strip steps between presented frames (px, the probe's `scroll` column is +the strip's drawn y for a focused PDF; cell height 25): + +| phase | before | after | +|---|---|---| +| slow notches (one each 300 ms) | 25 px in one frame a notch, 7 of 7 steps whole lines | p10/p50/p90/max 0.04/0.8/6.8/7.2 px, none a whole line | +| slow touchpad (0.06 line a frame) | 1.5 px every frame | 1.5 px every frame (followed) | +| a spin's steps | 25 px each (a notch a frame, 100 at a burst) | 0.5/16/28/42, a stream | +| settle tails | none (nothing settled) | no rise after the fastest frame; last step <= 0.05 px | + +Latency: the spin and held PageDown answer sooner (the frame that answers +a key no longer renders the pages it moves to before showing it; they +render as the glide's input frames, a stream's, come). The far jumps +(ge, gg, a Look at a page, Back) answer within the before's spread in +ReleaseSafe (p50 16.5/17.8 -> 22.6/14.9 over two runs, max 32.8/31.7 -> +32.1/31.2); in Debug ge's frame renders what the before split between the +`g` prefix's frame (~20 ms, re-rendering pages left banded by a fling) and +ge's own (~40): the same total in one frame (60-67 ms). The `late` frames +are a held PageDown's input frames rendering a page while it moves (33 ms +gaps; before they were not moving frames, and took 30 ms to answer). + ## The coordinator's latency rows, answered - **pages-up-big** (p90 8.8 -> 24): real. The paint-ahead's upward stretch diff --git a/src/FrameStats.zig b/src/FrameStats.zig index ee5ee3f2..cf3b00d3 100644 --- a/src/FrameStats.zig +++ b/src/FrameStats.zig @@ -45,8 +45,9 @@ pub const Frame = struct { /// 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), and where it drew the caret, its top in rows - /// (the jitter check: a caret on a fixed row must not wobble). + /// 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; @@ -286,6 +287,8 @@ pub const Step = struct { 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, @@ -316,6 +319,7 @@ pub fn named(name: []const u8) ?[]const Step { if (std.mem.eql(u8, name, "stress")) return &stress; if (std.mem.eql(u8, name, "kinds")) return &kinds; if (std.mem.eql(u8, name, "panes")) return &panes; + if (std.mem.eql(u8, name, "pdf-scroll")) return &pdf_scroll; if (std.mem.eql(u8, name, "one")) return &one; if (std.mem.eql(u8, name, "jumps")) return &jumps; if (std.mem.eql(u8, name, "longlines")) return &longlines; @@ -449,6 +453,71 @@ fn scrollSet(steps: []Step, n: *usize, t: *u32) void { t.* += 500; } +/// A PDF's strip put through what moves it (anim 11): a wheel's notches, +/// then spun; PageDown held; the far jumps ge and gg; a Look at a page and +/// Back; then slow: a notch at a time, and a touchpad's drag a pixel or so +/// a frame. +pub const pdf_scroll = blk: { + @setEvalBranchQuota(20_000); + var steps: [512]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + const at = struct { + fn add(s: []Step, k: *usize, ms: u32, act: @FieldType(Step, "act")) void { + s[k.*] = .{ .at_ms = ms, .act = act }; + k.* += 1; + } + }; + at.add(&steps, &n, t, .{ .exec = "Look ../../docs/design.pdf" }); + t += 2000; + at.add(&steps, &n, t, .{ .phase = "spin" }); + for (0..6) |_| { + at.add(&steps, &n, t, .{ .wheel = 1 }); + t += 150; + } + for (0..60) |_| { + at.add(&steps, &n, t, .{ .wheel = 1 }); + t += 8; + } + t += 600; + for (0..30) |_| { + at.add(&steps, &n, t, .{ .wheel = -1 }); + t += 8; + } + t += 600; + at.add(&steps, &n, t, .{ .phase = "held-pagedown" }); + for (0..20) |_| { + at.add(&steps, &n, t, .{ .key = .{ .cp = pardes.Key.page_down } }); + t += 33; + } + t += 600; + at.add(&steps, &n, t, .{ .phase = "far-jump" }); + for ([_][]const u8{ "e", "g" }) |second| { + at.add(&steps, &n, t, .{ .key = .{ .cp = 'g', .text = "g" } }); + at.add(&steps, &n, t + 20, .{ .key = .{ .cp = second[0], .text = second } }); + t += 800; + } + at.add(&steps, &n, t, .{ .exec = "Look ../../docs/design.pdf:12" }); + t += 800; + at.add(&steps, &n, t, .{ .key = .{ .cp = 'o', .ctrl = true } }); + t += 800; + at.add(&steps, &n, t, .{ .phase = "slow-notches" }); + for (0..8) |_| { + at.add(&steps, &n, t, .{ .wheel = 1 }); + t += 300; + } + at.add(&steps, &n, t, .{ .phase = "slow-touch" }); + for (0..120) |_| { + at.add(&steps, &n, t, .{ .touch = 0.06 }); + t += 16; + } + t += 600; + at.add(&steps, &n, t, .{ .phase = "done" }); + at.add(&steps, &n, t, .end); + const out = steps[0..n].*; + break :blk out; +}; + /// `scrollSet` alone, on the file the session opened: one kind, for a /// profiler's run. pub const one = blk: { diff --git a/src/animation.zig b/src/animation.zig index ae6f9ca0..764aa0b3 100644 --- a/src/animation.zig +++ b/src/animation.zig @@ -949,6 +949,143 @@ test "a flavour's stretched pane lands exactly on its box, and a click finds the } } +/// A view that follows its input (anim 9, 11): the picture's offset from +/// the core's position now (in the view's own unit: rows of text, pixels of +/// a PDF strip; negative, the picture still shows what is above), its speed +/// (units a second), when it was last integrated, and what has been feeding +/// it. The text body (the GUI's Glide) and a PDF strip are each one. +pub const Follow = struct { + offset: f32 = 0, + speed: f32 = 0, + at_ns: u64 = 0, + /// The last inputs (down positive), their spacing, the last's time, and + /// how many came as one stream. + feed: struct { amount: f32 = 0, gap_ns: u64 = 0, last_ns: u64 = 0, count: u16 = 0 } = .{}, + + /// How far the picture may lag, in bodies (a flick past that jumps); + /// how fast it may move, in bodies a second, so moving text stays + /// readable. + pub const reach = 2; + pub const bodies_per_s: f32 = 15; + /// Inputs this close, each the way the last went, are one stream. + pub const stream_ns = 150 * std.time.ns_per_ms; + + /// What a view's size and the flavour make of the rules: the spring at + /// 1.5x the flavour's pace, the speed cap, the lag cap, and the offset + /// under which it is at rest (a tenth of a pixel, in its unit). + pub const Pace = struct { omega: f32, cap: f32, limit: f32, rest: f32 }; + + pub fn pace(motion: Motion, body: f32, rest: f32) Pace { + return .{ .omega = motion.omega * 1.5, .cap = body * bodies_per_s, .limit = body * reach, .rest = rest }; + } + + pub fn moving(follow: *const Follow) bool { + return follow.offset != 0 or follow.speed != 0; + } + + /// An input: the core moved `amount` (down positive). The picture now + /// lags by as much more, its speed as it was. + pub fn kick(follow: *Follow, amount: f32, now_ns: u64, p: Pace) void { + follow.advance(now_ns, p); + follow.offset = std.math.clamp(follow.offset - amount, -p.limit, p.limit); + const f = &follow.feed; + const like = f.count > 0 and (amount > 0) == (f.amount > 0) and now_ns -| f.last_ns < stream_ns; + if (like) { + const gap = now_ns -| f.last_ns; + f.gap_ns = if (f.count == 1) gap else (f.gap_ns + gap) / 2; + f.amount = (f.amount + amount) / 2; + f.count +|= 1; + } else f.* = .{ .amount = amount, .count = 1 }; + f.last_ns = now_ns; + } + + /// The system moved on to `now_ns`. Fed by a stream, at the stream's + /// rate (an input's amount over their spacing), held a lag `lead` + /// behind so a late input never finds it stopped and the stream's end + /// never runs it past its mark; else on the spring, critically damped, + /// from the speed it has. Never faster than `p.cap`. + pub fn advance(follow: *Follow, now_ns: u64, p: Pace) void { + const dt: f32 = @floatCast(@as(f64, @floatFromInt(@min(now_ns -| follow.at_ns, 2 * frame_ns))) / std.time.ns_per_s); + follow.at_ns = now_ns; + if (follow.offset == 0 and follow.speed == 0) return; + const omega = p.omega; + const toward: f32 = if (follow.offset < 0) 1 else -1; + const f = follow.feed; + if (f.count >= 2 and f.gap_ns > 0 and now_ns -| f.last_ns < f.gap_ns * 3 / 2) { + const gap: f32 = @floatCast(@as(f64, @floatFromInt(f.gap_ns)) / std.time.ns_per_s); + const rate = @abs(f.amount) / gap; + const lead = @max(@abs(f.amount), rate / omega); + // ponytail: a gentle pull to the lead (a tenth an input), so the + // per-frame step varies by a tenth; a stream's own jitter beyond + // that shows. An estimate of the input clock if it ever matters. + // A slow stream's lag runs out before its next input: never + // faster than the spring's own pace from there (omega a unit of + // lag a second), so it eases onto the mark, not into it at speed. + const v = std.math.clamp(rate + 0.1 / gap * (@abs(follow.offset) - lead), 0, @min(p.cap, omega * @abs(follow.offset))); + const step = @min(v * dt, @abs(follow.offset)); + follow.offset += toward * step; + follow.speed = if (follow.offset == 0) 0 else toward * v; + return; + } + const x = follow.offset; + // Coming to rest from a stream: never faster than the spring's own + // pace from here (omega a unit of lag a second), so it eases in and + // does not pass its mark. + if (follow.speed * x < 0 and @abs(follow.speed) > omega * @abs(x)) follow.speed = std.math.sign(follow.speed) * omega * @abs(x); + const lead_v = follow.speed + omega * x; + const decay = @exp(-omega * dt); + var next = (x + lead_v * dt) * decay; + var speed = (follow.speed - omega * dt * lead_v) * decay; + if (@abs(next - x) > p.cap * dt) { + next = x + std.math.sign(next - x) * p.cap * dt; + speed = std.math.sign(next - x) * p.cap; + } + follow.offset = next; + follow.speed = speed; + if (@abs(next) < p.rest and @abs(speed) < 10 * p.rest) follow.* = .{ .at_ns = now_ns }; + } +}; + +test "a follow comes to rest without a snap: past its fastest frame each step is shorter, the last under a tenth of a pixel" { + // A flick's spin (a stream of notches, then nothing), one page, and + // notches slow enough that each lag runs out before the next (its + // stream must ease onto each mark, never pass it). + const p = Follow.pace(.{}, 600, 0.1); + for ([_]struct { n: u16, gap_ms: u64 }{ .{ .n = 12, .gap_ms = 16 }, .{ .n = 1, .gap_ms = 16 }, .{ .n = 6, .gap_ms = 144 } }) |run| { + var f: Follow = .{}; + var now: u64 = std.time.ns_per_s; + for (0..run.n) |_| { + f.kick(if (run.n == 1) 600 else 25, now, p); + var waited: u64 = 0; + while (waited < run.gap_ms) : (waited += 8) { + now += 8 * std.time.ns_per_ms; + const was = f.offset; + f.advance(now, p); + // Toward its mark only, and onto it from under a pixel. + try std.testing.expect(f.offset <= 0 and f.offset >= was); + if (f.offset == 0) try std.testing.expect(-was <= 3 * p.rest); + } + } + var last: f32 = std.math.inf(f32); + var before = f.offset; + var frames: usize = 0; + var fastest: f32 = 0; + while (f.moving()) : (frames += 1) { + now += frame_ns; + f.advance(now, p); + const step = @abs(f.offset - before); + try std.testing.expect(@abs(f.offset) <= @abs(before)); + if (f.offset == 0) try std.testing.expect(step <= 3 * p.rest); + fastest = @max(fastest, step); + if (step < fastest) try std.testing.expect(step <= last); + last = step; + before = f.offset; + try std.testing.expect(frames < 120); + } + try std.testing.expect(last <= 0.1); + } +} + /// The focused cursor's quad (docs/render-pipeline.md §5.4), in grid cells: /// four corners, each on its own springs, so a jump smears along its path /// (the leading corners stiffer than the trailing ones, Motion.follow) and diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 9890dc1a..0e141686 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -12,7 +12,7 @@ const ShaderAnimation = pardes.config.Runtime.ShaderAnimation; /// to be refused, which is what this number is for. /// 8: one layer type: a tag band carries all its rows (not a layer per /// line), and a frame carries the core's placed regions after its layers. -pub const version: u16 = 11; +pub const version: u16 = 12; /// The Chrome palette is carried field by field as its declaration lists /// them, so any change to it changes the wire: bump `version`, then this. @@ -980,6 +980,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { .pdf_scroll => |s| { try w.writeByte(s.pane); try w.writeInt(u32, @bitCast(s.delta_pixels), .little); + try w.writeByte(@intFromBool(s.glide)); }, .pinch => |v| try w.writeInt(u32, @bitCast(v), .little), .touch_scroll => |v| try w.writeInt(u32, @bitCast(v), .little), @@ -1043,7 +1044,7 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { }, .paste => .{ .event = .{ .paste = try getSlice32(&r) } }, .command => .{ .event = .{ .command = try r.take(try r.takeInt(u16, .little)) } }, - .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try getPane(&r), .delta_pixels = try getF32(&r) } } }, + .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try getPane(&r), .delta_pixels = try getF32(&r), .glide = try getBool(&r) } } }, .pinch => .{ .event = .{ .pinch = try getF32(&r) } }, .touch_scroll => .{ .event = .{ .touch_scroll = try getF32(&r) } }, .pointer_leave => .{ .event = .pointer_leave }, @@ -1297,9 +1298,10 @@ test "detached wire: every Event variant round-trips" { try testing.expectEqualStrings("clip", (try roundClient(&buf, .{ .event = .{ .paste = "clip" } })).event.paste); try testing.expectEqualStrings("Look /x", (try roundClient(&buf, .{ .event = .{ .command = "Look /x" } })).event.command); { - const got = (try roundClient(&buf, .{ .event = .{ .pdf_scroll = .{ .pane = 2, .delta_pixels = -12.5 } } })).event.pdf_scroll; + const got = (try roundClient(&buf, .{ .event = .{ .pdf_scroll = .{ .pane = 2, .delta_pixels = -12.5, .glide = false } } })).event.pdf_scroll; try testing.expectEqual(@as(u8, 2), got.pane); try testing.expectEqual(@as(f32, -12.5), got.delta_pixels); + try testing.expect(!got.glide); } try testing.expectEqual(@as(f32, 1.25), (try roundClient(&buf, .{ .event = .{ .pinch = 1.25 } })).event.pinch); try testing.expectEqual(@as(f32, -0.75), (try roundClient(&buf, .{ .event = .{ .touch_scroll = -0.75 } })).event.touch_scroll); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 3f7dd7ca..94eabb6c 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -3617,6 +3617,7 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { in.post(.{ .pdf_scroll = .{ .pane = @intCast(id), .delta_pixels = -w.y * @as(f32, @floatFromInt(g.cell_h)), + .glide = notchOf(w.y, w.integer_y) != null, } }); } else if (!w.mods.shift and pane.isTerminal() and pardes.panes.terminal.ownsWheel(pane)) { // The program's (codex, htop, less): every whole @@ -4338,6 +4339,10 @@ fn runDemo(g: *Gui, in: *Input, core: *pardes.Pardes) void { core.frames.input(now); wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); }, + .touch => |lines| { + core.frames.input(now); + wheelAt(g, in, .{ .y = -lines }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); + }, .key => |key| { core.frames.input(now); in.post(.{ .key = key }); @@ -5061,16 +5066,8 @@ test "a wheel over codex in a terminal reaches its pty as the mouse reports it a /// (an ease, a turn through zero); a jump mid-glide adds its rows with the /// speed kept. The spring's settle only comes once the inputs stop. const Glide = struct { - /// The picture's offset from the core's rows now (rows; negative, the - /// picture still shows what is above), its speed (offset's rows a - /// second), and when it was last integrated. - offset: f32 = 0, - speed: f32 = 0, - at_ns: u64 = 0, - /// What has been feeding it: the rows of the last inputs (down - /// positive), their spacing, the last's time, and how many came as one - /// stream. - feed: struct { rows: f32 = 0, gap_ns: u64 = 0, last_ns: u64 = 0, count: u16 = 0 } = .{}, + /// The picture's lag behind the core's rows and its motion (rows). + follow: pardes.animation.Follow = .{}, now_ns: u64 = 0, pane: usize = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, @@ -5100,21 +5097,16 @@ const Glide = struct { /// whatever moved it. seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i64 = 0, file: u64 = 0, revision: u32 = 0 } = @splat(.{}), - /// How far the picture may lag, in bodies: the rows kept past each - /// edge, so a jump made while one glides carries on from where it is. - const reach = 2; - const bodies_per_s: f32 = 15; - /// Inputs this close, each the way the last went, are one stream. - const stream_ns = 150 * std.time.ns_per_ms; + /// The rows kept past each edge, in bodies, so a jump made while one + /// glides carries on from where it is: as far as the picture may lag. + const reach = pardes.animation.Follow.reach; fn moving(glide: *const Glide) bool { - return glide.offset != 0 or glide.speed != 0 or glide.pending; + return glide.follow.moving() or glide.pending; } fn stop(glide: *Glide) void { - glide.speed = 0; - glide.feed = .{}; - glide.offset = 0; + glide.follow = .{ .at_ns = glide.follow.at_ns }; glide.pending = false; glide.nabove = 0; glide.nbelow = 0; @@ -5126,8 +5118,8 @@ const Glide = struct { /// The glide's lag in the core's lines: its rows, scaled by the lines /// they carried. fn lagLines(glide: *const Glide) f32 { - if (glide.rows_moved == 0) return glide.offset; - return glide.offset * glide.lines_moved / glide.rows_moved; + if (glide.rows_moved == 0) return glide.follow.offset; + return glide.follow.offset * glide.lines_moved / glide.rows_moved; } fn deinit(glide: *Glide, gpa: std.mem.Allocator) void { @@ -5140,70 +5132,18 @@ const Glide = struct { return glide.rect.w -| config.GUTTER; } - /// An input: the core's rows moved by `rows` (down positive) since the - /// last frame. The picture now lags by as many more, its speed as it was. + /// The rules at this body's size: a tenth of a pixel is 5e-3 rows. + fn pace(glide: *const Glide, motion: pardes.animation.Motion) pardes.animation.Follow.Pace { + return pardes.animation.Follow.pace(motion, @floatFromInt(glide.body_h), 5e-3); + } + + /// An input: the core's rows moved by `rows` (down positive). fn kick(glide: *Glide, rows: f32, now_ns: u64, motion: pardes.animation.Motion) void { - glide.advance(now_ns, motion); - // Never more than `reach` bodies behind: a flick past that jumps. - const limit: f32 = @floatFromInt(@as(u32, glide.body_h) * reach); - glide.offset = std.math.clamp(glide.offset - rows, -limit, limit); - const f = &glide.feed; - const like = f.count > 0 and (rows > 0) == (f.rows > 0) and now_ns -| f.last_ns < stream_ns; - if (like) { - const gap = now_ns -| f.last_ns; - f.gap_ns = if (f.count == 1) gap else (f.gap_ns + gap) / 2; - f.rows = (f.rows + rows) / 2; - f.count +|= 1; - } else f.* = .{ .rows = rows, .count = 1 }; - f.last_ns = now_ns; - } - - /// The system moved on to `now_ns`. Fed by a stream, at the stream's - /// rate (rows an input over their spacing), held a lag `lead` behind - /// the text so a late input never finds it stopped and the stream's end - /// never runs it past its mark; else on the flavour's spring at 1.5x - /// its pace, critically damped, from the speed it has. Never more than - /// `bodies_per_s` of the body a second, so moving text stays readable. + glide.follow.kick(rows, now_ns, glide.pace(motion)); + } + fn advance(glide: *Glide, now_ns: u64, motion: pardes.animation.Motion) void { - const dt: f32 = @floatCast(@as(f64, @floatFromInt(@min(now_ns -| glide.at_ns, 2 * pardes.animation.frame_ns))) / std.time.ns_per_s); - glide.at_ns = now_ns; - if (glide.offset == 0 and glide.speed == 0) return; - const omega = motion.omega * 1.5; - const cap = @as(f32, @floatFromInt(glide.body_h)) * bodies_per_s; - const toward: f32 = if (glide.offset < 0) 1 else -1; - const f = glide.feed; - if (f.count >= 2 and f.gap_ns > 0 and now_ns -| f.last_ns < f.gap_ns * 3 / 2) { - const gap: f32 = @floatCast(@as(f64, @floatFromInt(f.gap_ns)) / std.time.ns_per_s); - const rate = @abs(f.rows) / gap; - const lead = @max(@abs(f.rows), rate / omega); - // ponytail: a gentle pull to the lead (a tenth an input), so the - // per-frame step varies by a tenth; a stream's own jitter beyond - // that shows. An estimate of the input clock if it ever matters. - const v = std.math.clamp(rate + 0.1 / gap * (@abs(glide.offset) - lead), 0, cap); - const step = @min(v * dt, @abs(glide.offset)); - glide.offset += toward * step; - glide.speed = toward * v; - return; - } - const x = glide.offset; - // Coming to rest from a stream: never faster than the spring's own - // pace from here (omega a row of lag a second), so it eases in and - // does not pass its mark. - if (glide.speed * x < 0 and @abs(glide.speed) > omega * @abs(x)) glide.speed = std.math.sign(glide.speed) * omega * @abs(x); - const lead_v = glide.speed + omega * x; - const decay = @exp(-omega * dt); - var next = (x + lead_v * dt) * decay; - var speed = (glide.speed - omega * dt * lead_v) * decay; - if (@abs(next - x) > cap * dt) { - next = x + std.math.sign(next - x) * cap * dt; - speed = std.math.sign(next - x) * cap; - } - glide.offset = next; - glide.speed = speed; - if (@abs(next) < 5e-3 and @abs(speed) < 5e-2) { - glide.offset = 0; - glide.speed = 0; - } + glide.follow.advance(now_ns, glide.pace(motion)); } /// Finds how far the pane's body rows moved, `dir` rows at a time, by @@ -5307,11 +5247,11 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { defer core.shell_continuous = glide.moving() or g.sel_glow.fading or g.hover_glow.fading; glide.now_ns = core.now_ns; glide.motion = pardes.animation.Motion.of(core.settings.motion); - if (glide.offset != 0 or glide.speed != 0) { + if (glide.follow.offset != 0 or glide.follow.speed != 0) { glide.advance(core.now_ns, glide.motion); core.needs_frame = true; - if (glide.offset == 0) { - glide.offset = 0; + if (glide.follow.offset == 0) { + glide.follow.offset = 0; glide.nabove = 0; glide.nbelow = 0; glide.lines_moved = 0; @@ -5425,16 +5365,16 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde g.scroll_body_y = y0; g.scroll_body_h = bh; var shifted = layout; - shifted.y_off -= glide.offset * layout.h; + shifted.y_off -= glide.follow.offset * layout.h; const kept = holdContext(g, surface, glide.pane, held, bh, layout); shifted.y_off += kept.lift; var n: u32 = 0; // Only the rows the scissor shows: lagging a body or more, every body // row is past the edge, and drawing them all was twice the frame's // instances for the length of a long glide. - const lag: u16 = @intFromFloat(@min(@floor(@abs(glide.offset)), @as(f32, @floatFromInt(bh)))); - var row = y0 + kept.rows + if (glide.offset > 0) lag else 0; - const row_end = y0 + bh - if (glide.offset < 0) lag else 0; + const lag: u16 = @intFromFloat(@min(@floor(@abs(glide.follow.offset)), @as(f32, @floatFromInt(bh)))); + var row = y0 + kept.rows + if (glide.follow.offset > 0) lag else 0; + const row_end = y0 + bh - if (glide.follow.offset < 0) lag else 0; while (row < row_end) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; @@ -5448,13 +5388,13 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde } // The gap: rows past the top while the picture lags a move down, past // the bottom for one up; as many as it opens. - const gap: u16 = @intFromFloat(@min(@ceil(@abs(glide.offset)), @as(f32, @floatFromInt(@as(u32, bh) * Glide.reach)))); - const nkept = if (glide.offset < 0) glide.nabove else glide.nbelow; - const rows = if (glide.offset < 0) glide.above else glide.below; + const gap: u16 = @intFromFloat(@min(@ceil(@abs(glide.follow.offset)), @as(f32, @floatFromInt(@as(u32, bh) * Glide.reach)))); + const nkept = if (glide.follow.offset < 0) glide.nabove else glide.nbelow; + const rows = if (glide.follow.offset < 0) glide.above else glide.below; for (0..@min(gap, nkept)) |i| { const cells = rows[i * bw ..][0..bw]; // Row -1 - i above the body, or bh + i below it, in grid rows. - const at_row: i32 = if (glide.offset < 0) @as(i32, y0) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); + const at_row: i32 = if (glide.follow.offset < 0) @as(i32, y0) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); var at = shifted; // emitInstance takes an unsigned row: move the layout instead. at.y_off += @as(f32, @floatFromInt(at_row - @as(i32, y0))) * layout.h; @@ -5514,7 +5454,7 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe g.glide.measure(gpa, s); // Its two rows: the picture two rows behind, the rows that left kept, // nearest first. - try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.offset, 1e-4); + try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); try std.testing.expect(sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); // Frame by frame it comes back, never past, and settles. @@ -5523,11 +5463,11 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe now += 7 * ms; core.advance(now); stepGlide(&g, core, gpa); - try std.testing.expect(g.glide.offset <= 1e-4); + try std.testing.expect(g.glide.follow.offset <= 1e-4); if (frames > 200) return error.NeverSettled; } try std.testing.expect(frames > 5); - try std.testing.expectEqual(@as(f32, 0), g.glide.offset); + try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); try std.testing.expect(!core.shell_continuous); // Motion off: a notch lands at once. core.settings.motion = .off; @@ -5560,7 +5500,7 @@ const GlideRun = struct { const s = try core.render(arena.allocator()); if (g.glide.pending) g.glide.measure(gpa, s); if (g.glide.moving()) g.glide.advance(g.glide.now_ns, g.glide.motion); - seq.offsets[frame] = g.glide.offset; + seq.offsets[frame] = g.glide.follow.offset; seq.lines[frame] = @intCast(core.panes[core.active].?.file.?.scroll); seq.carets[frame] = caretRow(g, s) orelse -1; seq.cells[frame] = if (s.cursor) |cu| @floatFromInt(cu.y) else -1; @@ -5809,7 +5749,7 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { g.scroll_held_px = 0; - if (g.glide.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page, held); + if (g.glide.follow.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page, held); const scroll_pane = g.scroll_pane orelse return 0; if (g.scroll_lag == 0) return 0; for (surface.panelTracks()) |track| @@ -6436,7 +6376,7 @@ fn renderFrame( if (chrome.fx & 8 != 0 and chrome.decor_dots != null) for (surface.regionList()) |region| { if (region.kind != .body or cell_decor.nbodies == cell_decor.bodies.len) continue; var rows: f32 = @floatFromInt(region.line); - if (g.glide.moving() and g.glide.pane == region.owner) rows += g.glide.offset; + if (g.glide.moving() and g.glide.pane == region.owner) rows += g.glide.follow.offset; const period = cell_decor.uniforms[4]; cell_decor.bodies[cell_decor.nbodies] = bodyPixels(region, layout); cell_decor.shifts[cell_decor.nbodies] = @mod(-rows * layout.h * 0.25, period); @@ -6463,12 +6403,14 @@ fn renderFrame( const blink_alpha: f32 = if (blinkNow(g, chrome)) |b| b.alpha else 1; // While a glide moves the text, the caret is its quad, drawn from its // own springs, not a cell of the moving rows. - const quad_mode = chrome.cursor_glide & 2 != 0 and (chrome.cursor_glide & 1 != 0 or blink_alpha < 1 or g.glide.offset != 0); + const quad_mode = chrome.cursor_glide & 2 != 0 and (chrome.cursor_glide & 1 != 0 or blink_alpha < 1 or g.glide.follow.offset != 0); g.cursor_quad_alpha = if (quad_mode) chrome.cursor_alpha * blink_alpha else 0; // The probe's view of this frame's motion (FrameStats.Frame). if (core) |p| { const probe = &@constCast(p).frames; - probe.scroll = g.glide.offset; + // A focused PDF's strip is the core's (pdf_view.draw). + const pdf_focus = if (p.panes[p.active]) |pane| pane.hasPdf() else false; + if (!pdf_focus) probe.scroll = g.glide.follow.offset; probe.caret = caretRow(g, surface) orelse 0; } const cursors_shown = groups.tracks == 0 and !quad_mode; @@ -6726,7 +6668,7 @@ fn renderFrame( for (groups.items[0..groups.len], 0..) |group, index| std.debug.assert(cell_next[index] == group.cell_start + group.cell_count); // The body's context rows, which its scroll leaves where they are. - const scrolling: ?usize = if (g.glide.offset != 0) g.glide.pane else g.scroll_pane; + const scrolling: ?usize = if (g.glide.follow.offset != 0) g.glide.pane else g.scroll_pane; const held: u16 = if (core) |p| if (scrolling) |id| if (p.panes[id]) |pane| pane.context_rows else 0 else 0 else 0; shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held); // Over a theme's plaques a see-through cell with no ink blends to @@ -9620,7 +9562,7 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ti if (rail.thumb_h != 0 and rail.thumb_span > 0) { // In pixels, not rows, and with the picture while it glides // or lags behind the core's rows (both in rows of the body). - const lag: f32 = if (g.glide.offset != 0 and g.glide.pane == rail.owner) + const lag: f32 = if (g.glide.follow.offset != 0 and g.glide.pane == rail.owner) g.glide.lagLines() else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; const track_px = body_y1 - y0; @@ -10261,13 +10203,13 @@ test "the scrollbar thumb moves by the pixel and follows a glide" { // A line of a thousand moves it a fraction of a row, not 0 or 20 px. try std.testing.expect(at11 > at10 and at11 - at10 < 1); g.glide.pane = core.active; - g.glide.offset = -1; + g.glide.follow.offset = -1; try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); // A wrapped line: the picture moved two rows for the one line, and the // thumb lags the line, not two. g.glide.lines_moved = 1; g.glide.rows_moved = 2; - g.glide.offset = -2; + g.glide.follow.offset = -2; try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); } @@ -10757,7 +10699,7 @@ const max_cursors = 1 + pardes.MAX_PANES + pardes.MAX_TAG_LAYERS; fn caretRow(g: *const Gui, surface: *const pardes.Surface) ?f32 { const chrome = &surface.chrome; const cursor = surface.cursor orelse return null; - const quad = chrome.cursor_glide & 2 != 0 and (chrome.cursor_glide & 1 != 0 or g.glide.offset != 0); + const quad = chrome.cursor_glide & 2 != 0 and (chrome.cursor_glide & 1 != 0 or g.glide.follow.offset != 0); return if (quad) chrome.cursor_quad[1] else @floatFromInt(cursor.y); } diff --git a/src/pardes.zig b/src/pardes.zig index 0f3f87f2..829a7bfd 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -3690,7 +3690,9 @@ pub const Event = union(enum) { command: []const u8, /// Native shells may preserve sub-cell wheel distance in physical pixels. /// TTY button events still enter through the ordinary mouse path. - pdf_scroll: struct { pane: u8, delta_pixels: f32 }, + /// `glide`: a wheel's notch, which the strip glides; a touchpad's + /// fraction is followed as it comes. + pdf_scroll: struct { pane: u8, delta_pixels: f32, glide: bool = true }, pinch: f32, touch_scroll: f32, /// The host pointer left the drawable area. Unlike an out-of-range motion, @@ -6164,7 +6166,7 @@ pub const Pardes = struct { if (scroll.pane < MAX_PANES) { if (p.panes[scroll.pane]) |pane| { if (pane.hasPdf() and p.native_images) - _ = panes.Pdf.scrollPane(p, pane, @floatCast(scroll.delta_pixels)); + _ = panes.Pdf.scrollPane(p, pane, @floatCast(scroll.delta_pixels), scroll.glide); } } } @@ -7737,7 +7739,7 @@ pub const Pardes = struct { /// is for the stepped animations, which count frames of `frame_ns`. pub fn continuous(p: *const Pardes) bool { for (p.lifts) |spring| if (!spring.settled) return true; - return p.cursor_glide.moving() or p.shell_continuous; + return p.cursor_glide.moving() or p.shell_continuous or panes.Pdf.moving(p); } /// For shells that only need a yes or no: macOS and the board, which diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 2a89ef01..37e4b216 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -197,6 +197,81 @@ test "PDF selections retain their owning page across page focus" { try std.testing.expectEqual(@as(usize, 0), state.selection_text.len); } +test "a PDF strip glides a notch and a page to their marks, eased and never past them, and follows a touchpad's fraction at once" { + if (comptime !enabled) return; + const gpa = std.testing.allocator; + var state = try State.open(gpa, "docs/design.pdf", 1); + defer state.deinit(gpa); + const view: Viewport = .{ .pixel_w = 800, .pixel_h = 600 }; + const motion = pardes.animation.Motion.of(.smooth); + ensureLayout(&state, view); + var now: u64 = std.time.ns_per_s; + try std.testing.expectEqual(state.document_scroll_y, stripAt(&state, view, motion, now)); + for ([_]f64{ 20, 600 }) |step| { + const from = state.document_scroll_y; + _ = scrollDocument(&state, view, step); + const mark = state.document_scroll_y; + // The input's frame still shows where it was; then it eases in. + var shown = stripAt(&state, view, motion, now); + try std.testing.expectEqual(from, shown); + var last_step: f64 = 0; + var peaked = false; + for (0..60) |_| { + now += pardes.animation.frame_ns; + const next = stripAt(&state, view, motion, now); + const moved = next - shown; + try std.testing.expect(moved >= 0 and next <= mark); + // Past its fastest, each frame's step is no longer than the last. + if (moved < last_step) peaked = true; + if (peaked) try std.testing.expect(moved <= last_step + 1e-9); + last_step = moved; + shown = next; + } + try std.testing.expectEqual(mark, shown); + try std.testing.expect(!state.follow.moving()); + try std.testing.expect(last_step <= 1); + } + // A touchpad's fraction: drawn where the core is, the same frame. + const from = state.document_scroll_y; + _ = scrollDocument(&state, view, 0.25); + state.direct_y += state.document_scroll_y - from; + try std.testing.expectEqual(from + 0.25, stripAt(&state, view, motion, now)); +} + +test "a PDF glide renders the pages it crosses in its input's frame, but a far jump's only where it comes to rest" { + if (comptime !enabled) return; + const gpa = std.testing.allocator; + var state = try State.open(gpa, "docs/design.pdf", 1); + defer state.deinit(gpa); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const view: Viewport = .{ .pixel_w = 400, .pixel_h = 300 }; + const motion = pardes.animation.Motion.of(.smooth); + const key: TintKey = .{ .mode = .disabled, .colors = undefined }; + const none: HighlightInput = .{ .hover_color = .{ 0, 0, 0 }, .selection_color = .{ 0, 0, 0 } }; + ensureLayout(&state, view); + const frame = struct { + fn f(st: *State, a: *std.heap.ArenaAllocator, m: pardes.animation.Motion, k: TintKey, h: HighlightInput) void { + const v: Viewport = .{ .pixel_w = 400, .pixel_h = 300 }; + const shown = stripAt(st, v, m, std.time.ns_per_s); + st.document_scroll_y = shown; + _ = renderFrame(st, std.testing.allocator, a.allocator(), v, pardes.pdf_raster_policy, k, h, st.drawn_y - shown, st.far); + st.document_scroll_y = st.drawn_y; + } + }.f; + frame(&state, &arena, motion, key, none); + // A body down, onto page one's lower part: what it crosses is drawn. + _ = scrollDocument(&state, view, 300); + frame(&state, &arena, motion, key, none); + try std.testing.expect(!state.far and rasterForPage(&state, 0) != null); + // Far, to page three: only it; the slide comes in over page two's place. + state.document_scroll_y = @floatFromInt(state.page_starts[3]); + frame(&state, &arena, motion, key, none); + try std.testing.expect(state.far); + try std.testing.expect(rasterForPage(&state, 3) != null); + try std.testing.expect(rasterForPage(&state, 2) == null); +} + pub const Raster = if (enabled) struct { valid: bool = false, page: usize = 0, @@ -249,6 +324,15 @@ pub const State = if (enabled) struct { layout_fit: FitMode = .width, layout_valid: bool = false, document_scroll_y: f64 = 0, + /// The strip as drawn lags `document_scroll_y` by `follow` (anim 11, + /// the text's motion system, in pixels): `drawn_y` is where the core + /// stood at the last frame, `direct_y` what moved it since that the + /// picture takes as it comes (a touchpad, a relayout). + follow: pardes.animation.Follow = .{}, + drawn_y: f64 = 0, + direct_y: f64 = 0, + /// The last kick was a jump past a body (renderFrame's `far`). + far: bool = false, scroll_to_page_pending: bool = true, rasters: [raster_max]Raster = undefined, rasters_len: usize = 0, @@ -869,23 +953,28 @@ fn pageAtOffset(state: *const State, offset: f64) usize { return if (y >= end and lo + 1 < state.page_count) lo + 1 else lo; } -fn pageVisible(state: *const State, page: usize, viewport: Viewport) bool { +fn pageVisible(state: *const State, page: usize, y: f64, h: f64) bool { if (comptime !enabled) return false; - const top = @as(f64, @floatFromInt(state.page_starts[page])) - state.document_scroll_y; + const top = @as(f64, @floatFromInt(state.page_starts[page])) - y; const bottom = top + @as(f64, @floatFromInt(state.page_heights[page])); - return bottom > 0 and top < @as(f64, @floatFromInt(viewport.pixel_h)); + return bottom > 0 and top < h; } pub fn visiblePages(state: *const State, viewport: Viewport) VisiblePages { + return pagesOver(state, state.document_scroll_y, @floatFromInt(viewport.pixel_h)); +} + +/// The pages over the strip from `y`, `h` pixels down. +fn pagesOver(state: *const State, y: f64, h: f64) VisiblePages { if (comptime !enabled) return .{}; var out: VisiblePages = .{}; - var page = pageAtOffset(state, state.document_scroll_y); - if (page > 0 and pageVisible(state, page - 1, viewport)) page -= 1; + var page = pageAtOffset(state, y); + if (page > 0 and pageVisible(state, page - 1, y, h)) page -= 1; out.first = page; while (page < state.page_count) : (page += 1) { - const top = @as(f64, @floatFromInt(state.page_starts[page])) - state.document_scroll_y; - if (top >= @as(f64, @floatFromInt(viewport.pixel_h))) break; - if (pageVisible(state, page, viewport)) out.len += 1; + const top = @as(f64, @floatFromInt(state.page_starts[page])) - y; + if (top >= h) break; + if (pageVisible(state, page, y, h)) out.len += 1; } return out; } @@ -1496,18 +1585,31 @@ pub fn renderFrame( policy: RasterPolicy, tint_key: TintKey, highlight_input: HighlightInput, + path: f64, + far: bool, ) VisiblePages { if (comptime !enabled) return .{}; ensureLayout(state, viewport); state.resolveSearch(gpa); const highlights = buildHighlights(state, arena, highlight_input) catch Highlights{}; const request = renderRequest(viewport, policy, state.fit); - var visible = visiblePages(state, viewport); + // ponytail: every page the glide crosses to its mark (`path` pixels + // on) renders now, in the input's frame, so no frame of the glide + // waits on MuPDF (it renders on the loop). A far jump's slide (`far`) + // comes in over what is there, none of the page above its mark, which + // would cost the input's frame a page; a render thread would draw it. + const span = struct { + fn f(st: *const State, view: Viewport, along: f64, from_rest: bool) VisiblePages { + const h: f64 = @floatFromInt(view.pixel_h); + return if (from_rest) pagesOver(st, st.document_scroll_y + along, h) else pagesOver(st, st.document_scroll_y + @min(0, along), h + @abs(along)); + } + }.f; + var visible = span(state, viewport, path, far); reconcile(state, gpa, request, tint_key, highlights, visible, viewport); rearmSearchReveal(state, viewport); revealSearch(state, viewport, activeGeometry(state, viewport)); - visible = visiblePages(state, viewport); + visible = span(state, viewport, path, far); reconcile(state, gpa, request, tint_key, highlights, visible, viewport); return visible; } @@ -1898,6 +2000,7 @@ pub fn ensureLayout(state: *State, viewport: Viewport) void { if (comptime !enabled) return; const tz = tracy.zone(@src(), "pdf.ensure_layout"); defer tz.end(); + var relaid = false; if (state.layout_valid and !state.scroll_to_page_pending and !state.layout_anchor_pending and (state.layout_viewport_w != viewport.pixel_w or @@ -1919,6 +2022,7 @@ pub fn ensureLayout(state: *State, viewport: Viewport) void { state.layout_viewport_h = viewport.pixel_h; state.layout_fit = state.fit; state.layout_valid = true; + relaid = true; if (state.scroll_to_page_pending) { state.document_scroll_y = @floatFromInt(state.page_starts[state.page]); state.scroll_to_page_pending = false; @@ -1933,6 +2037,12 @@ pub fn ensureLayout(state: *State, viewport: Viewport) void { consumeOutlineReveal(state, viewport); const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h)); state.document_scroll_y = std.math.clamp(state.document_scroll_y, 0, max_scroll); + // A new layout is not a scroll: the picture is drawn there at once. + if (relaid) { + state.follow = .{}; + state.drawn_y = state.document_scroll_y; + state.direct_y = 0; + } } pub const WordProbe = if (enabled) struct { @@ -2688,23 +2798,55 @@ pub fn panPane( return panPixels(state, placed, axis, direction, display_pixels); } -pub fn scrollPane(core: *pardes.Pardes, pane: *pardes.Pane, delta_pixels: f64) bool { +/// `glide`: a notch, which the strip glides; else a touchpad's fraction, +/// which it follows as it comes. +pub fn scrollPane(core: *pardes.Pardes, pane: *pardes.Pane, delta_pixels: f64, glide: bool) bool { if (comptime !enabled) return false; const tz = tracy.zone(@src(), "pdf.scroll_notch"); defer tz.end(); const state = &(pane.pdf orelse return false); const view = ensurePaneLayout(core, pane) orelse return false; + const from = state.document_scroll_y; const result = scrollDocument(state, view, delta_pixels) orelse return false; + if (!glide) state.direct_y += state.document_scroll_y - from; if (result.active_page != state.page) activatePage(core, pane, result.active_page, false); return true; } +/// Where the strip is drawn this frame (anim 11): what moved the core's +/// position since the last frame kicks its follow, as a scroll kicks the +/// text's, all but what moved it directly; the follow then moves on to now. +fn stripAt(state: *State, view: Viewport, motion: pardes.animation.Motion, now_ns: u64) f64 { + const pace = pardes.animation.Follow.pace(motion, @floatFromInt(view.pixel_h), 0.1); + const moved = state.document_scroll_y - state.drawn_y - state.direct_y; + state.drawn_y = state.document_scroll_y; + state.direct_y = 0; + if (motion.instant) { + state.follow = .{}; + } else if (moved != 0) { + // A move past a body slides one, as a text's far jump does (G6): + // the pages between are rendered for the slide, not crossed. + const body: f64 = @floatFromInt(view.pixel_h); + state.far = @abs(moved) > body; + state.follow.kick(@floatCast(std.math.clamp(moved, -body, body)), now_ns, pace); + } else state.follow.advance(now_ns, pace); + const max_scroll = @as(f64, @floatFromInt(state.document_height -| view.pixel_h)); + return std.math.clamp(state.drawn_y + state.follow.offset, 0, max_scroll); +} + +/// A PDF strip is still on its way to where the core stands. +pub fn moving(core: *const pardes.Pardes) bool { + if (comptime !enabled) return false; + for (core.panes) |slot| if (slot) |pane| if (pane.pdf) |state| if (state.follow.moving()) return true; + return false; +} + pub fn verticalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void { if (comptime !enabled) return; if (!core.native_images) return stepPanePage(core, pane, direction); const rows: u32 = @intCast(@max(1, config.wheel_rows)); const pixels = scaledStep(core.cell_pixels.h, rows); - _ = scrollPane(core, pane, @as(f64, @floatFromInt(pixels)) * direction); + _ = scrollPane(core, pane, @as(f64, @floatFromInt(pixels)) * direction, true); } pub fn horizontalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void { @@ -2730,6 +2872,14 @@ pub fn draw( const state = &(pane.pdf orelse return false); const view = paneViewport(core, pane) orelse return false; const key = TintKey{ .mode = state.tint, .colors = tintColors(core) }; + ensureLayout(state, view); + // Drawn where the strip's follow is; the core's position comes back + // after (`drawn_y`), unless a search's reveal moved it as it drew, + // which is then drawn there at once. + const shown = stripAt(state, view, pardes.animation.Motion.of(core.settings.motion), core.now_ns); + state.document_scroll_y = shown; + defer state.document_scroll_y = state.drawn_y; + if (pane_id == core.active) core.frames.scroll = @floatCast(shown); const visible = renderFrame( state, core.pdf_gpa, @@ -2738,7 +2888,13 @@ pub fn draw( pardes.pdf_raster_policy, key, highlightInput(core, pane_id, pane), + state.drawn_y - shown, + state.far, ); + if (state.document_scroll_y != shown) { + state.follow = .{}; + state.drawn_y = state.document_scroll_y; + } var placed_any = false; var page = visible.first; const visible_end = visible.first + visible.len; diff --git a/test/pdf.zig b/test/pdf.zig index d4efdfaf..5f7ebc52 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -774,6 +774,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { .rows = 24, }); defer p.deinit(); + p.settings.motion = .off; // placements, not the glide (anim 11) const pane = p.panes[0].?; try std.testing.expect(hasPdf(pane)); try std.testing.expect(pane.pdf.?.page_count > 1); @@ -822,7 +823,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { // SDL's raw dy path retains fractions in the placement itself; it does // not leave native pixels fixed while only the underlying cells slide. - p.update(.{ .pdf_scroll = .{ .pane = 0, .delta_pixels = 0.25 } }); + p.update(.{ .pdf_scroll = .{ .pane = 0, .delta_pixels = 0.25, .glide = false } }); try std.testing.expectEqual(@as(f64, 0.25), pane.pdf.?.document_scroll_y); _ = frame.reset(.retain_capacity); const fractional = try p.render(frame.allocator()); @@ -940,7 +941,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { page0_revision, panes.Pdf.rasterForPage(&pane.pdf.?, 0).?.revision, ); - try std.testing.expect(panes.Pdf.scrollPane(p, pane, 1)); + try std.testing.expect(panes.Pdf.scrollPane(p, pane, 1, false)); try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page); try std.testing.expectEqual( page1_revision, @@ -1142,7 +1143,7 @@ test "a fling's banded pages show the reader exactly what whole pages would" { // is counted the way a wheel batch counts it. pv.document_scroll_y = 0; pv.scroll_travel = 0; - try std.testing.expect(panes.Pdf.scrollPane(p, pane, landing)); + try std.testing.expect(panes.Pdf.scrollPane(p, pane, landing, false)); _ = frame.reset(.retain_capacity); const flung = try p.render(frame.allocator()); try std.testing.expect(flung.nimages >= 2); @@ -1261,7 +1262,7 @@ test "a tall page is drawn at the display's resolution, in bands that are the wh defer gpa.free(middle); var middle_y: usize = 0; for ([_]f64{ 0, @round(max_scroll / 2), max_scroll }, 0..) |at, step| { - _ = panes.Pdf.scrollPane(p, pane, at - pv.document_scroll_y); + _ = panes.Pdf.scrollPane(p, pane, at - pv.document_scroll_y, false); pv.scroll_travel = 0; // read, not flung _ = frame.reset(.retain_capacity); const surface = try p.render(frame.allocator()); @@ -1291,7 +1292,7 @@ test "a tall page is drawn at the display's resolution, in bands that are the wh // Straight back to the middle from the foot: the rows rendered afresh // are the very rows rendered on the way down, so no seam moves with the // path a reader took. - _ = panes.Pdf.scrollPane(p, pane, @round(max_scroll / 2) - pv.document_scroll_y); + _ = panes.Pdf.scrollPane(p, pane, @round(max_scroll / 2) - pv.document_scroll_y, false); pv.scroll_travel = 0; _ = frame.reset(.retain_capacity); const again = (try p.render(frame.allocator())).images[0].?; @@ -1305,7 +1306,7 @@ test "a tall page is drawn at the display's resolution, in bands that are the wh middle[(common_top - middle_y) * stride .. (common_end - middle_y) * stride], again.rgba[(common_top - again_y) * stride .. (common_end - again_y) * stride], ); - _ = panes.Pdf.scrollPane(p, pane, max_scroll - pv.document_scroll_y); + _ = panes.Pdf.scrollPane(p, pane, max_scroll - pv.document_scroll_y, false); pv.scroll_travel = 0; _ = frame.reset(.retain_capacity); const foot = try gpa.dupe(u8, (try p.render(frame.allocator())).images[0].?.rgba); @@ -1663,6 +1664,7 @@ test "PDF tint and tinted theme changes rebuild every visible raster only" { .rows = 24, }); defer p.deinit(); + p.settings.motion = .off; // placements, not the glide (anim 11) const pane = p.panes[0].?; const pv = &pane.pdf.?; p.native_images = true; -- cgit v1.3 From b0773dc68491b0eab1b8030731b063cba3dd2b40 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 25 Oct 2026 10:15:44 -0300 Subject: pdfrender 0: the pdf-sdm timedemo (the Intel SDM, 5363 pages) and the probe's landed column (the frame a PDF page lands on) --- src/FrameStats.zig | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- src/pdf_view.zig | 7 +++++ 2 files changed, 83 insertions(+), 2 deletions(-) (limited to 'src/FrameStats.zig') diff --git a/src/FrameStats.zig b/src/FrameStats.zig index cf3b00d3..cabb003b 100644 --- a/src/FrameStats.zig +++ b/src/FrameStats.zig @@ -62,6 +62,9 @@ pub const Frame = struct { 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. @@ -96,6 +99,7 @@ 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 which. demo_ns: u64 = 0, demo_name: []const u8 = "", @@ -157,8 +161,10 @@ pub fn record(stats: *FrameStats, end_ns: u64, moving: bool, skipped: bool) void .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; @@ -270,14 +276,14 @@ pub fn dump(stats: *const FrameStats, path: [:0]const u8) void { }; 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\n", .{}); + 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}\n", .{ f.shaped, f.rastered, f.bytes }); + write.line(fd, &buf, "\t{d}\t{d}\t{d}\t{d}\n", .{ f.shaped, f.rastered, f.bytes, f.landed }); }; } @@ -320,6 +326,7 @@ pub fn named(name: []const u8) ?[]const Step { if (std.mem.eql(u8, name, "kinds")) return &kinds; if (std.mem.eql(u8, name, "panes")) return &panes; if (std.mem.eql(u8, name, "pdf-scroll")) return &pdf_scroll; + if (std.mem.eql(u8, name, "pdf-sdm")) return &pdf_sdm; if (std.mem.eql(u8, name, "one")) return &one; if (std.mem.eql(u8, name, "jumps")) return &jumps; if (std.mem.eql(u8, name, "longlines")) return &longlines; @@ -518,6 +525,73 @@ pub const pdf_scroll = blk: { break :blk out; }; +/// The same, on a manual of 5363 pages (the Intel SDM, combined volumes, +/// 27 MB: run where `sdm.pdf` is, a copy): its open, a wheel spun both +/// ways, PageDown held five seconds, a far Look to page 3000 and Back, gg, +/// a Look at page 4500, then slow notches and a touchpad's drag. +pub const pdf_sdm = blk: { + @setEvalBranchQuota(40_000); + var steps: [512]Step = undefined; + var n: usize = 0; + var t: u32 = 1500; + const at = struct { + fn add(s: []Step, k: *usize, ms: u32, act: @FieldType(Step, "act")) void { + s[k.*] = .{ .at_ms = ms, .act = act }; + k.* += 1; + } + }; + at.add(&steps, &n, t, .{ .phase = "open" }); + at.add(&steps, &n, t, .{ .exec = "Look sdm.pdf" }); + t += 3000; + at.add(&steps, &n, t, .{ .phase = "spin" }); + for (0..6) |_| { + at.add(&steps, &n, t, .{ .wheel = 1 }); + t += 150; + } + for (0..60) |_| { + at.add(&steps, &n, t, .{ .wheel = 1 }); + t += 8; + } + t += 600; + for (0..30) |_| { + at.add(&steps, &n, t, .{ .wheel = -1 }); + t += 8; + } + t += 600; + at.add(&steps, &n, t, .{ .phase = "held-pagedown" }); + for (0..150) |_| { + at.add(&steps, &n, t, .{ .key = .{ .cp = pardes.Key.page_down } }); + t += 33; + } + t += 800; + at.add(&steps, &n, t, .{ .phase = "far-jump" }); + at.add(&steps, &n, t, .{ .exec = "Look sdm.pdf:3000" }); + t += 1200; + at.add(&steps, &n, t, .{ .key = .{ .cp = 'o', .ctrl = true } }); + t += 1200; + at.add(&steps, &n, t, .{ .key = .{ .cp = 'g', .text = "g" } }); + at.add(&steps, &n, t + 20, .{ .key = .{ .cp = 'g', .text = "g" } }); + t += 1200; + at.add(&steps, &n, t, .{ .phase = "look-deep" }); + at.add(&steps, &n, t, .{ .exec = "Look sdm.pdf:4500" }); + t += 1500; + at.add(&steps, &n, t, .{ .phase = "slow-notches" }); + for (0..8) |_| { + at.add(&steps, &n, t, .{ .wheel = 1 }); + t += 300; + } + at.add(&steps, &n, t, .{ .phase = "slow-touch" }); + for (0..120) |_| { + at.add(&steps, &n, t, .{ .touch = 0.06 }); + t += 16; + } + t += 600; + at.add(&steps, &n, t, .{ .phase = "done" }); + at.add(&steps, &n, t, .end); + const out = steps[0..n].*; + break :blk out; +}; + /// `scrollSet` alone, on the file the session opened: one kind, for a /// profiler's run. pub const one = blk: { diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 37e4b216..15e7dac5 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -336,6 +336,8 @@ pub const State = if (enabled) struct { scroll_to_page_pending: bool = true, rasters: [raster_max]Raster = undefined, rasters_len: usize = 0, + /// Rasters installed since the last draw (the probe's `landed`). + landed: u16 = 0, spare: [raster_spare][]u8 = @splat(&.{}), spare_len: usize = 0, layout_anchor_pending: bool = false, @@ -1465,6 +1467,7 @@ fn reconcile( state.next_raster_revision +%= 1; if (state.next_raster_revision == 0) state.next_raster_revision = 1; slot.revision = state.next_raster_revision; + state.landed +|= 1; } state.trimSpares(gpa); } @@ -2880,6 +2883,10 @@ pub fn draw( state.document_scroll_y = shown; defer state.document_scroll_y = state.drawn_y; if (pane_id == core.active) core.frames.scroll = @floatCast(shown); + defer { + core.frames.landed +|= state.landed; + state.landed = 0; + } const visible = renderFrame( state, core.pdf_gpa, -- cgit v1.3