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
|
//! 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);
}
}
|