/*
* Posture Track
* by Tom Gerhardt, but mostly Dan O'Sullivan (I just added to his code)
* This application tracks your spine angle as you work and graphs the data on screen
*/
package wk3;

import java.awt.Rectangle;
import java.util.ArrayList;

import processing.core.*;
import processing.video.*;

public class PostureTrack extends PApplet{
Capture video;// regular processing libary
PFont font;

float goalHue = 156;

float goalSaturation = 251;

float goalBrightness = 139;

int threshold = 57;

///posture angle vars
float dRectH = 0;
float dRectW = 0;
float posAng = 0;

//graph vars
ArrayList graphLines = new ArrayList();
int arrayOffset = 0;

static public void main(String _args[]) {
PApplet.main(new String[] { "wk3.PostureTrack" });
}

public void setup() {
size(640, 480);
video = new Capture(this, 640, 480);
font = loadFont("HelveticaNeueLTStd-Blk-48.vlw");

}

public void draw() {
if (video.available()) {
video.read();
// make a rectangle at 0,0
Rectangle myRect = null; // make a rect variable but don't put anything in it yet
for (int row = 0; row < video.height; row++) {
for (int col = 0; col < video.width; col++) {
int offset = row * width + col;

int thisPixel = video.pixels[offset];
float h = hue(thisPixel);
float s = saturation(thisPixel);
float b = brightness(thisPixel);
float closeness = dist(h, s, b, goalHue, goalSaturation, goalBrightness);
if (closeness < threshold) {
if (myRect == null) myRect = new Rectangle(col, row, 1, 1);// this is the pixel to quality make a rect
else myRect.add(col, row); // stretch the rect to include this pixel
}
}
}
image(video, 0, 0);
stroke(170,0,80);
fill(0, 255, 0, 0);
if (myRect != null) { //if you found something
//calculate and display posture angle
dRectW = myRect.width;
dRectH = myRect.height;
posAng = dRectH/dRectW;
textFont(font, 64);

if(posAng < .5){
if (graphLines.size() < 640){
graphLines.add(posAng);
} else{
graphLines.remove(0);
graphLines.add(posAng);
//arrayOffset++;
}
for (int c = arrayOffset; c < graphLines.size() - arrayOffset; c++){
strokeWeight(1);
Number tmpNum = (Number) graphLines.get(c);
line(c - arrayOffset, 480, c - arrayOffset, 480 - tmpNum.floatValue() * 400);
}
rect(myRect.x, myRect.y, myRect.width, myRect.height);
ellipse(myRect.x + myRect.width / 2, myRect.y + myRect.height / 2, 10, 10);
fill(170,0,80);
text(posAng, 0,60);
}
}
}
}

public void mousePressed() {

int thisPixel = video.pixels[mouseY * width + mouseX];
goalHue = hue(thisPixel);
goalBrightness = brightness(thisPixel);
goalSaturation = saturation(thisPixel);
println("Goal" + goalHue + " " + goalSaturation + " " + goalBrightness);
}

public void keyPressed() {
if (key == 's') {
video.settings();
} else if (key == '-') {
threshold--;
println("Threshold " + threshold);
} else if (key == '=') {
threshold++;
println("Threshold " + threshold);
}
}
}