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

Thursday, 28 January 2010

Two dimensional Hilbert fractal with LSystems and ruby-processing


#############################################################
# A Hilbert fractal implemented (uses my grammar library)
# Lindenmayer System in ruby-processing by Martin Prout
#############################################################

require 'hilbert'

class Hilbert_Test < Processing::App
  load_library :grammar
  attr_reader :hilbert
  def setup
    size 600, 600
    @hilbert = Hilbert.new 
    hilbert.create_grammar 5 
    no_loop
  end
 
  def draw
    background 0
    hilbert.render
  end
end


############################
# hilbert.rb
###########################
class Hilbert
  include Processing::Proxy

  attr_accessor :grammar, :axiom, :draw_length, :turtle
  DELTA = Math::PI/2
  XPOS = 0  # placeholders for turtle
  YPOS = 1
  THETA = 2
  def initialize 
    @axiom = "FL"
    @grammar = Grammar.new axiom
    grammar.add_rule "L", "+RF-LFL-FR+"
    grammar.add_rule "R", "-LF+RFR+FL-"
    @draw_length = 200
    stroke 0, 255, 0
    stroke_weight 2 
    @turtle = Array.new(3)           # using an array as turtle
    turtle[XPOS] = width/9
    turtle[YPOS] = height/9
    turtle[THETA] = 0
  end

  def render
    axiom.scan(/./) do |element|
      case element
      when 'F'                      # NB NOT using affine transforms
        draw_line(turtle)
      when '+'
        @turtle[THETA] += DELTA    
      when '-'
        @turtle[THETA] -= DELTA    
      when 'L'
      when 'R'
      else puts "Grammar not recognized"
      end
    end
  end
 
  def draw_line(turtle)
    x_temp = turtle[XPOS]
    y_temp = turtle[YPOS]
    @turtle[XPOS] += draw_length * Math.cos(turtle[THETA])
    @turtle[YPOS] += draw_length * Math.sin(turtle[THETA])
    line(x_temp, y_temp, turtle[XPOS], turtle[YPOS])
  end

  ##############################
  # create grammar from axiom and
  # rules (adjust scale)
  ##############################
 
  def create_grammar(gen)
    @draw_length *=  0.6**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