1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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);
};
}
}
|