summaryrefslogtreecommitdiff
path: root/src/sketch/derived.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/sketch/derived.zig')
-rw-r--r--src/sketch/derived.zig56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/sketch/derived.zig b/src/sketch/derived.zig
new file mode 100644
index 0000000..c42a322
--- /dev/null
+++ b/src/sketch/derived.zig
@@ -0,0 +1,56 @@
+//! Data computed from State, kept out of it.
+const std = @import("std");
+const abi = @import("abi");
+
+/// A `T` computed in `draw` from a few State fields, kept in Session: the
+/// segments of a Koch curve from its generation, an L-system's sentence,
+/// a tessellation too big to redo every frame. State keeps what `update`
+/// changes (the generation, one byte), so snapshots and replays stay
+/// small; this keeps what follows from it, however big it grows.
+///
+/// `key` says what the value was built from: pass the State fields it
+/// depends on, as a number (`s.generation`) or a hash. `stale` is true when
+/// the key differs, and on the first frame after a reload, since new code
+/// may compute it differently; then rebuild `value`. A seek or a replay
+/// changes the key like an update does, so what is drawn always follows
+/// State, and the timeline needs nothing more.
+///
+/// pub const Session = struct { curve: sk.Derived(std.ArrayList(Segment)) = .{ .value = .empty } };
+/// if (ss.curve.stale(s.generation, f.in)) try koch(&ss.curve.value, f.session, s.generation);
+///
+/// After a failed rebuild call `forget`, so the next frame tries again.
+pub fn Derived(comptime T: type) type {
+ return struct {
+ const Self = @This();
+
+ value: T,
+ /// The key `value` was built for; null before the first build or
+ /// after `forget`.
+ key: ?u64 = null,
+
+ /// True when `value` must be rebuilt for `key`; it is then taken
+ /// as built for `key`.
+ pub fn stale(d: *Self, key: u64, in: *const abi.Input) bool {
+ if (d.key == key and !in.reloaded) return false;
+ d.key = key;
+ return true;
+ }
+
+ /// The next `stale` is true whatever its key.
+ pub fn forget(d: *Self) void {
+ d.key = null;
+ }
+ };
+}
+
+test "stale when the key changes, after a reload, and after forget" {
+ var d: Derived(u32) = .{ .value = 0 };
+ const live: abi.Input = .{};
+ try std.testing.expect(d.stale(3, &live));
+ try std.testing.expect(!d.stale(3, &live));
+ try std.testing.expect(d.stale(4, &live));
+ try std.testing.expect(d.stale(4, &.{ .reloaded = true }));
+ try std.testing.expect(!d.stale(4, &live));
+ d.forget();
+ try std.testing.expect(d.stale(4, &live));
+}