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

Sunday 29 November 2009

A basic example of a plant Lindenmayer systems in ruby processing


########################################################
# A basic plant implemented using a
# Lindenmayer System in ruby-processing by Martin Prout
########################################################

require 'plant'

class Plant_Test < Processing::App
  attr_reader :plant
  def setup
    size 600, 600
    @plant = Plant.new   
    plant.simulate 4   
    no_loop
  end
  def draw
    background 0
    translate 300, 550
    plant.render
    save_frame "plant_4.png"
  end
end

############################
# plant.rb
###########################

require 'jcode'  ## required until jruby supports ruby 1.9

class Plant
  include Processing::Proxy
  DELTA = (Math::PI/180) * 60
 
  attr_accessor :axiom, :rule, :start_length, :theta, :production, :draw_length, :xpos, :ypos

  def initialize
    @axiom = "F"
    @rule = "F[-F]F[+F][F]"
    @start_length = 250
    stroke 255
    stroke_weight 4
    reset
  end

  def reset                         # initialize or reset variables
    @production = axiom
    @draw_length = start_length
  end

  def iterate prod_, rule_
    @draw_length *=  0.5
    new_production = prod_       
    new_production.gsub!('F', rule_)
  end

  def render
    production.each_char do |element|
      case element
      when 'F'            # NB here I am using affine transforms here, and push_matrix to save context
        line(0, 0, 0, -draw_length)  
        translate(0, -draw_length)  
      when '+'
        rotate(+DELTA)   
      when '-'
        rotate(-DELTA)    
      when '['
        push_matrix
      when ']'
        pop_matrix       # pop_matrix to return to original context
      else puts "Grammar not recognized"
      end
    end
  end
 
  def simulate gen
    gen.times do
      @production = iterate(production, rule)
    end
  end
end



two repetitions




three repetitions


 
four repetitions

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