/********************************************************/
/* Erik Kastner. http://metaatem.net
/* Playing with processing - balls falling
/********************************************************/

import processing.opengl.*;
import javax.media.opengl.*;
PGraphicsOpenGL pgl;
GL gl;

ArrayList balls; // The balls that wll be drawn
int yPos; // the "bottom" of the screen
int xPos;
int vec; // the vector of x's change

void setup() {
size(400,400,OPENGL);
background(0);
yPos = height;
xPos = width;
vec = 1;

balls = new ArrayList();
}

void draw() {
background(0); // clear the scene each time
lights(); // give the balls some shading
noStroke();

// this next group is additive blending via flight404
pgl = (PGraphicsOpenGL) g;
gl = pgl.gl;

pgl.beginGL();
gl.glDisable(GL.GL_DEPTH_TEST);
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA,GL.GL_ONE);
pgl.endGL();

// add a new ball every 5 frames
if(frameCount % 5 == 0)
balls.add(new Ball());

// loop over all the balls and draw them to the screen
// I had an else in here to do balls.remove(i) but it didn't work, not sure why
for (int i=0; i<balls.size(); i++) {
Ball ba = (Ball)balls.get(i);
// make sure it's in the view
if (ba.y < yPos+50) {
pushMatrix();
translate(ba.x, ba.y, ba.z);
fill(ba.c);
sphere(20);
popMatrix();
}
}

// move the floor up 10 lines
yPos -= 10;

// shimmy the camera left and right
xPos += vec;

// change directions - gives the camera a 50 column "sweep" from left to right
if (xPos >= width+25 || xPos <= width-25) vec *= -1;

// move the cammera
camera(xPos-width/2.0, yPos-height/2, (height/2.0) / tan(PI*60.0 / 360.0), xPos-width/2.0, yPos-height/2, 0, 0, 1, 0);

//saveFrame("filename-####.png");
}

class Ball {
float x;
float y;
float z;
color c;
Ball() {
x = random(width);
y = random(yPos-height*2, yPos-height*3);
z = random(-300,300);
c = color((int)random(255), (int)random(255), (int)random(255), (int)random(100,200));
}
}