Skip to content

Commit 9888c93

Browse files
committed
Stuff
1 parent d314551 commit 9888c93

File tree

1 file changed

+102
-0
lines changed
  • processing_app/topics/lsystems/library/koch

1 file changed

+102
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# Kochline class
2+
class KochLine
3+
include Propane::Proxy
4+
attr_reader :start, :finish
5+
6+
def initialize(a, b)
7+
@start = a.copy
8+
@finish = b.copy
9+
end
10+
11+
def display
12+
stroke(120)
13+
line(start.x, start.y, finish.x, finish.y)
14+
end
15+
16+
# This is easy, just 1/3 of the way
17+
def kochleft
18+
v = finish - start
19+
v /= 3
20+
v + start
21+
end
22+
23+
# More complicated, using a little trig to figure out where this vector is!
24+
def kochmiddle
25+
v = finish - start
26+
v /= 3
27+
p = start.copy
28+
p += v
29+
rotate_line(v, -60)
30+
p + v
31+
end
32+
33+
# Easy, just 2/3 of the way
34+
def kochright
35+
v = start - finish
36+
v /= 3
37+
v + finish
38+
end
39+
40+
private
41+
42+
def rotate_line(v, theta)
43+
xtemp = v.x
44+
# Might need to check for rounding errors like with angleBetween function?
45+
v.x = v.x * DegLut.cos(theta) - v.y * DegLut.sin(theta)
46+
v.y = xtemp * DegLut.sin(theta) + v.y * DegLut.cos(theta)
47+
end
48+
end
49+
50+
# KochFractal class
51+
class KochFractal
52+
attr_reader :count, :start, :finish, :lines
53+
def initialize(width, height)
54+
@start = Vec2D.new(0, height - 20)
55+
@finish = Vec2D.new(width, height - 20)
56+
@lines = []
57+
restart
58+
end
59+
60+
def next_level
61+
# For every line that is in the arraylist
62+
# create 4 more lines in a new arraylist
63+
@lines = iterate(lines)
64+
@count += 1
65+
end
66+
67+
def restart
68+
@count = 0 # Reset count
69+
lines.clear # Empty the array list
70+
lines << KochLine.new(start, finish)
71+
end
72+
73+
def render
74+
lines.each(&:display)
75+
end
76+
77+
# This is where the **MAGIC** happens
78+
# Step 1: Create an empty arraylist
79+
# Step 2: For every line currently in the arraylist
80+
# - calculate 4 line segments based on Koch algorithm
81+
# - add all 4 line segments into the new arraylist
82+
# Step 3: Return the new arraylist and it becomes the list of line segments
83+
# for the structure. As we do this over and over again, each line gets broken
84+
# into 4 lines, which gets broken into 4 lines, and so on. . .
85+
def iterate(before)
86+
[].tap do |now| # Create empty list
87+
before.each do |l|
88+
# Calculate 5 koch vectors (done for us by the line object)
89+
a = l.start
90+
b = l.kochleft
91+
c = l.kochmiddle
92+
d = l.kochright
93+
e = l.finish
94+
# Make line segments between all the vectors and add them
95+
now << KochLine.new(a, b)
96+
now << KochLine.new(b, c)
97+
now << KochLine.new(c, d)
98+
now << KochLine.new(d, e)
99+
end
100+
end
101+
end
102+
end

0 commit comments

Comments
 (0)