|
| 1 | +require 'forwardable' |
| 2 | +require_relative './rotator' |
| 3 | + |
| 4 | +class Branch |
| 5 | + include Enumerable |
| 6 | + extend Forwardable |
| 7 | + def_delegators(:@children, :<<, :each, :length) |
| 8 | + # variance angle for growth direction per time step |
| 9 | + THETA = Math::PI / 6 |
| 10 | + # max segments per branch |
| 11 | + MAX_LEN = 100 |
| 12 | + # max recursion limit |
| 13 | + MAX_GEN = 3 |
| 14 | + # branch chance per time step |
| 15 | + BRANCH_CHANCE = 0.05 |
| 16 | + # branch angle variance |
| 17 | + BRANCH_THETA = Math::PI / 4 |
| 18 | + attr_reader :position, :dir, :path, :children, :xbound, :speed, :ybound, :app, :zbound |
| 19 | + |
| 20 | + def initialize(app, pos, dir, speed) |
| 21 | + @app = app |
| 22 | + @position = pos |
| 23 | + @dir = dir |
| 24 | + @speed = speed |
| 25 | + @path = [] |
| 26 | + @children = [] |
| 27 | + @xbound = Boundary.new(-600, 600) |
| 28 | + @ybound = Boundary.new(-150, 150) |
| 29 | + @zbound = Boundary.new(-150, 150) |
| 30 | + path << pos |
| 31 | + end |
| 32 | + |
| 33 | + def run |
| 34 | + grow |
| 35 | + display |
| 36 | + end |
| 37 | + |
| 38 | + private |
| 39 | + |
| 40 | + def grow |
| 41 | + check_bounds(position + (dir * speed)) |
| 42 | + @position += (dir * speed) |
| 43 | + Rotate.rotate_x!(dir, rand(-0.5..0.5) * THETA) |
| 44 | + Rotate.rotate_y!(dir, rand(-0.5..0.5) * THETA) |
| 45 | + Rotate.rotate_z!(dir, rand(-0.5..0.5) * THETA) |
| 46 | + path << position |
| 47 | + if (length < MAX_GEN) && (rand < BRANCH_CHANCE) |
| 48 | + branch_dir = dir.copy |
| 49 | + Rotate.rotate_x!(branch_dir, rand(-0.5..0.5) * BRANCH_THETA) |
| 50 | + Rotate.rotate_y!(branch_dir, rand(-0.5..0.5) * BRANCH_THETA) |
| 51 | + Rotate.rotate_z!(branch_dir, rand(-0.5..0.5) * BRANCH_THETA) |
| 52 | + self << Branch.new(app, position.copy, branch_dir, speed * 0.99) |
| 53 | + end |
| 54 | + each(&:grow) |
| 55 | + end |
| 56 | + |
| 57 | + def display |
| 58 | + app.begin_shape |
| 59 | + app.stroke 255 |
| 60 | + app.stroke_weight 0.5 |
| 61 | + app.no_fill |
| 62 | + path.each { |vec| vec.to_vertex(app.renderer) } |
| 63 | + app.end_shape |
| 64 | + each(&:display) |
| 65 | + end |
| 66 | + |
| 67 | + def check_bounds(pos) |
| 68 | + dir.x *= -1 if xbound.exclude? pos.x |
| 69 | + dir.y *= -1 if ybound.exclude? pos.y |
| 70 | + dir.z *= -1 if zbound.exclude? pos.z |
| 71 | + end |
| 72 | +end |
| 73 | + |
| 74 | +# we are looking for excluded values |
| 75 | +Boundary = Struct.new(:lower, :upper) do |
| 76 | + def exclude?(val) |
| 77 | + true unless (lower...upper).cover? val |
| 78 | + end |
| 79 | +end |
0 commit comments