spoike
9/2/2011 - 7:35 AM

Funky pattern

Funky pattern

/**
 * Funky pattern generator. Creates a rather funky, Amiga-esque
 * demo pattern that fades and regenerates. Looks cool but is 
 * quite useless.
 *
 * Uses sinus function to generate the colors, offset and 
 * scaled so that the bound [-1.0f, 1.0f] is [0, 255] instead.
 */

void setup()
{
  int w = 1024;
  size(200, 200);
  background(backCol);
  // Using primes 7, 11, 13 as stepping value to create 
  // seemingly non-repetetive unique patterns for each
  // color channel.
  r = new Col(0, 0.011);
  g = new Col(PI/2, 0.007);
  b = new Col(PI, 0.013);
}

int backCol = 50;
float y = 100;
int gridw = 7;
int gridh = 3;
boolean inv = false;
Col r;
Col g;
Col b;

void draw() 
{
  r.stepUp();
  g.stepUp();
  b.stepUp();

  // Step up y  
  y = y - 1;
  if (y < 0) {
    y = height;
  }
  
  // draw it
  drawit(y, r, g, b);
  fill(backCol, 2);
  noStroke();
  rect(0, 0, width, height);
}

void drawit(float y, Col r, Col g, Col b) {
  if (y % gridh == 0) {
    inv = !inv;
  }
  int r1 = inv ? r.getCol(true) : r.getCol(false);
  int r2 = 255 - r1;
  int g1 = inv ? g.getCol(true) : g.getCol(false);
  int g2 = 255 - g1;
  int b1 = inv ? b.getCol(true) : b.getCol(false);
  int b2 = 255 - b1;
  for (int i = 0; i < width; i += gridw*2) {
    stroke(r1, g1, b1);
    line(i, y, i+gridw, y);
    stroke(r2/2, g2/2, b2/2);
    line(i+gridw, y, i+gridw+gridw, y);
  }
}

class Col {
  float rad = 0;
  float radStep = 0.01f;
  
  Col(float rad, float radStep) {
    this.rad = rad;
    this.radStep = radStep;
  }
  
  public void stepUp() {
    rad += radStep;
    if (rad >= 2*PI) {
      rad = 0;
    }
  }
  
  public int getCol(boolean inverted) {
    int out = (int) ((cos(rad) + 1f / 2f) * 255f);
    return inverted ? out : 255 - out;
  }
}