Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Monday 30 November 2009

Koch curve using l-systems

Revised as of 16 January 2010 to uses a custom grammar library (see Cesàro fractal in a later post) and various modifications

########################################################
# koch_test.rb uses grammar library
#
# A Koch curve implemented using a
# Lindenmayer System in ruby-processing by Martin Prout
########################################################
require 'koch'

class KochCurve < Processing::App
  load_library :grammar
  attr_reader :koch
  
  def setup
    size 600, 600
    @koch = Koch.new
    koch.create_grammar 4
    no_loop
  end
  
  def draw
    background 0
    koch.render
  end
end

############################
# koch.rb
#
# Koch Curve
###########################
class Koch
  include Processing::Proxy
  
  attr_accessor :axiom, :grammar, :start_length, :theta, :production, :draw_length, :xpos, :ypos
  XPOS = 0     # placeholders for turtle array
  YPOS = 1
  ANGLE = 2 
  DELTA = (Math::PI/180) * 90.0    # convert degrees to radians
  
  def initialize
    @axiom = "F-F-F-F"
    @grammar = Grammar.new axiom
    grammar.add_rule('F', "FF-F-F-F-F-F+F")  
    @start_length = 10
    @theta = 0.0
    @xpos = width * 0.6
    @ypos = height * 0.8
    stroke 255
    @production = axiom
    @draw_length = start_length
  end

   def render
    turtle = [xpos, ypos, 0.0]    # simple array act as turtle
    production.scan(/./).each do |element|
      case element
      when 'F'                     # NB NOT using affine transforms
        turtle = draw_line(turtle, draw_length)
      when '+'
        turtle[ANGLE] += DELTA  
      when '-'
        turtle[ANGLE] -= DELTA      
      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.75**gen
    @production = grammar.generate gen
  end
  
  private
  ######################################################
  # draws line using current turtle and length parameters
  # returns a turtle corresponding to the new position
  ######################################################

  def draw_line(turtle, length)
    new_xpos = turtle[XPOS] + length * Math.cos(turtle[ANGLE])
    new_ypos = turtle[YPOS] + length * Math.sin(turtle[ANGLE])
    line(turtle[XPOS], turtle[YPOS], new_xpos, new_ypos)
    turtle = [new_xpos, new_ypos, turtle[ANGLE]]
  end
end  




 

No comments:

Post a Comment

Followers

Blog Archive

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2