Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

再帰的な三角形分割

/**
* recursive triangle division
*
* @author aa_debdeb
* @date 2016/10/16
*/

void setup(){
  size(640, 640);
  noStroke();
  colorMode(HSB, 360, 100, 100);
  mousePressed();
}

void mousePressed(){
  float hue = random(360);
  background(hue, 40, 100);
  pushMatrix();
  translate(width / 2, height * 3.0 / 5);
  ArrayList<Triangle> triangles = new ArrayList<Triangle>();
  triangles.add(new Triangle());
  while(triangles.size() != 0){
    Triangle tri = triangles.remove(0);
    if((tri.depth <= 1) || (tri.depth < 5 && random(1) < 0.9)){
      triangles.addAll(tri.divide());
    } else {
      fill(hue, random(40, 100), random(60, 100));
      tri.display();
    }
  } 
  popMatrix();
}

void draw(){

}

class Triangle{

  PVector loc;
  float radious;  
  float startAngle;
  int depth;
  
  Triangle(){
    loc = new PVector(0, 0);
    radious = 320;
    startAngle = -HALF_PI;
    depth = 0;
  }
  
  Triangle(PVector _loc, float _radious, float _startAngle, int _depth){
    loc = _loc;
    radious = _radious;
    startAngle = _startAngle;
    depth = _depth;
  }
  
  ArrayList<Triangle> divide(){
    ArrayList<Triangle> children = new ArrayList<Triangle>();
    float cRadious = radious / 2.0;
    for(int i = 0; i < 3; i++){
      PVector cLoc = new PVector(loc.x + cRadious * cos(i * TWO_PI / 3 + startAngle), loc.y + cRadious* sin(i * TWO_PI / 3 + startAngle));
      float cStartAngle = startAngle + i * TWO_PI / 3;
      children.add(new Triangle(cLoc, cRadious, cStartAngle, depth + 1));
    }
    children.add(new Triangle(new PVector(loc.x, loc.y), cRadious, -1 * startAngle, depth + 1));
    
    return children;
  }
  
  void display(){
    pushMatrix();
    translate(loc.x, loc.y);
    beginShape();
    for(int i = 0; i < 3; i++){
      vertex(radious * cos(i * TWO_PI / 3 + startAngle), radious * sin(i * TWO_PI / 3 + startAngle));
    }
    endShape(CLOSE);
    popMatrix();
  }
  
}
f:id:aa_debdeb:20161009081544j:plain