diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
| commit | 6933f99ddb2d7103515d26838496309a807bba26 (patch) | |
| tree | 991c2fe7d4a57957222876e190fa4d16a0fb889c /examples/noc/src | |
| parent | 82fca5c9f29124f37f6dcd08e73e6999ce44a69d (diff) | |
| download | sketchbook-6933f99ddb2d7103515d26838496309a807bba26.tar.gz sketchbook-6933f99ddb2d7103515d26838496309a807bba26.zip | |
Move standalone sketches into sketchbook examples
Diffstat (limited to 'examples/noc/src')
22 files changed, 1820 insertions, 0 deletions
diff --git a/examples/noc/src/accel_to_mouse.zig b/examples/noc/src/accel_to_mouse.zig new file mode 100644 index 0000000..9f6e8af --- /dev/null +++ b/examples/noc/src/accel_to_mouse.zig @@ -0,0 +1,31 @@ +//! Example 1.10: Accelerating towards the mouse. +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "accel_to_mouse"; +pub const width = 640; +pub const height = 360; + +const topspeed = 5; + +pub const State = struct { + position: vec.Vec = .{ width / 2, height / 2 }, + velocity: vec.Vec = .{ 0, 0 }, + clock: sk.Clock = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| { + const mouse: vec.Vec = .{ in.mouse_x, in.mouse_y }; + const acceleration = vec.withLength(mouse - s.position, 0.2); + s.velocity = vec.clampLength(s.velocity + acceleration, topspeed); + s.position += s.velocity; + } +} + +const ball: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + sk.draw.circle(f, s.position, 24, ball); +} diff --git a/examples/noc/src/additive_blending.zig b/examples/noc/src/additive_blending.zig new file mode 100644 index 0000000..a40a883 --- /dev/null +++ b/examples/noc/src/additive_blending.zig @@ -0,0 +1,63 @@ +//! Example 4.9: Additive Blending. The smoke of 4.8 tinted magenta, three +//! particles a step, and drawn with `f.blend(.add)` (`blendMode(ADD)`), +//! so where they pile up they glow towards white. The pointer's x sets +//! the wind. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; +const windArrow = @import("smoke.zig").windArrow; + +pub const name = "additive_blending"; +pub const width = 640; +pub const height = 360; + +/// A particle lives 41 steps (100 down by 2.5 until below 0), and three +/// are added a step. +const max_particles = 128; +const origin: vec.Vec = .{ width / 2, height - 75 }; + +const Particle = struct { + position: vec.Vec, + velocity: vec.Vec, + lifespan: f32 = 100, + + fn init(rng: std.Random) Particle { + return .{ .position = origin, .velocity = .{ rng.floatNorm(f32) * 0.3, rng.floatNorm(f32) * 0.3 - 1 } }; + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(49), + particles: sk.List(Particle, max_particles) = .{}, + wind: f32 = 0, + clock: sk.Clock = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| { + s.wind = std.math.lerp(-0.2, 0.2, in.mouse_x / width); + var i = s.particles.count(); + while (i > 0) { + i -= 1; + const p = &s.particles.slice()[i]; + p.velocity += vec.Vec{ s.wind, 0 }; + p.position += p.velocity; + p.lifespan -= 2.5; + if (p.lifespan < 0) _ = s.particles.orderedRemove(i); + } + for (0..3) |_| s.particles.appendBounded(.init(s.rng.random())) catch {}; + } +} + +const magenta = sk.Color.hex(0xff64ff); + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(.black); + f.blend(.add); + const texture = f.host.loadImage("assets/texture.png"); + for (s.particles.constSlice()) |p| { + if (p.lifespan == 100) continue; // added this step: not shown yet + f.imageAt(texture, .translate(p.position[0], p.position[1]), .{ .tint = magenta.alphaFloat(p.lifespan / 255) }); + } + windArrow(f, s.wind); +} diff --git a/examples/noc/src/angular_forces.zig b/examples/noc/src/angular_forces.zig new file mode 100644 index 0000000..75183f5 --- /dev/null +++ b/examples/noc/src/angular_forces.zig @@ -0,0 +1,81 @@ +//! Example 3.2: Forces with (arbitrary) angular motion. Twenty movers orbit +//! an attractor and spin with their sideways acceleration. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "angular_forces"; +pub const width = 640; +pub const height = 360; + +const Mover = struct { + mass: f32 = 1, + radius: f32 = 8, + position: vec.Vec = .{ 0, 0 }, + velocity: vec.Vec = .{ 0, 0 }, + acceleration: vec.Vec = .{ 0, 0 }, + angle: f32 = 0, + angle_velocity: f32 = 0, + angle_acceleration: f32 = 0, + + fn applyForce(m: *Mover, force: vec.Vec) void { + m.acceleration += vec.scale(force, 1 / m.mass); + } + fn update(m: *Mover) void { + m.velocity += m.acceleration; + m.position += m.velocity; + m.angle_acceleration = m.acceleration[0] / 10.0; + m.angle_velocity = std.math.clamp(m.angle_velocity + m.angle_acceleration, -0.1, 0.1); + m.angle += m.angle_velocity; + m.acceleration = .{ 0, 0 }; + } +}; + +const Attractor = struct { + position: vec.Vec = .{ width / 2, height / 2 }, + mass: f32 = 20, + g: f32 = 1, + + fn attract(a: Attractor, m: Mover) vec.Vec { + const force = a.position - m.position; + const distance = std.math.clamp(vec.length(force), 5, 25); + return vec.withLength(force, (a.g * a.mass * m.mass) / (distance * distance)); + } +}; +const attractor: Attractor = .{}; + +pub const State = struct { + movers: [20]Mover = @splat(.{}), + rng: std.Random.Xoshiro256 = .init(32), + clock: sk.Clock = .{}, +}; + +pub fn init(s: *State) void { + const r = s.rng.random(); + for (&s.movers) |*m| { + const position: vec.Vec = .{ std.math.lerp(0, width, r.float(f32)), std.math.lerp(0, height, r.float(f32)) }; + const mass = std.math.lerp(0.1, 2, r.float(f32)); + const velocity: vec.Vec = .{ std.math.lerp(-1, 1, r.float(f32)), std.math.lerp(-1, 1, r.float(f32)) }; + m.* = .{ .mass = mass, .radius = mass * 8, .position = position, .velocity = velocity }; + } +} + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| for (&s.movers) |*m| { + m.applyForce(attractor.attract(m.*)); + m.update(); + }; +} + +const attractor_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(175).alpha(200), .stroke = .black, .width = 2 }; +const mover_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + sk.draw.circle(f, attractor.position, attractor.mass, attractor_pen); + for (s.movers) |m| { + const pen = mover_pen.transformed(.place(m.position, m.angle)); // push; translate; rotate + sk.draw.circle(f, .{ 0, 0 }, m.radius, pen); + sk.draw.line(f, .{ 0, 0 }, .{ m.radius, 0 }, pen); + } +} diff --git a/examples/noc/src/bin_lattice.zig b/examples/noc/src/bin_lattice.zig new file mode 100644 index 0000000..4766f6c --- /dev/null +++ b/examples/noc/src/bin_lattice.zig @@ -0,0 +1,192 @@ +//! Nature of Code, Example 5.12: Bin-lattice spatial subdivision. The +//! flocking of 5.11, but each boid looks only at the boids in its own and +//! the eight surrounding cells of a 40-pixel grid, so 2000 boids cost about +//! what 200 did with every pair. The shaded cells are the pointer's +//! neighbourhood; drag to add boids. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "bin_lattice"; +pub const width = 640; +pub const height = 360; + +const max_boids = 4096; +const resolution = 40; +const cols = width / resolution; +const rows = height / resolution; + +const Boid = struct { + position: vec.Vec, + velocity: vec.Vec, + const r = 3.0; + const maxspeed = 3; + const maxforce = 0.05; + + fn init(rng: std.Random, x: f32, y: f32) Boid { + return .{ .position = .{ x, y }, .velocity = .{ std.math.lerp(-1, 1, rng.float(f32)), std.math.lerp(-1, 1, rng.float(f32)) } }; + } + + fn seek(self: *const Boid, target: vec.Vec) vec.Vec { + const desired = vec.withLength(target - self.position, maxspeed); + return vec.clampLength(desired - self.velocity, maxforce); + } + + fn borders(self: *Boid) void { + const p = &self.position; + if (p[0] < -r) p[0] = width + r; + if (p[1] < -r) p[1] = height + r; + if (p[0] > width + r) p[0] = -r; + if (p[1] > height + r) p[1] = -r; + } +}; + +/// The bin lattice as a counting sort: boid indices ordered by cell, and +/// where each cell's run of them starts. Indices, not pointers or per-cell +/// lists: two fixed arrays that save, scrub and migrate like any other +/// State. It is derived data, rebuilt from the positions at every step, so +/// a reload that changes `resolution` (and the array sizes) loses nothing. +const Grid = struct { + /// The boids in cell `c` (row-major) are `order[start[c]..start[c + 1]]`, + /// in boid order. + start: [cols * rows + 1]u16 = @splat(0), + order: [max_boids]u16 = @splat(0), + + /// The cell a boid is binned in; boids just off the edge go in the edge + /// cells, as `constrain` does in the original. + fn binOf(p: vec.Vec) usize { + const col: usize = @intFromFloat(std.math.clamp(@floor(p[0] / resolution), 0, cols - 1)); + const row: usize = @intFromFloat(std.math.clamp(@floor(p[1] / resolution), 0, rows - 1)); + return row * cols + col; + } + + fn build(g: *Grid, boids: []const Boid) void { + @memset(&g.start, 0); + for (boids) |b| g.start[binOf(b.position) + 1] += 1; + for (1..g.start.len) |c| g.start[c] += g.start[c - 1]; + var next = g.start; + for (boids, 0..) |b, i| { + const c = binOf(b.position); + g.order[next[c]] = @intCast(i); + next[c] += 1; + } + } + + fn cell(g: *const Grid, col: usize, row: usize) []const u16 { + const c = row * cols + col; + return g.order[g.start[c]..g.start[c + 1]]; + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(512), + boids: sk.List(Boid, max_boids) = .{}, + grid: Grid = .{}, + clock: sk.Clock = .{}, +}; + +pub fn init(s: *State) void { + const rng = s.rng.random(); + for (0..2000) |_| { + const x = rng.float(f32) * width; + const y = rng.float(f32) * height; + s.boids.appendBounded(.init(rng, x, y)) catch {}; + } +} + +pub fn update(s: *State, in: *const sk.Input) void { + // mouseDragged: a boid per pointer move with the button down. + if (in.buttons & 1 != 0) for (in.events) |e| if (e.kind == .mouse_move) { + s.boids.appendBounded(.init(s.rng.random(), e.x, e.y)) catch {}; + }; + for (0..s.clock.steps(in)) |_| { + // Binned once per step, from where the boids were; each then moves + // in turn, seeing the ones before it where they have moved to. + const boids = s.boids.slice(); + s.grid.build(boids); + for (boids) |*boid| flock(boid, boids, &s.grid); + } +} + +/// flock() + update() + borders() over the 3x3 cells around the boid: +/// separation, alignment and cohesion summed in one pass over them. +fn flock(self: *Boid, boids: []const Boid, grid: *const Grid) void { + const desired_separation = 25; + const neighbor_distance = 50; + var away: vec.Vec = .{ 0, 0 }; + var close: f32 = 0; + var velocities: vec.Vec = .{ 0, 0 }; + var positions: vec.Vec = .{ 0, 0 }; + var near: f32 = 0; + const col: i32 = @intFromFloat(@floor(self.position[0] / resolution)); + const row: i32 = @intFromFloat(@floor(self.position[1] / resolution)); + for ([_]i32{ -1, 0, 1 }) |dc| for ([_]i32{ -1, 0, 1 }) |dr| { + const c = col + dc; + const r = row + dr; + if (c < 0 or c >= cols or r < 0 or r >= rows) continue; + for (grid.cell(@intCast(c), @intCast(r))) |j| { + const other = boids[j]; + const d = vec.distance(self.position, other.position); + if (d > 0 and d < desired_separation) { + away += vec.scale(vec.normalize(self.position - other.position), 1 / d); + close += 1; + } + if (d > 0 and d < neighbor_distance) { + velocities += other.velocity; + positions += other.position; + near += 1; + } + } + }; + var sep: vec.Vec = .{ 0, 0 }; + if (close > 0) away = vec.scale(away, 1 / close); + if (vec.length(away) > 0) sep = vec.clampLength(vec.withLength(away, Boid.maxspeed) - self.velocity, Boid.maxforce); + var ali: vec.Vec = .{ 0, 0 }; + var coh: vec.Vec = .{ 0, 0 }; + if (near > 0) { + ali = vec.clampLength(vec.withLength(vec.scale(velocities, 1 / near), Boid.maxspeed) - self.velocity, Boid.maxforce); + coh = self.seek(vec.scale(positions, 1 / near)); + } + self.velocity = vec.clampLength(self.velocity + vec.scale(sep, 1.5) + ali + coh, Boid.maxspeed); + self.position += self.velocity; + self.borders(); +} + +const shape = [_]vec.Vec{ .{ Boid.r * 2, 0 }, .{ -Boid.r * 2, -Boid.r }, .{ -Boid.r * 2, Boid.r } }; + +/// The grid, the pointer's neighbourhood, then every body in one shape and +/// every outline in another: four `shape` commands for any number of boids. +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + var lines: sk.draw.Tessellation = .empty; + var cells: sk.draw.Tessellation = .empty; + var bodies: sk.draw.Tessellation = .empty; + var outlines: sk.draw.Tessellation = .empty; + const gpa = f.scratch; + for (0..cols + 1) |i| { + const x: f32 = @floatFromInt(i * resolution); + lines.strokeLine(gpa, .{ x, 0 }, .{ x, height }, 1, .identity) catch return; + } + for (0..rows + 1) |j| { + const y: f32 = @floatFromInt(j * resolution); + lines.strokeLine(gpa, .{ 0, y }, .{ width, y }, 1, .identity) catch return; + } + const mouse_col: i32 = @intFromFloat(@floor(std.math.clamp(f.in.mouse_x, -1e6, 1e6) / resolution)); + const mouse_row: i32 = @intFromFloat(@floor(std.math.clamp(f.in.mouse_y, -1e6, 1e6) / resolution)); + for ([_]i32{ -1, 0, 1 }) |dc| for ([_]i32{ -1, 0, 1 }) |dr| { + const c = mouse_col + dc; + const r = mouse_row + dr; + if (c < 0 or c >= cols or r < 0 or r >= rows) continue; + const rect: vec.Rect = .{ .x = @floatFromInt(c * resolution), .y = @floatFromInt(r * resolution), .w = resolution, .h = resolution }; + cells.fillRect(gpa, rect, .identity) catch return; + }; + for (s.boids.constSlice()) |boid| { + const xf: vec.Affine = .place(boid.position, vec.angle(boid.velocity)); + bodies.fillPolygon(gpa, &shape, xf) catch break; + outlines.strokePolygon(gpa, &shape, 1, xf) catch break; + } + f.shape(&lines, .gray(200)); + f.shape(&cells, sk.Color.hex(0xff3232).alpha(100)); + f.shape(&bodies, .gray(127)); + f.shape(&outlines, .black); +} diff --git a/examples/noc/src/bouncing_ball.zig b/examples/noc/src/bouncing_ball.zig new file mode 100644 index 0000000..24d951b --- /dev/null +++ b/examples/noc/src/bouncing_ball.zig @@ -0,0 +1,28 @@ +//! Example 1.2: Bouncing Ball, with vectors. +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "bouncing_ball"; +pub const width = 640; +pub const height = 360; + +pub const State = struct { + position: vec.Vec = .{ 100, 100 }, + velocity: vec.Vec = .{ 2.5, 2 }, + clock: sk.Clock = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| { + s.position += s.velocity; + if (s.position[0] > width or s.position[0] < 0) s.velocity[0] *= -1; + if (s.position[1] > height or s.position[1] < 0) s.velocity[1] *= -1; + } +} + +const ball: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + sk.draw.circle(f, s.position, 24, ball); +} diff --git a/examples/noc/src/flappy_bird.zig b/examples/noc/src/flappy_bird.zig new file mode 100644 index 0000000..77c1e4a --- /dev/null +++ b/examples/noc/src/flappy_bird.zig @@ -0,0 +1,140 @@ +//! Nature of Code, Example 11.1: Flappy Bird, as a game: click or space +//! flaps, a pipe ends the round, a click starts the next. The book's +//! version only prints "OOPS!" and flies on; the score, the end of a round +//! and the restart are added here. +const std = @import("std"); +const sk = @import("sketch"); + +pub const name = "flappy_bird"; +pub const width = 640; +pub const height = 360; + +const bird_x = 50; +const gravity = 0.5; +const flap_force = -10; +const pipe_width = 20; +const pipe_speed = 2; +/// The gap between a pipe's top and bottom. +const spacing = 100; +/// Steps between new pipes (the book's `frameCount % 100`). +const pipe_every = 100; + +const Bird = struct { + y: f32 = 120, + velocity: f32 = 0, + + fn step(b: *Bird) void { + b.velocity += gravity; + b.y += b.velocity; + b.velocity *= 0.95; + // The floor. + if (b.y > height) { + b.y = height; + b.velocity = 0; + } + } +}; + +const Pipe = struct { + x: f32 = width, + top: f32, + /// Counted in the score once the bird is past it. + passed: bool = false, + + fn collides(p: Pipe, b: Bird) bool { + const vertical = b.y < p.top or b.y > p.top + spacing; + const horizontal = bird_x > p.x and bird_x < p.x + pipe_width; + return vertical and horizontal; + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(11), + bird: Bird = .{}, + pipes: sk.List(Pipe, 8) = .{}, + /// Steps this round, for spacing the pipes. + steps: u32 = 0, + score: u32 = 0, + best: u32 = 0, + /// The round is over: the bird hit pipe `hit`. + over: bool = false, + hit: u8 = 0, + clock: sk.Clock = .{}, +}; + +pub fn init(s: *State) void { + newRound(s); +} + +fn newRound(s: *State) void { + s.bird = .{}; + s.pipes.clear(); + s.steps = 0; + s.score = 0; + s.over = false; + addPipe(s); +} + +fn addPipe(s: *State) void { + s.pipes.appendBounded(.{ .top = sk.math.uniform(s.rng.random(), 0, height - spacing) }) catch {}; +} + +pub fn update(s: *State, in: *const sk.Input) void { + const flap = in.mousePressed(.left) != null or in.pressed(sk.Key.space); + if (s.over) { + // The round is over: nothing moves until the next one starts. + if (flap) newRound(s); + return; + } + if (flap) s.bird.velocity += flap_force; + for (0..s.clock.steps(in)) |_| if (!s.over) step(s); +} + +fn step(s: *State) void { + // The book's order: pipes, then the bird, then maybe a new pipe. + var i = s.pipes.count(); + while (i > 0) { + i -= 1; + const p = &s.pipes.slice()[i]; + p.x -= pipe_speed; + if (p.collides(s.bird)) { + s.over = true; + s.hit = @intCast(i); + } + if (!p.passed and p.x + pipe_width < bird_x) { + p.passed = true; + s.score += 1; + s.best = @max(s.best, s.score); + } + if (p.x < -pipe_width) { + _ = s.pipes.orderedRemove(i); + if (s.over and s.hit > i) s.hit -= 1; + } + } + if (s.over) return; + s.bird.step(); + s.steps += 1; + if (s.steps % pipe_every == 0) addPipe(s); +} + +const pipe_pen: sk.draw.Pen = .{ .fill = .black }; +const panel: sk.draw.Pen = .{ .fill = sk.Color.white.alpha(220), .stroke = .gray(100), .width = 2 }; +const bird_pen: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + for (s.pipes.constSlice()) |p| { + sk.draw.rect(f, .{ .x = p.x, .y = 0, .w = pipe_width, .h = p.top }, pipe_pen); + sk.draw.rect(f, .{ .x = p.x, .y = p.top + spacing, .w = pipe_width, .h = height - p.top - spacing }, pipe_pen); + } + sk.draw.circle(f, .{ bird_x, s.bird.y }, 8, bird_pen); + // Text on panels of its own, so pipes do not hide it. + sk.draw.rect(f, .{ .x = -2, .y = -2, .w = 252, .h = 42 }, panel); + f.print(8, 8, 2, sk.Color.gray(100), "score {d} best {d}", .{ s.score, s.best }); + if (s.over) { + const p = s.pipes.constSlice()[s.hit]; + f.print(p.x, p.top + 20, 2, sk.Color.hex(0xd02020), "OOPS!", .{}); + sk.draw.rect(f, .{ .x = 150, .y = 158, .w = 340, .h = 46 }, panel); + f.print(176, 166, 2, sk.Color.black, "click to fly again", .{}); + } +} diff --git a/examples/noc/src/flocking.zig b/examples/noc/src/flocking.zig new file mode 100644 index 0000000..7ba4727 --- /dev/null +++ b/examples/noc/src/flocking.zig @@ -0,0 +1,133 @@ +//! Nature of Code, Example 5.11: Flocking. Drag the mouse to add boids. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "flocking"; +pub const width = 640; +pub const height = 360; + +/// Processing's ArrayList grows without bound; State needs a number. +const max_boids = 2048; + +const Boid = struct { + position: vec.Vec, + velocity: vec.Vec, + const r = 3.0; + const maxspeed = 3; + const maxforce = 0.05; + + fn init(rng: std.Random, x: f32, y: f32) Boid { + return .{ .position = .{ x, y }, .velocity = .{ std.math.lerp(-1, 1, rng.float(f32)), std.math.lerp(-1, 1, rng.float(f32)) } }; + } + + /// flock() + update() + borders(). `boids` includes `self`, and those + /// before it have already moved this frame, as in the original. + fn run(self: *Boid, boids: []const Boid) void { + const sep = vec.scale(self.separate(boids), 1.5); + const ali = self.alignment(boids); + const coh = self.cohere(boids); + self.velocity = vec.clampLength(self.velocity + sep + ali + coh, maxspeed); + self.position += self.velocity; + self.borders(); + } + + fn seek(self: *const Boid, target: vec.Vec) vec.Vec { + const desired = vec.withLength(target - self.position, maxspeed); + return vec.clampLength(desired - self.velocity, maxforce); + } + + fn borders(self: *Boid) void { + const p = &self.position; + if (p[0] < -r) p[0] = width + r; + if (p[1] < -r) p[1] = height + r; + if (p[0] > width + r) p[0] = -r; + if (p[1] > height + r) p[1] = -r; + } + + fn separate(self: *const Boid, boids: []const Boid) vec.Vec { + const desired_separation = 25; + var steer: vec.Vec = .{ 0, 0 }; + var count: f32 = 0; + for (boids) |other| { + const d = vec.distance(self.position, other.position); + if (d > 0 and d < desired_separation) { + steer += vec.scale(vec.normalize(self.position - other.position), 1 / d); + count += 1; + } + } + if (count > 0) steer = vec.scale(steer, 1 / count); + if (vec.length(steer) > 0) steer = vec.clampLength(vec.withLength(steer, maxspeed) - self.velocity, maxforce); + return steer; + } + + fn alignment(self: *const Boid, boids: []const Boid) vec.Vec { + const neighbor_distance = 50; + var sum: vec.Vec = .{ 0, 0 }; + var count: f32 = 0; + for (boids) |other| { + const d = vec.distance(self.position, other.position); + if (d > 0 and d < neighbor_distance) { + sum += other.velocity; + count += 1; + } + } + if (count == 0) return .{ 0, 0 }; + return vec.clampLength(vec.withLength(vec.scale(sum, 1 / count), maxspeed) - self.velocity, maxforce); + } + + fn cohere(self: *const Boid, boids: []const Boid) vec.Vec { + const neighbor_distance = 50; + var sum: vec.Vec = .{ 0, 0 }; + var count: f32 = 0; + for (boids) |other| { + const d = vec.distance(self.position, other.position); + if (d > 0 and d < neighbor_distance) { + sum += other.position; + count += 1; + } + } + if (count == 0) return .{ 0, 0 }; + return self.seek(vec.scale(sum, 1 / count)); + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(11), + boids: sk.List(Boid, max_boids) = .{}, + clock: sk.Clock = .{}, +}; + +pub fn init(s: *State) void { + for (0..120) |_| s.boids.appendBounded(.init(s.rng.random(), width / 2, height / 2)) catch {}; +} + +pub fn update(s: *State, in: *const sk.Input) void { + // mouseDragged: a boid per pointer move with the button down. + if (in.buttons & 1 != 0) for (in.events) |e| if (e.kind == .mouse_move) { + s.boids.appendBounded(.init(s.rng.random(), e.x, e.y)) catch {}; + }; + for (0..s.clock.steps(in)) |_| { + const boids = s.boids.slice(); + for (boids) |*boid| boid.run(boids); + } +} + +const shape = [_]vec.Vec{ .{ Boid.r * 2, 0 }, .{ -Boid.r * 2, -Boid.r }, .{ -Boid.r * 2, Boid.r } }; + +/// Every boid's body in one shape command and every outline in another, +/// rather than two commands per boid. Processing draws each boid's outline +/// right after its body; here all outlines come after all bodies, which +/// shows only where boids overlap. +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + var bodies: sk.draw.Tessellation = .empty; + var outlines: sk.draw.Tessellation = .empty; + for (s.boids.constSlice()) |boid| { + const xf: vec.Affine = .place(boid.position, vec.angle(boid.velocity)); + bodies.fillPolygon(f.scratch, &shape, xf) catch break; + outlines.strokePolygon(f.scratch, &shape, 1, xf) catch break; + } + f.shape(&bodies, .gray(127)); + f.shape(&outlines, .black); +} diff --git a/examples/noc/src/flow_field.zig b/examples/noc/src/flow_field.zig new file mode 100644 index 0000000..0452c56 --- /dev/null +++ b/examples/noc/src/flow_field.zig @@ -0,0 +1,104 @@ +//! Nature of Code, Example 5.4: Flow Field Following. Space toggles the +//! field's arrows; a click makes a new field. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "flow_field"; +pub const width = 640; +pub const height = 360; + +const resolution = 20; +const cols = width / resolution; +const rows = height / resolution; + +/// The field is a function of its seed, so State keeps only the seed: +/// Processing's `noiseSeed(random(10000))`. +const FlowField = struct { + seed: u32 = 0, + + fn init(rng: std.Random) FlowField { + return .{ .seed = rng.uintLessThan(u32, 10000) }; + } + + /// The arrow in column `i`, row `j`. + fn at(ff: FlowField, i: usize, j: usize) vec.Vec { + const xoff: f32 = @floatFromInt(i); + const yoff: f32 = @floatFromInt(j); + return vec.unit(std.math.lerp(0, std.math.tau, vec.noise(ff.seed, xoff * 0.1, yoff * 0.1, 0))); + } + + fn lookup(ff: FlowField, position: vec.Vec) vec.Vec { + const column: usize = @intFromFloat(std.math.clamp(@floor(position[0] / resolution), 0, cols - 1)); + const row: usize = @intFromFloat(std.math.clamp(@floor(position[1] / resolution), 0, rows - 1)); + return ff.at(column, row); + } +}; + +const Vehicle = struct { + position: vec.Vec, + velocity: vec.Vec = .{ 0, 0 }, + maxspeed: f32, + maxforce: f32, + const r = 4; + + fn follow(v: *Vehicle, flow: FlowField) void { + const desired = vec.scale(flow.lookup(v.position), v.maxspeed); + const steer = vec.clampLength(desired - v.velocity, v.maxforce); + // applyForce + update: acceleration lasts one step, so it is not State. + v.velocity = vec.clampLength(v.velocity + steer, v.maxspeed); + v.position += v.velocity; + } + + fn borders(v: *Vehicle) void { + const p = &v.position; + if (p[0] < -r) p[0] = width + r; + if (p[1] < -r) p[1] = height + r; + if (p[0] > width + r) p[0] = -r; + if (p[1] > height + r) p[1] = -r; + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(5), + debug: bool = true, + flowfield: FlowField = .{}, + vehicles: [120]Vehicle = undefined, + clock: sk.Clock = .{}, +}; + +/// setup(): defaults cannot call the PRNG, so the random parts happen here. +pub fn init(s: *State) void { + const rng = s.rng.random(); + const lerp = std.math.lerp; + s.flowfield = .init(rng); + for (&s.vehicles) |*v| v.* = .{ + .position = .{ lerp(0, width, rng.float(f32)), lerp(0, height, rng.float(f32)) }, + .maxspeed = lerp(2, 5, rng.float(f32)), + .maxforce = lerp(0.1, 0.5, rng.float(f32)), + }; +} + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.pressed(sk.Key.space)) s.debug = !s.debug; + for (in.events) |e| if (e.kind == .mouse_down) { + s.flowfield = .init(s.rng.random()); + }; + for (0..s.clock.steps(in)) |_| for (&s.vehicles) |*v| { + v.follow(s.flowfield); + v.borders(); + }; +} + +const arrow: sk.draw.Pen = .{ .stroke = .black, .width = 1 }; +const body: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; +const triangle = [_]vec.Vec{ .{ Vehicle.r * 2, 0 }, .{ -Vehicle.r * 2, -Vehicle.r }, .{ -Vehicle.r * 2, Vehicle.r } }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + if (s.debug) for (0..cols) |i| for (0..rows) |j| { + const centre = vec.scale(.{ @floatFromInt(i), @floatFromInt(j) }, resolution) + vec.splat(resolution / 2); + sk.draw.line(f, centre, centre + vec.scale(s.flowfield.at(i, j), resolution / 2), arrow); + }; + for (&s.vehicles) |*v| sk.draw.polygon(f, &triangle, body.transformed(.place(v.position, vec.angle(v.velocity)))); +} diff --git a/examples/noc/src/fluid_resistance.zig b/examples/noc/src/fluid_resistance.zig new file mode 100644 index 0000000..8b479fd --- /dev/null +++ b/examples/noc/src/fluid_resistance.zig @@ -0,0 +1,83 @@ +//! Example 2.5: Fluid Resistance. Nine movers fall under gravity and drag +//! in the lower half; a click starts them over with new masses. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "fluid_resistance"; +pub const width = 640; +pub const height = 360; + +const Liquid = struct { + area: sk.Rect, + c: f32, + + /// Processing's test is strict on all four sides; `Rect.contains` + /// includes the top and left edge, which no mover lands on exactly. + fn contains(l: Liquid, m: Mover) bool { + return l.area.contains(m.position[0], m.position[1]); + } + fn calculateDrag(l: Liquid, m: Mover) vec.Vec { + const speed = vec.length(m.velocity); + return vec.withLength(-m.velocity, l.c * speed * speed); + } +}; +const liquid: Liquid = .{ .area = .{ .x = 0, .y = height / 2, .w = width, .h = height / 2 }, .c = 0.1 }; + +const Mover = struct { + mass: f32 = 1, + radius: f32 = 8, + position: vec.Vec = .{ 0, 0 }, + velocity: vec.Vec = .{ 0, 0 }, + acceleration: vec.Vec = .{ 0, 0 }, + + fn applyForce(m: *Mover, force: vec.Vec) void { + m.acceleration += vec.scale(force, 1 / m.mass); + } + fn update(m: *Mover) void { + m.velocity += m.acceleration; + m.position += m.velocity; + m.acceleration = .{ 0, 0 }; + } + fn checkEdges(m: *Mover) void { + if (m.position[1] > height - m.radius) { + m.velocity[1] *= -0.9; + m.position[1] = height - m.radius; + } + } +}; + +pub const State = struct { + movers: [9]Mover = @splat(.{}), + rng: std.Random.Xoshiro256 = .init(25), + clock: sk.Clock = .{}, +}; + +pub fn init(s: *State) void { + reset(s); +} + +fn reset(s: *State) void { + for (&s.movers, 0..) |*m, i| { + const mass = std.math.lerp(0.5, 3, s.rng.random().float(f32)); + m.* = .{ .mass = mass, .radius = mass * 8, .position = .{ 40 + @as(f32, @floatFromInt(i)) * 70, 0 } }; + } +} + +pub fn update(s: *State, in: *const sk.Input) void { + for (in.events) |e| if (e.kind == .mouse_down) reset(s); + for (0..s.clock.steps(in)) |_| for (&s.movers) |*m| { + if (liquid.contains(m.*)) m.applyForce(liquid.calculateDrag(m.*)); + m.applyForce(.{ 0, 0.1 * m.mass }); + m.update(); + m.checkEdges(); + }; +} + +const mover_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + f.fill(liquid.area, sk.Color.gray(220)); + for (s.movers) |m| sk.draw.circle(f, m.position, m.radius, mover_pen); +} diff --git a/examples/noc/src/koch.zig b/examples/noc/src/koch.zig new file mode 100644 index 0000000..2dfa8ef --- /dev/null +++ b/examples/noc/src/koch.zig @@ -0,0 +1,79 @@ +//! Nature of Code, Example 8.5: the Koch Curve. Each click applies the +//! rules once more: four segments for every one (after 8, back to 0). +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "koch"; +pub const width = 640; +pub const height = 360; + +const max_generation = 8; + +/// The whole curve is a function of how often the rules ran, so that is +/// all State keeps: one byte, however many segments it means (65536 at +/// generation 8, 1 MiB as points). Snapshots, replays and seeks stay cheap. +pub const State = struct { + generation: u8 = 5, +}; + +/// The segments, and their picture, derived from the generation in +/// `draw` and kept here between frames. `Derived` rebuilds them when the +/// generation they were made for is not State's (a click, a seek, a +/// replay) and after a reload. +pub const Session = struct { + curve: sk.Derived(Curve) = .{ .value = .{} }, +}; + +const Segment = struct { start: vec.Vec, end: vec.Vec }; + +const Curve = struct { + segments: std.ArrayList(Segment) = .empty, + picture: sk.draw.Tessellation = .empty, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.mousePressed(.left) != null) s.generation = if (s.generation == max_generation) 0 else s.generation + 1; +} + +/// The book's `generate()`: every segment becomes four, the middle two +/// raised into a peak. +fn generate(gpa: std.mem.Allocator, segments: *std.ArrayList(Segment)) !void { + var next: std.ArrayList(Segment) = try .initCapacity(gpa, segments.items.len * 4); + for (segments.items) |line| { + const v = vec.scale(line.end - line.start, 1.0 / 3.0); + const b = line.start + v; + const d = b + v; + // Rotated by -60°, so the peak points up. + const c = b + vec.Affine.rotate(-std.math.pi / 3.0).applyVector(v); + for ([_]vec.Vec{ line.start, b, c, d }, [_]vec.Vec{ b, c, d, line.end }) |from, to| next.appendAssumeCapacity(.{ .start = from, .end = to }); + } + segments.deinit(gpa); + segments.* = next; +} + +fn build(curve: *Curve, gpa: std.mem.Allocator, generation: u8) !void { + curve.segments.clearRetainingCapacity(); + try curve.segments.append(gpa, .{ .start = .{ 0, 300 }, .end = .{ width, 300 } }); + for (0..generation) |_| try generate(gpa, &curve.segments); + // The segments join end to start: one line through their points, 2 px + // wide with round joins and ends, looks like the book's separate + // round-capped lines and draws each pixel once. + const points = try gpa.alloc(vec.Vec, curve.segments.items.len + 1); + defer gpa.free(points); + for (curve.segments.items, points[0..curve.segments.items.len]) |line, *p| p.* = line.start; + points[points.len - 1] = curve.segments.items[curve.segments.items.len - 1].end; + curve.picture.clearRetainingCapacity(); + try curve.picture.strokePath(gpa, points, .{ .width = 2, .join = .round, .cap = .round }, .identity); +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + f.clear(sk.Color.white); + if (ss.curve.stale(s.generation, f.in)) build(&ss.curve.value, f.session, s.generation) catch { + ss.curve.forget(); + f.host.log("out of session memory: curve dropped"); + return; + }; + f.shape(&ss.curve.value.picture, .black); + f.print(8, 8, 2, sk.Color.gray(100), "generation {d}: {d} segments", .{ s.generation, ss.curve.value.segments.items.len }); +} diff --git a/examples/noc/src/lsystem.zig b/examples/noc/src/lsystem.zig new file mode 100644 index 0000000..b5ac660 --- /dev/null +++ b/examples/noc/src/lsystem.zig @@ -0,0 +1,102 @@ +//! Nature of Code, Example 8.9: an L-system, drawn by a turtle. Each click +//! rewrites the sentence once more (after 5, back to the axiom). +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "lsystem"; +pub const width = 640; +pub const height = 360; + +const axiom = "F"; +/// The book's one rule; every other character stays itself. +const rule = .{ 'F', "FF+[+F-F-F]-[-F+F+F]" }; +const angle = std.math.degreesToRadians(25.0); +const max_generation = 5; + +/// The sentence follows from the axiom, the rule and how often it ran: +/// State keeps only the count. The sentence itself grows eightfold a +/// generation (11 116 characters at 4, 88 940 at 5), which is Session's +/// business, rebuilt by `Derived` when the count changes. +pub const State = struct { + generation: u8 = 4, +}; + +pub const Session = struct { + tree: sk.Derived(Tree) = .{ .value = .{} }, +}; + +const Tree = struct { + sentence: std.ArrayList(u8) = .empty, + picture: sk.draw.Tessellation = .empty, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.mousePressed(.left) != null) s.generation = if (s.generation == max_generation) 0 else s.generation + 1; +} + +/// The book's `generate()`, `generation` times. +fn rewrite(gpa: std.mem.Allocator, sentence: *std.ArrayList(u8), generation: u8) !void { + sentence.clearRetainingCapacity(); + try sentence.appendSlice(gpa, axiom); + var next: std.ArrayList(u8) = .empty; + defer next.deinit(gpa); + for (0..generation) |_| { + next.clearRetainingCapacity(); + for (sentence.items) |c| { + if (c == rule[0]) try next.appendSlice(gpa, rule[1]) else try next.append(gpa, c); + } + std.mem.swap(std.ArrayList(u8), sentence, &next); + } +} + +/// The turtle: `F` draws a step and moves along it, `+`/`-` turn, `[` +/// pushes and `]` pops. A push is a call with a copy of the transform, a +/// pop is its return: no stack to keep. +const Turtle = struct { + picture: *sk.draw.Tessellation, + gpa: std.mem.Allocator, + step: f32, + + /// Walks `sentence` from `i.*` until its `]` (or the end), placed by `xf`. + fn walk(t: Turtle, sentence: []const u8, i: *usize, start: vec.Affine) !void { + var xf = start; + while (i.* < sentence.len) { + const c = sentence[i.*]; + i.* += 1; + switch (c) { + 'F', 'G' => { + try t.picture.strokeLine(t.gpa, .{ 0, 0 }, .{ 0, -t.step }, 1, xf); + xf = xf.mul(.translate(0, -t.step)); + }, + '+' => xf = xf.mul(.rotate(angle)), + '-' => xf = xf.mul(.rotate(-angle)), + '[' => try t.walk(sentence, i, xf), + ']' => return, + else => {}, + } + } + } +}; + +fn build(tree: *Tree, gpa: std.mem.Allocator, generation: u8) !void { + try rewrite(gpa, &tree.sentence, generation); + tree.picture.clearRetainingCapacity(); + // Each generation doubles the trunk (F → FF), so the step halves to + // keep the tree the book's size: 6 px at generation 4. + const turtle: Turtle = .{ .picture = &tree.picture, .gpa = gpa, .step = 96 / std.math.pow(f32, 2, @floatFromInt(generation)) }; + var i: usize = 0; + try turtle.walk(tree.sentence.items, &i, .translate(width / 2, height)); +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + f.clear(sk.Color.white); + if (ss.tree.stale(s.generation, f.in)) build(&ss.tree.value, f.session, s.generation) catch { + ss.tree.forget(); + f.host.log("out of session memory: tree dropped"); + return; + }; + f.shape(&ss.tree.value.picture, .black); + f.print(8, height - 64, 2, sk.Color.gray(100), "generation {d}", .{s.generation}); + f.print(8, height - 36, 2, sk.Color.gray(100), "{d} characters", .{ss.tree.value.sentence.items.len}); +} 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 }, .{}); +} diff --git a/examples/noc/src/path_following.zig b/examples/noc/src/path_following.zig new file mode 100644 index 0000000..b1715dc --- /dev/null +++ b/examples/noc/src/path_following.zig @@ -0,0 +1,111 @@ +//! Nature of Code, Example 5.8: Path Following. Space toggles the +//! debugging lines; a click makes a new path. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "path_following"; +pub const width = 640; +pub const height = 360; + +/// How far a vehicle may wander from the path before it steers back. +const radius = 20; + +const Path = [4]vec.Vec; + +fn newPath(rng: std.Random) Path { + return .{ + .{ -20, height / 2 }, + .{ vec.uniform(rng, 0, width / 2), vec.uniform(rng, 0, height) }, + .{ vec.uniform(rng, width / 2, width), vec.uniform(rng, 0, height) }, + .{ width + 20, height / 2 }, + }; +} + +/// Where a vehicle is headed and what it steers toward: `follow` in the +/// book, which also draws it. Here `update` steers by it and `draw` shows +/// it, both computing it from State. +const Aim = struct { future: vec.Vec, normal: vec.Vec, target: vec.Vec, distance: f32 }; + +const Vehicle = struct { + position: vec.Vec, + velocity: vec.Vec = .{ 2, 0 }, + maxspeed: f32, + maxforce: f32, + const r = 4; + + /// Reynolds' path following: predict 50 px ahead, find the nearest + /// normal point on the path, aim 10 px further along it. + fn aim(v: Vehicle, path: Path) Aim { + const future = v.position + vec.withLength(v.velocity, 50); + var best: Aim = .{ .future = future, .normal = future, .target = future, .distance = std.math.inf(f32) }; + for (path[0 .. path.len - 1], path[1..]) |a, b| { + const ab = vec.normalize(b - a); + var normal = a + vec.scale(ab, vec.dot(future - a, ab)); + // The book's shortcut: the path runs left to right. + if (normal[0] < a[0] or normal[0] > b[0]) normal = b; + const d = vec.distance(future, normal); + if (d < best.distance) best = .{ .future = future, .normal = normal, .target = normal + vec.scale(ab, 10), .distance = d }; + } + return best; + } + + fn step(v: *Vehicle, path: Path) void { + const a = v.aim(path); + var force: vec.Vec = .{ 0, 0 }; + if (a.distance > radius) { + const desired = a.target - v.position; + if (vec.length(desired) > 0) force = vec.clampLength(vec.withLength(desired, v.maxspeed) - v.velocity, v.maxforce); + } + v.velocity = vec.clampLength(v.velocity + force, v.maxspeed); + v.position += v.velocity; + // Past the end, back to the start. + if (v.position[0] > path[3][0] + r) v.position = .{ path[0][0] - r, path[0][1] + (v.position[1] - path[3][1]) }; + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(8), + debug: bool = true, + path: Path = undefined, + cars: [2]Vehicle = .{ + .{ .position = .{ 0, height / 2 }, .maxspeed = 2, .maxforce = 0.04 }, + .{ .position = .{ 0, height / 2 }, .maxspeed = 3, .maxforce = 0.1 }, + }, + clock: sk.Clock = .{}, +}; + +pub fn init(s: *State) void { + s.path = newPath(s.rng.random()); +} + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.pressed(sk.Key.space)) s.debug = !s.debug; + if (in.mousePressed(.left) != null) s.path = newPath(s.rng.random()); + for (0..s.clock.steps(in)) |_| for (&s.cars) |*car| car.step(s.path); +} + +/// The path, as wide as the radius on either side: translucent black over +/// white makes Processing's gray 200, and where the round joins meet the +/// segments nothing is drawn twice. +const road: sk.draw.Pen = .{ .stroke = sk.Color.black.alpha(55), .width = radius * 2, .join = .round }; +const centre: sk.draw.Pen = .{ .stroke = .black }; +const body: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; +const marker: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black }; +const triangle = [_]vec.Vec{ .{ Vehicle.r * 2, 0 }, .{ -Vehicle.r * 2, -Vehicle.r }, .{ -Vehicle.r * 2, Vehicle.r } }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + sk.draw.polyline(f, &s.path, road); + sk.draw.polyline(f, &s.path, centre); + if (s.debug) for (s.cars) |car| { + const a = car.aim(s.path); + sk.draw.line(f, car.position, a.future, centre); + sk.draw.circle(f, a.future, 2, marker); + sk.draw.circle(f, a.normal, 2, marker); + sk.draw.line(f, a.future, a.normal, centre); + // Red while steering back toward the path. + sk.draw.circle(f, a.target, 4, .{ .fill = if (a.distance > radius) .hex(0xff0000) else .gray(127) }); + }; + for (s.cars) |car| sk.draw.polygon(f, &triangle, body.transformed(.place(car.position, vec.angle(car.velocity)))); +} diff --git a/examples/noc/src/pendulum.zig b/examples/noc/src/pendulum.zig new file mode 100644 index 0000000..0ea177f --- /dev/null +++ b/examples/noc/src/pendulum.zig @@ -0,0 +1,54 @@ +//! Nature of Code, Example 3.11: Swinging Pendulum. Drag the bob. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "pendulum"; +pub const width = 640; +pub const height = 360; + +const pivot: vec.Vec = .{ width / 2, 30 }; +const r = 175; +const ball_r = 24; +const damping = 0.995; +const gravity = 0.4; + +pub const State = struct { + angle: f32 = std.math.pi / 4.0, + angle_velocity: f32 = 0, + dragging: bool = false, + clock: sk.Clock = .{}, + + fn bob(s: *const State) vec.Vec { + return pivot + vec.scale(.{ @sin(s.angle), @cos(s.angle) }, r); + } +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (in.events) |e| switch (e.kind) { + .mouse_down => if (vec.distance(.{ e.x, e.y }, s.bob()) < ball_r) { + s.dragging = true; + }, + .mouse_up => { + s.angle_velocity = 0; + s.dragging = false; + }, + else => {}, + }; + for (0..s.clock.steps(in)) |_| if (s.dragging) { + const diff = pivot - vec.Vec{ in.mouse_x, in.mouse_y }; + s.angle = std.math.atan2(-diff[1], diff[0]) - std.math.degreesToRadians(90); + } else { + s.angle_velocity += -gravity / @as(f32, r) * @sin(s.angle); + s.angle += s.angle_velocity; + s.angle_velocity *= damping; + }; +} + +const pen: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + sk.draw.line(f, pivot, s.bob(), pen); + sk.draw.circle(f, s.bob(), ball_r, pen); +} diff --git a/examples/noc/src/processing_noise.zig b/examples/noc/src/processing_noise.zig new file mode 100644 index 0000000..e5606e6 --- /dev/null +++ b/examples/noc/src/processing_noise.zig @@ -0,0 +1,86 @@ +//! Processing's own `noise()` (PApplet.noise), for ports that must match the +//! book's pictures: its 4096-entry table filled by java.util.Random seeded +//! with `seed`, as `noiseSeed(0)` would, and its half-degree cosine fade. +//! Four octaves, falloff 0.5, like Processing's defaults. Otherwise prefer +//! `sk.math.noise` (table-free, any seed, same on every host). +const std = @import("std"); + +const seed: u64 = 0; +const perlin_size = 4095; +const perlin: [perlin_size + 1]f32 = blk: { + @setEvalBranchQuota(100_000); + const mask: u64 = (1 << 48) - 1; + var s: u64 = (seed ^ 0x5DEECE66D) & mask; + var table: [perlin_size + 1]f32 = undefined; + for (&table) |*v| { + s = (s *% 0x5DEECE66D +% 0xB) & mask; + v.* = @as(f32, @floatFromInt(s >> 24)) / (1 << 24); + } + break :blk table; +}; +/// Processing's cosine fade, through its half-degree cos table. +fn fade(i: f32) f32 { + const k: f32 = @floor(i * 360); + return 0.5 * (1 - @cos(@mod(k, 720) * std.math.pi / 360)); +} + +pub fn noise(x_in: f32, y_in: f32, z_in: f32) f32 { + const ywrapb = 4; + const ywrap = 1 << ywrapb; + const zwrapb = 8; + const zwrap = 1 << zwrapb; + const x = @abs(x_in); + const y = @abs(y_in); + const z = @abs(z_in); + var xi: i32 = @intFromFloat(x); + var yi: i32 = @intFromFloat(y); + var zi: i32 = @intFromFloat(z); + var xf = x - @as(f32, @floatFromInt(xi)); + var yf = y - @as(f32, @floatFromInt(yi)); + var zf = z - @as(f32, @floatFromInt(zi)); + var r: f32 = 0; + var ampl: f32 = 0.5; + const p = struct { + fn at(i: i32) f32 { + return perlin[@intCast(i & perlin_size)]; + } + }.at; + for (0..4) |_| { + var of = xi + (yi << ywrapb) + (zi << zwrapb); + const rxf = fade(xf); + const ryf = fade(yf); + var n1 = p(of); + n1 += rxf * (p(of + 1) - n1); + var n2 = p(of + ywrap); + n2 += rxf * (p(of + ywrap + 1) - n2); + n1 += ryf * (n2 - n1); + of += zwrap; + n2 = p(of); + n2 += rxf * (p(of + 1) - n2); + var n3 = p(of + ywrap); + n3 += rxf * (p(of + ywrap + 1) - n3); + n2 += ryf * (n3 - n2); + n1 += fade(zf) * (n2 - n1); + r += n1 * ampl; + ampl *= 0.5; + xi <<= 1; + xf *= 2; + yi <<= 1; + yf *= 2; + zi <<= 1; + zf *= 2; + if (xf >= 1) { + xi += 1; + xf -= 1; + } + if (yf >= 1) { + yi += 1; + yf -= 1; + } + if (zf >= 1) { + zi += 1; + zf -= 1; + } + } + return r; +} diff --git a/examples/noc/src/quadtree.zig b/examples/noc/src/quadtree.zig new file mode 100644 index 0000000..98c791d --- /dev/null +++ b/examples/noc/src/quadtree.zig @@ -0,0 +1,135 @@ +//! Nature of Code, Example 5.13: QuadTree. The points under the pointer's +//! square are found through the tree; drag to add points. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "quadtree"; +pub const width = 640; +pub const height = 360; + +/// Points a node holds before it splits in four. +const capacity = 8; + +/// A rect by its centre and half-sizes, as the book has it. +const Box = struct { + x: f32, + y: f32, + w: f32, + h: f32, + + fn contains(b: Box, p: vec.Vec) bool { + return p[0] >= b.x - b.w and p[0] < b.x + b.w and p[1] >= b.y - b.h and p[1] < b.y + b.h; + } + fn intersects(b: Box, r: Box) bool { + return !(r.x - r.w > b.x + b.w or r.x + r.w < b.x - b.w or r.y - r.h > b.y + b.h or r.y + r.h < b.y - b.h); + } + fn rect(b: Box) vec.Rect { + return .{ .x = b.x - b.w, .y = b.y - b.h, .w = b.w * 2, .h = b.h * 2 }; + } +}; + +/// The tree is derived from the points: `draw` builds it every frame in +/// scratch memory (a few thousand inserts), so State holds only the +/// points, and a seek or a replay needs nothing else. Nodes refer to +/// their children by index, not by pointer. +const QuadTree = struct { + nodes: std.ArrayList(Node) = .empty, + + const Node = struct { + boundary: Box, + points: sk.List(vec.Vec, capacity) = .{}, + /// The first of four children (ne, nw, se, sw), or 0 for none. + children: u32 = 0, + }; + + fn init(gpa: std.mem.Allocator, boundary: Box) !QuadTree { + var t: QuadTree = .{}; + try t.nodes.append(gpa, .{ .boundary = boundary }); + return t; + } + + fn insert(t: *QuadTree, gpa: std.mem.Allocator, index: u32, p: vec.Vec) !bool { + const node = &t.nodes.items[index]; + if (!node.boundary.contains(p)) return false; + if (node.points.appendBounded(p)) |_| return true else |_| {} + if (node.children == 0) try t.subdivide(gpa, index); + const first = t.nodes.items[index].children; + for (first..first + 4) |child| if (try t.insert(gpa, @intCast(child), p)) return true; + return false; + } + + fn subdivide(t: *QuadTree, gpa: std.mem.Allocator, index: u32) !void { + const b = t.nodes.items[index].boundary; + const w = b.w / 2; + const h = b.h / 2; + t.nodes.items[index].children = @intCast(t.nodes.items.len); + for ([_][2]f32{ .{ 1, -1 }, .{ -1, -1 }, .{ 1, 1 }, .{ -1, 1 } }) |d| { + try t.nodes.append(gpa, .{ .boundary = .{ .x = b.x + d[0] * w, .y = b.y + d[1] * h, .w = w, .h = h } }); + } + } + + fn query(t: *const QuadTree, gpa: std.mem.Allocator, index: u32, range: Box, found: *std.ArrayList(vec.Vec)) !void { + const node = t.nodes.items[index]; + if (!node.boundary.intersects(range)) return; + for (node.points.constSlice()) |p| if (range.contains(p)) try found.append(gpa, p); + if (node.children != 0) for (node.children..node.children + 4) |child| try t.query(gpa, @intCast(child), range, found); + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(13), + /// Processing's list grows without bound; State needs a number. + points: sk.List(vec.Vec, 4096) = .{}, +}; + +/// setup(): 2000 points, normally distributed around the centre. (The +/// book centres y on width / 2 too, which puts the cloud at the bottom +/// edge; here it is height / 2.) +pub fn init(s: *State) void { + const rng = s.rng.random(); + for (0..2000) |_| { + const p: vec.Vec = .{ rng.floatNorm(f32) * width / 8 + width / 2, rng.floatNorm(f32) * width / 8 + height / 2 }; + s.points.appendBounded(p) catch break; + } +} + +/// Dragging sprinkles a point a step near the pointer (the book's video +/// version). +pub fn update(s: *State, in: *const sk.Input) void { + if (!in.mouseHeld(.left)) return; + const rng = s.rng.random(); + const p: vec.Vec = .{ in.mouse_x + vec.uniform(rng, -5, 5), in.mouse_y + vec.uniform(rng, -5, 5) }; + s.points.appendBounded(p) catch {}; +} + +const range_pen: sk.draw.Pen = .{ .fill = sk.Color.hex(0xff3232).alpha(50), .stroke = .hex(0xff3232), .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + build(s, f) catch f.host.log("out of scratch memory: tree dropped"); +} + +fn build(s: *const State, f: *sk.Frame) !void { + const gpa = f.scratch; + var tree: QuadTree = try .init(gpa, .{ .x = width / 2, .y = height / 2, .w = width, .h = height }); + for (s.points.constSlice()) |p| _ = try tree.insert(gpa, 0, p); + + // Every node's outline and every point, black, in one shape: show(). + var black: sk.draw.Tessellation = .empty; + for (tree.nodes.items) |node| { + try black.strokeRect(gpa, node.boundary.rect(), 1, .identity); + for (node.points.constSlice()) |p| try black.fillRect(gpa, .{ .x = p[0] - 0.5, .y = p[1] - 0.5, .w = 1, .h = 1 }, .identity); + } + f.shape(&black, .black); + + const mouse: vec.Vec = .{ f.in.mouse_x, f.in.mouse_y }; + if (mouse[0] >= width or mouse[1] >= height) return; + const range: Box = .{ .x = mouse[0], .y = mouse[1], .w = 50, .h = 50 }; + sk.draw.rect(f, range.rect(), range_pen); + var found: std.ArrayList(vec.Vec) = .empty; + try tree.query(gpa, 0, range, &found); + var dots: sk.draw.Tessellation = .empty; + for (found.items) |p| try dots.fillCircle(gpa, p, 1.5, .identity); + f.shape(&dots, .gray(50)); +} diff --git a/examples/noc/src/random_walk.zig b/examples/noc/src/random_walk.zig new file mode 100644 index 0000000..fff856e --- /dev/null +++ b/examples/noc/src/random_walk.zig @@ -0,0 +1,60 @@ +//! Example 0.1: Random Walk. A walker takes a random step left, right, up +//! or down each frame and leaves a black dot; the canvas is never cleared. +//! The dots go into an offscreen image that keeps them (`f.target`). +const std = @import("std"); +const sk = @import("sketch"); + +pub const name = "random_walk"; +pub const width = 640; +pub const height = 360; + +const Walker = struct { + x: i32 = width / 2, + y: i32 = height / 2, + rng: std.Random.Xoshiro256 = .init(1), + + fn step(w: *Walker) void { + switch (w.rng.random().uintLessThan(u8, 4)) { + 0 => w.x += 1, + 1 => w.x -= 1, + 2 => w.y += 1, + else => w.y -= 1, + } + } +}; + +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, +}; + +/// 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, so it shows +/// what playing would have. +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(); + f.fill(.{ .x = ss.shadow.x, .y = ss.shadow.y, .w = 1, .h = 1 }, .black); + } + // 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 }, .{}); +} diff --git a/examples/noc/src/recursive_tree.zig b/examples/noc/src/recursive_tree.zig new file mode 100644 index 0000000..a71f7f9 --- /dev/null +++ b/examples/noc/src/recursive_tree.zig @@ -0,0 +1,35 @@ +//! Example 8.6: Recursive Tree. Each branch draws itself, then two +//! branches two thirds as long, turned by the angle the pointer's x sets +//! (0 at the left edge, a right angle at the right). Push/pop is +//! `pen.transformed`: each call gets its own pen. +const std = @import("std"); +const sk = @import("sketch"); + +pub const name = "recursive_tree"; +pub const width = 640; +pub const height = 360; + +pub const State = struct { + angle: f32 = 0, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + s.angle = std.math.lerp(0, std.math.pi / 2.0, in.mouse_x / width); +} + +const trunk: sk.draw.Pen = .{ .stroke = .black, .width = 2, .xf = .translate(width / 2, height) }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(.white); + branch(f, trunk, 100, s.angle); +} + +fn branch(f: *sk.Frame, pen: sk.draw.Pen, len: f32, angle: f32) void { + sk.draw.line(f, .{ 0, 0 }, .{ 0, -len }, pen); + const tip = pen.transformed(.translate(0, -len)); + const next = len * 0.67; + if (next > 2) { + branch(f, tip.transformed(.rotate(angle)), next, angle); + branch(f, tip.transformed(.rotate(-angle)), next, angle); + } +} diff --git a/examples/noc/src/smoke.zig b/examples/noc/src/smoke.zig new file mode 100644 index 0000000..c0acb04 --- /dev/null +++ b/examples/noc/src/smoke.zig @@ -0,0 +1,70 @@ +//! Example 4.8: Image Texture System (smoke). Particles rise from an +//! emitter, each a soft image centred on it (Processing's +//! `imageMode(CENTER)`, here `f.imageAt`) and fading with its lifespan +//! (`tint(255, lifespan)`). The pointer's x sets a wind, drawn as an arrow. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "smoke"; +pub const width = 640; +pub const height = 360; + +/// A particle lives 51 steps (100 down by 2 until below 0), and one is +/// added a step. +const max_particles = 56; +const origin: vec.Vec = .{ width / 2, height - 75 }; + +const Particle = struct { + position: vec.Vec, + velocity: vec.Vec, + lifespan: f32 = 100, + + fn init(rng: std.Random) Particle { + return .{ .position = origin, .velocity = .{ rng.floatNorm(f32) * 0.3, rng.floatNorm(f32) * 0.3 - 1 } }; + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(48), + particles: sk.List(Particle, max_particles) = .{}, + /// From the pointer's x: -0.2 at the left edge, 0.2 at the right. + wind: f32 = 0, + clock: sk.Clock = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| { + s.wind = std.math.lerp(-0.2, 0.2, in.mouse_x / width); + var i = s.particles.count(); + while (i > 0) { + i -= 1; + const p = &s.particles.slice()[i]; + p.velocity += vec.Vec{ s.wind, 0 }; + p.position += p.velocity; + p.lifespan -= 2; + if (p.lifespan < 0) _ = s.particles.orderedRemove(i); + } + s.particles.appendBounded(.init(s.rng.random())) catch {}; + } +} + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(.black); + const texture = f.host.loadImage("assets/texture.png"); + for (s.particles.constSlice()) |p| { + // Processing shows a particle as it updates it: not yet the new one. + if (p.lifespan == 100) continue; + f.imageAt(texture, .translate(p.position[0], p.position[1]), .{ .tint = sk.Color.white.alphaFloat(p.lifespan / 255) }); + } + windArrow(f, s.wind); +} + +/// The wind as an arrow from the top middle, 500 times its length. +pub fn windArrow(f: *sk.Frame, wind: f32) void { + const pen: sk.draw.Pen = .{ .stroke = .white, .xf = .place(.{ width / 2, 50 }, if (wind < 0) std.math.pi else 0) }; + const len = @abs(wind) * 500; + sk.draw.line(f, .{ 0, 0 }, .{ len, 0 }, pen); + sk.draw.line(f, .{ len, 0 }, .{ len - 4, 2 }, pen); + sk.draw.line(f, .{ len, 0 }, .{ len - 4, -2 }, pen); +} diff --git a/examples/noc/src/system_of_systems.zig b/examples/noc/src/system_of_systems.zig new file mode 100644 index 0000000..d02938c --- /dev/null +++ b/examples/noc/src/system_of_systems.zig @@ -0,0 +1,79 @@ +//! Nature of Code, Example 4.4: A System of Systems. Click to add emitters. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "system_of_systems"; +pub const width = 640; +pub const height = 360; + +/// A particle lives 128 steps (255 down by 2 until below 0), and an emitter +/// adds one a step: 128 at once. +const max_particles = 136; +const max_emitters = 32; + +const Particle = struct { + position: vec.Vec, + velocity: vec.Vec, + lifespan: f32 = 255, + + fn init(rng: std.Random, origin: vec.Vec) Particle { + const lerp = std.math.lerp; + return .{ .position = origin, .velocity = .{ lerp(-1, 1, rng.float(f32)), lerp(-2, 0, rng.float(f32)) } }; + } + fn update(p: *Particle) void { + p.velocity += vec.Vec{ 0, 0.05 }; // gravity + p.position += p.velocity; + p.lifespan -= 2; + } + fn isDead(p: Particle) bool { + return p.lifespan < 0; + } +}; + +const Emitter = struct { + origin: vec.Vec, + particles: sk.List(Particle, max_particles) = .{}, + + fn run(e: *Emitter) void { + var i = e.particles.count(); + while (i > 0) { + i -= 1; + const p = &e.particles.slice()[i]; + p.update(); + if (p.isDead()) _ = e.particles.orderedRemove(i); + } + } +}; + +pub const State = struct { + rng: std.Random.Xoshiro256 = .init(4), + emitters: sk.List(Emitter, max_emitters) = .{}, + clock: sk.Clock = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (in.events) |e| if (e.kind == .mouse_down) { + s.emitters.appendBounded(.{ .origin = .{ e.x, e.y } }) catch {}; + }; + for (0..s.clock.steps(in)) |_| for (s.emitters.slice()) |*emitter| { + emitter.run(); + emitter.particles.appendBounded(.init(s.rng.random(), emitter.origin)) catch {}; + }; +} + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + for (s.emitters.constSlice()) |*emitter| { + // Processing shows each particle as it updates them, newest first. + // The one just added is not shown until next frame. + const shown = emitter.particles.constSlice(); + var i = shown.len -| 1; + while (i > 0) { + i -= 1; + const a = shown[i].lifespan / 255; + const pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alphaFloat(a), .stroke = sk.Color.black.alphaFloat(a), .width = 2 }; + sk.draw.circle(f, shown[i].position, 4, pen); + } + } +} diff --git a/examples/noc/src/the_wave.zig b/examples/noc/src/the_wave.zig new file mode 100644 index 0000000..86ce10d --- /dev/null +++ b/examples/noc/src/the_wave.zig @@ -0,0 +1,31 @@ +//! Nature of Code, Example 3.9: The Wave. +const std = @import("std"); +const sk = @import("sketch"); + +pub const name = "the_wave"; +pub const width = 640; +pub const height = 360; + +pub const State = struct { + start_angle: f32 = 0, + angle_velocity: f32 = 0.2, + clock: sk.Clock = .{}, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| s.start_angle += 0.02; +} + +const pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + // Processing advances startAngle after reading it; State already has. + var angle = s.start_angle - 0.02; + var x: f32 = 0; + while (x <= width) : (x += 24) { + const y = std.math.lerp(0, height, (@sin(angle) + 1) / 2); + sk.draw.circle(f, .{ x, y }, 24, pen); + angle += s.angle_velocity; + } +} diff --git a/examples/noc/src/wolfram_ca.zig b/examples/noc/src/wolfram_ca.zig new file mode 100644 index 0000000..fd8fc63 --- /dev/null +++ b/examples/noc/src/wolfram_ca.zig @@ -0,0 +1,62 @@ +//! Nature of Code, Example 7.1: Wolfram Elementary Cellular Automaton +//! (rule 90). Processing paints one row a frame over the last frame's +//! pixels; here every frame is drawn from State, so State keeps every row. +const std = @import("std"); +const sk = @import("sketch"); + +pub const name = "wolfram_ca"; +pub const width = 640; +pub const height = 320; + +const w = 10; +const cols = width / w; +/// Processing stops once `generation * w > height`: rows 0 to 32. +const max_rows = height / w + 1; +const ruleset = [8]u1{ 0, 1, 0, 1, 1, 0, 1, 0 }; + +pub const State = struct { + rows: [max_rows][cols]u1 = initial(), + /// Rows drawn so far: Processing's `generation`. + generation: u32 = 0, + clock: sk.Clock = .{}, + + fn initial() [max_rows][cols]u1 { + var rows: [max_rows][cols]u1 = @splat(@splat(0)); + rows[0][cols / 2] = 1; + return rows; + } +}; + +fn rules(left: u1, me: u1, right: u1) u1 { + const index = @as(u3, left) << 2 | @as(u3, me) << 1 | right; + return ruleset[7 - @as(usize, index)]; +} + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.steps(in)) |_| if (s.generation < max_rows) { + // Processing draws `cells`, then computes the next generation. + if (s.generation > 0) { + const cells = s.rows[s.generation - 1]; + var next = cells; + for (1..cols - 1) |i| next[i] = rules(cells[i - 1], cells[i], cells[i + 1]); + s.rows[s.generation] = next; + } + s.generation += 1; + }; +} + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(0xffffff); + for (s.rows[0..s.generation], 0..) |cells, generation| { + for (1..cols - 1) |i| if (cells[i] == 1) { + // square(i * w, generation * w, w) with a 1px black stroke: the + // stroke adds half a pixel all round. + f.fill(sk.Rect{ + .x = @as(f32, @floatFromInt(i * w)) - 0.5, + .y = @as(f32, @floatFromInt(generation * w)) - 0.5, + .w = w + 1, + .h = w + 1, + }, 0x000000); + }; + } +} |
