topical media & game development

talk show tell print

graphic-processing-site-examples-Topics-Fractals-and-L-Systems-Pentigree-LSystem.pde / pde



  class LSystem {
  
    int steps = 0;
  
    String axiom;
    String rule;
    String production;
  
    float startLength;
    float drawLength;
    float theta;
  
    int generations;
  
    LSystem() {
  
      axiom = "F";
      rule = "F+F-F";
      startLength = 90.0;
      theta = radians(120.0);
      reset();
    }
  
    void reset() {
      production = axiom;
      drawLength = startLength;
      generations = 0;
    }
  
    int getAge() {
      return generations;
    }
    
    void render() {
      translate(width/2, height/2);
      steps += 5;          
      if (steps > production.length()) {
        steps = production.length();
      }
      for (int i = 0; i < steps; i++) {
        char step = production.charAt(i);
        if (step == 'F') {
          rect(0, 0, -drawLength, -drawLength);
          noFill();
          translate(0, -drawLength);
        } 
        else if (step == '+') {
          rotate(theta);
        } 
        else if (step == '-') {
          rotate(-theta);
        } 
        else if (step == '[') {
          pushMatrix();
        } 
        else if (step == ']') {
          popMatrix();            
        }
      }
    }
    
    void simulate(int gen) {
      while (getAge() < gen) {
        production = iterate(production, rule);
      }
    }
  
    String iterate(String prod_, String rule_) {
      drawLength = drawLength * 0.6;
      generations++;
      String newProduction = prod_;          
      newProduction = newProduction.replaceAll("F", rule_);
      return newProduction;
    }
  }
  
  


(C) Æliens 20/2/2008

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.