Recently I've been looking at Povray, pyprocessing, and cfdg (version 3.0) as tools for creating digital images. I have branched two separate blogs where I mainly explore jruby + processing and processing.py

Tuesday, 5 January 2010

Sierpinski 'Arrowhead' Variant in processing using L-Systems

Revised version as of 8 January 2010, note Grammar is now an interface implemented by SimpleGrammar (or StochasticGrammar for weighted rules).

   1 import lsystem.*;
   2 
   3 // sierpinski.pde
   4 
   5 
   6 float drawLength;
   7 float xpos;
   8 float ypos;
   9 float DELTA = PI/3; // 60 degrees
  10 ArrayList points;
  11 float theta = 0;
  12 Grammar grammar;
  13 TurtleStack ts;
  14 String production;
  15 
  16 void setup() {
  17   size(800,700);
  18   createLSystem();
  19   points = new ArrayList();
  20   stroke(255, 0, 0);
  21   noFill();
  22   smooth();
  23   translateRules();
  24   noLoop();
  25 }
  26 
  27 void createLSystem(){
  28   int generations = 6;                 // set no of recursions
  29   String axiom = "A";  
  30   grammar = new SimpleGrammar(this, axiom);  // initialize custom library
  31   grammar.addRule('A', "B+A+B"); // add rule
  32   grammar.addRule('B', "A-B-A"); // add rule
  33   float startLength = 700;
  34   production = grammar.createGrammar(generations);
  35   drawLength = startLength * pow(0.5, generations); 
  36 }
  37 
  38 void translateRules() {
  39   TurtleStack ts = new TurtleStack();
  40   xpos = width/9;
  41   ypos = height * 0.9;
  42   CharacterIterator it = new StringCharacterIterator(production);
  43   for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
  44     Turtle turtle;
  45     switch(ch){
  46     case 'A':
  47       float[] temp = {
  48         xpos, ypos, (xpos += drawLength * cos(theta)), (ypos += drawLength *  sin(theta))
  49       };
  50       points.add(temp);
  51       break;
  52      case 'B':
  53       float[] tempb = {
  54         xpos, ypos, (xpos += drawLength * cos(theta)), (ypos += drawLength *  sin(theta))
  55       };
  56       points.add(tempb);
  57       break;  
  58     case '+':
  59       theta += (DELTA);
  60       break;
  61     case '-':
  62       theta -= (DELTA);
  63       break;
  64     default:
  65       System.err.println("character " + ch + " not in grammar");
  66     }
  67   }
  68 }
  69 
  70 void draw() {
  71   background(0);
  72   float[] tmp;
  73   for (int i =0; i < points.size(); i++)
  74   { 
  75     tmp = (float[])points.get(i);
  76     line(tmp[0], tmp[1], tmp[2], tmp[3]);
  77   }
  78 }


No comments:

Post a Comment

Followers

Blog Archive

About Me

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