読者です 読者をやめる 読者になる 読者になる

30 min. Processing

毎日30分、Processingで何かを作る

L-System(植物3)

フラクタル
f:id:aa_debdeb:20160214102836j:plain
/**
* L-system (Plant3)
*
* @author aa_debdeb
* @date 2016/02/20
*/

LSystem lsystem;
int step;

void setup(){
  size(500, 500);
  
  float d = 3.5;
  float delta = 20;
  String string = "X";
  HashMap<Character, String> rules = new HashMap<Character, String>();
  rules.put('X', "F[+X]F[-X]+X");
  rules.put('F', "FF");
  float iniDir = 270;
  PVector iniPos = new PVector(0, 250);
  
  lsystem = new LSystem(d, delta, string, rules, iniDir, iniPos);
  step = 0;
  
  background(0);
}

void draw(){

}

void mousePressed(){
  println("step: " + step);
  lsystem.draw();
  lsystem.step();
  step++;
}

void keyPressed(){
  saveFrame("images/image.jpg");
}

class LSystem{

  float d;
  float delta;
  String string;
  HashMap<Character, String> rules;
  float iniDir;
  PVector iniPos;
  
  LSystem(float d, float delta, String string, 
          HashMap<Character, String> rules,
          float iniDir, PVector iniPos){    
    this.d = d;
    this.delta =delta;
    this.string = string;
    this.rules =rules;
    this.iniDir = iniDir;
    this.iniPos = iniPos;
  }
  
  void step(){
    String nextString = "";
    for(int i = 0; i < string.length(); i++){
      char c = string.charAt(i);
      if(rules.containsKey(c)){
        nextString += rules.get(c);
      } else {
        nextString += c;
      }
    } 
    string = nextString;
  }
  
  void draw(){
    background(0);
    stroke(255);
    translate(width / 2, height / 2);
    translate(iniPos.x, iniPos.y);
    rotate(radians(iniDir));
    for(int i = 0; i < string.length(); i++){
      char c = string.charAt(i);
      switch(c){
        case 'A':
        case 'B':
        case 'F':
          line(0, 0, d, 0);
          translate(d, 0);
          break;
        case 'X':
        case 'Y':
        case 'f':
          translate(d, 0);
          break;
        case '+':
          rotate(radians(-delta));
          break;
        case '-':
          rotate(radians(delta));
          break;
        case '[':
          pushMatrix();
          break;
        case ']':
          popMatrix();
          break;
      }
    }  
  }
}