DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Cantor's Sets With Processing

02.04.2008
| 7302 views |
  • submit to reddit
        This simple Processing programme generates the <a href="http://en.wikibooks.org/wiki/Fractals/Cantor's_Set">Cantor's Sets</a> fractal.

Images are generated randomly, but tend to look like <a href="http://scvalex.deviantart.com/art/Cantor-s-Sets-76451637">this</a>.

int setHeight = 60;
color setColour = color(184 + random(-40, 40),
                        124 + random(-40, 40),
                        124 + random(-40, 40));
int wid = 600;

void setup() {
  size(wid, (int)((log(wid) / log(3) + 1) * (setHeight + 5)));
  background(0);
  smooth();
  
  cantorSet(10, 10, width - 20, setColour);
  
  save("cantorSet.png");
}

float rnd(float x) {
  return x + random(-20, 20);
}

void brushRect(int x, int y, int w, int h) {
  for (int i = 0; i < h; ++i) {
    float r = random(3);
    strokeWeight(r);
    float downpull = random(h / 4);
    float shudder = random(-2, 2);
    line(x + shudder, y + i, x + w - shudder, y + i + downpull);
  }
}

void cantorSet(int y, int offX, int wid, color col) {
  if ((y > height - 10) || (wid < 1))
    return;

  stroke(col);
  brushRect(offX, y, wid, setHeight);
  //fill(col);
  //rect(offX, y, wid, setHeight);
  
  color newCol = color(rnd(red(col)), rnd(green(col)),
                      rnd(blue(col)));
  cantorSet(y + setHeight + 5, offX, wid / 3, newCol);
  cantorSet(y + setHeight + 5, offX + wid*2/3, wid / 3, newCol);
}