#include "testApp.h"


//--------------------------------------------------------------
void testApp::setup() {
	
	ofBackground(255, 255, 255);
	
	bDoneMakingDots = false;
	capture			= false;
	bDrawFace		= false;
	startSize		= 200;
	maxDots			= 20000;
	
	photo.loadImage("face.jpg");
	
}

//--------------------------------------------------------------
void testApp::update() {
	
	if(dots.size() < maxDots) {
		int num = 100;
		for(int i=0; i<num; i++) {
			
			unsigned char * px	 = photo.getPixels();
			int				w	 = photo.getWidth();
			int				h	 = photo.getHeight();
			
			// make a new dot
			Dot newDot;
			newDot.x	  = ofRandom(0, w);
			newDot.y	  = ofRandom(0, h);
			
			// pixel position
			int index	  = MAX(0 , MIN(w*h, (int)newDot.y*w+(int)newDot.x));
			newDot.r	  = px[ (index*3) + 0 ];
			newDot.g	  = px[ (index*3) + 1 ];
			newDot.b	  = px[ (index*3) + 2 ];
			
			// skip the white pixels
			int grayVal   = (newDot.r+newDot.g+newDot.b)/3;
			if(grayVal > 230) continue;
			
			newDot.a	  = 50;
			newDot.radius = ofRandom(1, startSize);

			dots.push_back(newDot);
		}
		
		if(startSize > 9) startSize -= 0.3;
	}
	
	if(!bDoneMakingDots && dots.size() >= maxDots) {
		bDoneMakingDots = true;
		printf("--- done making dots ---\n");
	}

}

//--------------------------------------------------------------
void testApp::draw(){
	
	if(capture){
		output.begin("face.pdf", ofGetWidth(), ofGetHeight(), OF_OUTPUT_PDF);
	}
	
	if(bDrawFace) {
		
		ofEnableAlphaBlending();
		for(int i=0; i<dots.size(); i++) {
			Dot &d = dots[i];
			output.setColor(d.r, d.g, d.b, d.a);
			output.fill();
			output.circle(d.x, d.y, d.radius);
			
			// add a outline you can do 
			// this in illustrator doing 
			// it in cairo cause two circles...
			ofSetColor(20, 20, 20, 100);
			ofNoFill();
			ofCircle(d.x, d.y, d.radius);
			
		}
		ofDisableAlphaBlending();
		ofSetColor(0xffffff);
		//photo.draw(0, 0);
	}
	
	
	if(capture){
		output.end();
		capture =false;
	}
	
	
}

//--------------------------------------------------------------
void testApp::keyPressed(int key){
	if(key == ' '){
		capture = true;
	}
	if(key == 'f') bDrawFace = !bDrawFace;
	if(key == 'c') {
		dots.clear();
		startSize = ofRandom(40, 200);
		bDoneMakingDots = false;
	}
}

//--------------------------------------------------------------
void testApp::keyReleased(int key){
	
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
	
}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
	
}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}


//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
	
}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
	
}

