diff options
Diffstat (limited to 'examples/noc/src/noise_walker.zig')
| -rw-r--r-- | examples/noc/src/noise_walker.zig | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/examples/noc/src/noise_walker.zig b/examples/noc/src/noise_walker.zig new file mode 100644 index 0000000..f1998fc --- /dev/null +++ b/examples/noc/src/noise_walker.zig @@ -0,0 +1,61 @@ +//! Example 0.6: Perlin Noise Walker. Noise moves a circle; the canvas is +//! never cleared, so the circles pile up into a trail, drawn into an +//! offscreen image that keeps them (`f.target`). +const std = @import("std"); +const sk = @import("sketch"); +const noise = @import("processing_noise.zig").noise; + +pub const name = "noise_walker"; +pub const width = 640; +pub const height = 360; + +const Walker = struct { + tx: f32 = 0, + ty: f32 = 10000, + x: f32 = 0, + y: f32 = 0, + + fn step(w: *Walker) void { + w.x = std.math.lerp(0, width, noise(w.tx, 0, 0)); + w.y = std.math.lerp(0, height, noise(w.ty, 0, 0)); + w.tx += 0.01; + w.ty += 0.01; + } +}; + +pub const State = struct { + walker: Walker = .{}, + clock: sk.Clock = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| s.walker.step(); +} + +pub const Session = struct { + trail: sk.Image = .none, + /// The walk again, as far as the trail shows it. + shadow: Walker = .{}, + drawn: u64 = 0, +}; + +const pen: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; + +/// The trail is a cache of the walk, not State: after a jump (a seek, a +/// load, a reload) it is painted again from the first step. +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + if (ss.trail == .none or f.in.jumped) { + if (ss.trail == .none) ss.trail = f.host.newImage(width, height); + ss.* = .{ .trail = ss.trail }; + f.target(ss.trail); + f.clear(.white); + } else f.target(ss.trail); + while (ss.drawn < s.clock.count) : (ss.drawn += 1) { + ss.shadow.step(); + sk.draw.circle(f, .{ ss.shadow.x, ss.shadow.y }, 24, pen); + } + // A `set` moved the walker off the walk: go on from there. + ss.shadow = s.walker; + f.target(.none); + f.image(ss.trail, .{ .x = 0, .y = 0, .w = width, .h = height }, .{}); +} |
