/ examples / turtle / tree.scad
tree.scad
 1  use <polyline_join.scad>
 2  use <turtle/t3d.scad>
 3  use <util/rand.scad>
 4  
 5  trunk_leng = 50;
 6  branch_scale = 0.7;
 7  branch_angle = 30;
 8  width = 2;
 9  $fn = 4;
10  
11  module line(t1, t2, start_width, end_width) {
12      polyline_join([t3d(t1, "point"), t3d(t2, "point")]) {
13          sphere(start_width / 2);
14          sphere(end_width / 2);
15      }
16  }
17  
18  module shoot(t, trunk_leng, branch_scale, branch_angle, width) {
19      t2 = t3d(t, "forward", leng = trunk_leng);
20      line(t, t2, width, width);
21  
22      branch_leng = trunk_leng * branch_scale;
23      
24      color("green") {
25          t3 = t3d(t2, "turn", angle = branch_angle);
26          line(
27              t2, 
28              t3d(t3, "forward", leng = branch_leng), 
29              width,
30              width * rand(1, 3)
31          );
32  
33          t4 = t3d(t2, "turn", angle = -branch_angle);  
34          line(
35              t2, 
36              t3d(t4, "forward", leng = branch_leng), 
37              width,
38              width * rand(1, 3)
39          );
40      }
41  }
42  
43  module tree(t, trunk_leng, branch_scale, branch_angle, width) {
44      if(trunk_leng > width * 2) {
45          t2 = t3d(t, "forward", leng = trunk_leng * rand(0.6, 1));
46          line(t, t2, trunk_leng / 3, trunk_leng / 3 * branch_scale);
47  
48          rolled = t3d(t2, "roll", angle = 120 * rand(0.6, 1));
49          branch_leng = trunk_leng * branch_scale;
50          
51          t3 = t3d(rolled, "turn", angle = branch_angle * rand(0.6, 1));
52          tree(t3, branch_leng, branch_scale, branch_angle, width);
53  
54          t4 = t3d(rolled, "turn", angle = -branch_angle * rand(0.6, 1));        
55          tree(t4, branch_leng, branch_scale, branch_angle, width);
56      }
57      else {
58          shoot(t, trunk_leng, branch_scale, branch_angle, width);
59      }
60  }
61  
62  tree(t3d(), trunk_leng, branch_scale, branch_angle, width);