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

Sunday, 6 December 2009

Cesàro (or Torn Square) Fractal using Lindenmayer System

Revised version as of 8th January 2010, nows uses once more re-factored lsystem library.

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


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