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

Tuesday 8 December 2009

A square edge fractal with L-System and ruby-processing

LSystem using my custom grammar library (see Cesàro fractal in earlier post)


########################################################
# Chequer implemented using a grammar library
# Lindenmayer System in ruby-processing by Martin Prout
########################################################

require 'chequer'

class Chequer_Test < Processing::App
  load_libraries 'grammar'

  attr_reader :chequer

  def setup
    size 600, 600
    @chequer = Chequer.new  
    chequer.create_grammar 4  
    no_loop
  end

  def draw
    background 0
    chequer.render
  end
end

############################
# chequer.rb
###########################

class Chequer
  include Processing::Proxy

  attr_accessor :axiom, :grammar, :production, :draw_length, :theta, :xpos, :ypos
  DELTA = Math::PI/2

  def initialize
    @axiom = "F-F-F-F"
    @grammar = Grammar.new axiom
    @grammar.add_rule "F", "FF-F-F-F-FF"
    @draw_length = 500
    stroke 0, 255, 0
    stroke_weight 2  
    @xpos = width * 0.9
    @ypos = height/10
    @theta = 0
  end

  def render
    stack = Array.new               # directly using locally defined array as turtle stack
    production.each_char do |element|
      case element
      when 'F'                     # NB NOT using affine transforms
        x_temp = xpos
        y_temp = ypos
        @xpos -= draw_length * Math.cos(theta) # looks neater here
        @ypos -= draw_length * Math.sin(theta)
        line(x_temp, y_temp, xpos, ypos)
      when '+'
        @theta += DELTA
      when '-'
        @theta -= 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 /=  3**gen
    @production = @grammar.generate gen
  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