summaryrefslogtreecommitdiff
path: root/src/host/timeline.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-30 21:34:41 -0300
committerGabriel Schneider <[email protected]>2026-11-12 13:22:02 -0300
commit2348776791e9dd17afeb12a06ba42a4a71917bcf (patch)
tree780c4b12b76c8b97a28408dd40944d65f159fdc7 /src/host/timeline.zig
parent590ba7b9b579b97e34b51ab7e3460ebc85713343 (diff)
downloadsketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.tar.gz
sketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.zip
sketchbook: a drawing layer on top, host fixes for replay and migration
Diffstat (limited to 'src/host/timeline.zig')
-rw-r--r--src/host/timeline.zig216
1 files changed, 176 insertions, 40 deletions
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index cd65478..8a5448a 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -3,6 +3,11 @@
//!
//! Playback is host state, not sketch state: wall clocks, modes and cursors
//! must not contaminate byte comparisons between two runs of a sketch.
+//!
+//! Recordings are frames: each frame's events, then its `tick`. Playback,
+//! seek and step only ever stop between frames, and `frames` cuts a run of
+//! events into them, so `update` sees exactly the frames it saw live, one
+//! call each.
const std = @import("std");
const posix = std.posix;
const abi = @import("abi");
@@ -19,13 +24,52 @@ pub const Recording = extern struct {
count: u32,
snapshot: u32,
magic: u32,
- reserved: [3]u32,
+ /// The build that recorded it (`build`, two halves), 0 when unknown.
+ build_low: u32,
+ build_high: u32,
+ reserved: u32,
events: [capacity]abi.Event,
slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8,
pub fn slice(r: *const Recording) []const abi.Event {
return r.events[0..r.count];
}
+ pub fn build(r: *const Recording) u64 {
+ return @as(u64, r.build_high) << 32 | r.build_low;
+ }
+ /// Events up to the end of the last whole frame.
+ pub fn whole(r: *const Recording) usize {
+ return frameStart(r.slice(), r.count);
+ }
+};
+
+/// The largest frame boundary at or before `index`: 0, or just after a tick.
+pub fn frameStart(events: []const abi.Event, index: usize) usize {
+ var i = @min(index, events.len);
+ while (i > 0 and events[i - 1].kind != .tick) i -= 1;
+ return i;
+}
+
+/// Cuts events into frames, each ending with its tick. Events after the
+/// last tick (a frame not finished) are never returned.
+pub fn frames(events: []const abi.Event) Frames {
+ return .{ .events = events };
+}
+
+pub const Frames = struct {
+ events: []const abi.Event,
+ start: usize = 0,
+
+ pub fn next(f: *Frames) ?[]const abi.Event {
+ var i = f.start;
+ while (i < f.events.len) : (i += 1) {
+ if (f.events[i].kind != .tick) continue;
+ const frame = f.events[f.start .. i + 1];
+ f.start = i + 1;
+ return frame;
+ }
+ return null;
+ }
};
comptime {
@@ -65,16 +109,9 @@ pub const Bank = struct {
if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording;
return r;
}
- pub const Diff = struct { count: usize = 0, first: ?usize = null, last: ?usize = null };
- pub fn compare(self: Bank, a: usize, b: usize) Diff {
- var diff: Diff = .{};
- for (self.slot(a), self.slot(b), 0..) |x, y, i| {
- if (x == y) continue;
- diff.count += 1;
- if (diff.first == null) diff.first = i;
- diff.last = i;
- }
- return diff;
+ /// Leaf by leaf (`memory.compare`): padding never differs.
+ pub fn compare(self: Bank, a: usize, b: usize) memory.Diff {
+ return memory.compare(self.state.layout, self.slot(a), self.slot(b));
}
};
@@ -85,37 +122,55 @@ pub const Timeline = struct {
cursor: usize = 0,
position: u64 = 0,
clock: u64 = 0,
+ /// Set whenever live state is restored from a snapshot, for the host
+ /// to reset the input state that went with the old bytes.
+ restored: bool = false,
+
+ /// Restores a snapshot into live state.
+ pub fn restore(self: *Timeline, index: usize) !void {
+ try self.bank.restore(index);
+ self.restored = true;
+ }
- pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64) !void {
+ /// `build` identifies the code recording (0: unknown); `play` warns
+ /// when it differs.
+ pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64, build: u64) !void {
// An unused snapshot captures the current state; an existing one is
// restored, so several recordings can branch from exactly those bytes.
if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot);
- try self.bank.restore(snapshot);
+ try self.restore(snapshot);
const r = self.bank.recording(index);
@memset(std.mem.asBytes(r)[0..32], 0);
r.magic = recording_magic;
r.snapshot = @intCast(snapshot);
+ r.build_low = @truncate(build);
+ r.build_high = @truncate(build >> 32);
self.selected = index;
self.cursor = 0;
self.position = 0;
self.clock = now;
self.mode = .recording;
}
- pub fn capture(self: *Timeline, event: abi.Event) !void {
+ /// Records one frame (its events, then its tick) and rewrites their
+ /// times as recorded, so live `update` sees exactly what a replay will.
+ /// A frame that does not fit ends the recording before it.
+ pub fn capture(self: *Timeline, frame: []abi.Event) !void {
if (self.mode != .recording) return;
const r = self.bank.recording(self.selected);
- if (r.count == capacity) {
+ if (frame.len > capacity - r.count) {
self.mode = .live;
return error.RecordingFull;
}
- var e = event;
- // Queued events can predate the start command. Keep insertion order and
- // nondecreasing times, including several events at the same timestamp.
- e.time = @max(e.time -| self.clock, r.duration);
- r.events[r.count] = e;
- r.count += 1;
- r.duration = e.time;
- self.position = e.time;
+ for (frame) |*e| {
+ // Queued events can predate the start command. Keep insertion
+ // order and nondecreasing times, including several events at the
+ // same timestamp.
+ e.time = @max(e.time -| self.clock, r.duration);
+ r.events[r.count] = e.*;
+ r.count += 1;
+ r.duration = e.time;
+ }
+ self.position = r.duration;
self.cursor = r.count;
}
pub fn stop(self: *Timeline, now: u64) void {
@@ -128,7 +183,7 @@ pub const Timeline = struct {
}
pub fn play(self: *Timeline, index: usize, now: u64) !void {
const r = try self.bank.get(index);
- try self.bank.restore(r.snapshot);
+ try self.restore(r.snapshot);
self.selected = index;
self.cursor = 0;
self.position = 0;
@@ -143,53 +198,61 @@ pub const Timeline = struct {
self.mode = .playing;
}
}
- /// The recorded events due by `now`. Feed them to the same `update` that
- /// live input goes through.
+ /// The recorded frames due by `now`: whole frames, whose ticks are due
+ /// (a frame's input comes before its tick, so input alone is never
+ /// due). Feed them to the same `update` that live input goes through.
pub fn tick(self: *Timeline, now: u64) []const abi.Event {
if (self.mode != .playing) return &.{};
const r = self.bank.recording(self.selected);
self.position = @min(r.duration, self.position +| (now -| self.clock));
self.clock = now;
const start = self.cursor;
- while (self.cursor < r.count and r.events[self.cursor].time <= self.position) self.cursor += 1;
+ var i = self.cursor;
+ while (i < r.count and r.events[i].time <= self.position) : (i += 1) {
+ if (r.events[i].kind == .tick) self.cursor = i + 1;
+ }
if (self.position == r.duration) self.mode = .paused;
return r.events[start..self.cursor];
}
- /// Restores the snapshot and returns the first `count` events to replay,
- /// so seeking backwards works too.
+ /// Restores the snapshot and returns the frames that make up the first
+ /// `count` events (rounded down to a whole frame) to replay, so seeking
+ /// backwards works too.
pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event {
const r = try self.bank.get(self.selected);
- try self.bank.restore(r.snapshot);
- self.cursor = @min(count, r.count);
+ try self.restore(r.snapshot);
+ self.cursor = frameStart(r.slice(), count);
self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time;
self.mode = .paused;
return r.events[0..self.cursor];
}
+ /// To the last frame whose tick is at or before `time`.
pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event {
const r = try self.bank.get(self.selected);
const position = @min(time, r.duration);
var count: usize = 0;
- while (count < r.count and r.events[count].time <= position) count += 1;
+ for (r.slice(), 0..) |e, i| {
+ if (e.time > position) break;
+ if (e.kind == .tick) count = i + 1;
+ }
const events = try self.seekCount(count);
self.position = position;
return events;
}
- /// Moves by `steps` input events, passing over frame ticks.
+ /// Moves by `steps` frames, forwards or back.
pub fn step(self: *Timeline, steps: i64) ![]const abi.Event {
const r = try self.bank.get(self.selected);
- var cursor = self.cursor;
+ const events = r.slice();
+ var cursor = frameStart(events, self.cursor);
var remaining = @abs(steps);
while (remaining > 0) : (remaining -= 1) {
if (steps > 0) {
- while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1;
- if (cursor == r.count) break;
+ const end = r.whole();
+ if (cursor == end) break;
cursor += 1;
- // Include the frame's tick so time-driven sketches advance too.
- while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1;
+ while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1;
} else {
- while (cursor > 0 and r.events[cursor - 1].kind == .tick) cursor -= 1;
if (cursor == 0) break;
- cursor -= 1;
+ cursor = frameStart(events, cursor - 1);
}
}
return self.seekCount(cursor);
@@ -206,3 +269,76 @@ pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 {
};
return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true });
}
+
+test "frames are whole: input waits for its tick, live and in playback" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ // A bank on plain memory: one slot of 8 bytes, snapshot 1 used.
+ var file: memory.StateFile = undefined;
+ file.map = try a.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.slot_count * memory.page);
+ @memset(file.map, 0);
+ file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 0b11, .field_count = 0, .strings_len = 0 };
+ file.layout = .{};
+ const inputs = try a.alignedAlloc(u8, .fromByteUnits(memory.page), recording_len);
+ @memset(inputs, 0);
+ var t: Timeline = .{ .bank = .{ .state = &file, .inputs = inputs } };
+ // Frame k: a move at 10k ms, its tick at 10k + 5 ms; then a move with
+ // no tick (a frame cut off).
+ try t.startRecording(0, 1, 1000, 7);
+ try std.testing.expect(t.restored);
+ for (0..4) |k| {
+ var frame = [_]abi.Event{
+ .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) },
+ abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667),
+ };
+ try t.capture(&frame);
+ // Live update sees the recorded times.
+ try std.testing.expectEqual(@as(u64, k * 10_000_000 + 5_000_000), frame[1].time);
+ }
+ const r = t.bank.recording(0);
+ r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 };
+ r.count += 1;
+ t.stop(1000 + 41_000_000);
+ try std.testing.expectEqual(@as(u64, 7), r.build());
+
+ try t.play(0, 0);
+ var delivered: usize = 0;
+ // Every moment between 0 and the end, 1 ms apart.
+ var now: u64 = 0;
+ while (t.mode == .playing) : (now += 1_000_000) {
+ const events = t.tick(now);
+ if (events.len == 0) continue;
+ try std.testing.expectEqual(abi.Event.Kind.tick, events[events.len - 1].kind);
+ var it = frames(events);
+ while (it.next()) |frame| {
+ try std.testing.expectEqual(@as(usize, 2), frame.len);
+ delivered += 1;
+ }
+ }
+ try std.testing.expectEqual(@as(usize, 4), delivered);
+ try std.testing.expectEqual(@as(usize, 8), t.cursor);
+
+ // A seek between a frame's input and its tick stops before the frame.
+ try std.testing.expectEqual(@as(usize, 4), (try t.seekTime(22_000_000)).len);
+ try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(r.count)).len);
+ try std.testing.expectEqual(@as(usize, 6), (try t.step(-1)).len);
+ try std.testing.expectEqual(@as(usize, 8), (try t.step(5)).len);
+ try std.testing.expectEqual(@as(usize, 2), (try t.step(-3)).len);
+ // The cut-off frame is never fed.
+ var it = frames(r.slice());
+ var n: usize = 0;
+ while (it.next()) |_| n += 1;
+ try std.testing.expectEqual(@as(usize, 4), n);
+}
+
+test "a tick's dt reads back the same live and replayed" {
+ // E4: nanoseconds do not survive f32 seconds; both sides read the f32.
+ for ([_]u64{ 16_666_667, 16_666_666, 15_000_001, 33_333_333, 0, 1 }) |dt| {
+ const live = abi.Event.tick(5, dt);
+ var recorded = live;
+ recorded.time = 0;
+ try std.testing.expectEqual(live.tickDt(), recorded.tickDt());
+ try std.testing.expect(@abs(@as(i64, @intCast(live.tickDt())) - @as(i64, @intCast(dt))) < 8);
+ }
+}