A Sierpinski (triangle) variant after Mark Meyers nodebox l-systems...
for the grammar library see a previous post Cesàro fractal
##
# A Sierpinski Variant implemented using a
# Lindenmayer System in ruby-processing by Martin Prout
###
require 'sierpinski'
class Sierpinski_Test < Processing::App
load_libraries 'grammar'
attr_reader :sierpinski
def setup
size 500, 600
@sierpinski = Sierpinski.new
sierpinski.create_grammar 8
no_loop
end
def draw
background 0
sierpinski.render
end
end
############################
# sierpinski.rb
###########################
class Sierpinski
include Processing::Proxy
attr_accessor :axiom, :grammar, :start_length, :theta, :production, :draw_length, :xpos, :ypos
DELTA = (Math::PI/180) * 60.0 # convert degrees to radians
GAMMA = (Math::PI/180) * 60.25
def initialize
@axiom = "A"
@grammar = Grammar.new axiom
grammar.add_rule "A", "B+A+B"
grammar.add_rule "B", "A-B-A"
@start_length = 450
@theta = 0.0
@xpos = width * 0.95
@ypos = height * 0.8
stroke 255
@production = axiom
@draw_length = start_length
end
def render # NB not using affine transforms here
repeats = 1
production.each_char do |element|
case element
when 'B', 'A'
line(xpos, ypos, (@xpos -= draw_length * Math.cos(theta)), (@ypos += draw_length * Math.sin(theta)))
when '+'
@theta += DELTA * repeats
repeats = 1
when '-'
@theta -= GAMMA * repeats
repeats = 1
when '2'
repeats = 2
else
puts "Character '#{element}' is not in grammar"
end
end
end
##############################
# create grammar from axiom and
# rules (adjust scale)
##############################
def create_grammar(gen)
@draw_length *= 0.5**gen
@production = grammar.generate gen
end
end
No comments:
Post a Comment