4.3 Video Sampling + Physics

 

import processing.video.*;
import fisica.*;

ArrayList  <PVector> pixelmatch = new ArrayList <PVector>();
ArrayList  <FCircle> rigid = new ArrayList <FCircle> ();

FWorld world;

Capture cam;

PGraphics video_holder;

int vwidth = 640;
int vheight = 480;

color track_color = color(0,0,0);

void setup() {
  size(640, 480);
  
  String[] cameras = Capture.list();
  
  if (cameras.length == 0) {
    println("There are no cameras available for capture.");
    exit();
  } else {
    println("Available cameras:");
    for (int i = 0; i < cameras.length; i++) {
      println(cameras[16]);
    }
    
    // The camera can be initialized directly using an 
    // element from the array returned by list():
    cam = new Capture(this, cameras[16]);
    cam.start();     
    
    video_holder = createGraphics(vwidth,vheight);
  }     
  Fisica.init(this);

  world = new FWorld();
  world.setGravity(0, 100);
}

void draw() {
  
  rigid = new ArrayList ();
  
  if (cam.available() == true) {
    cam.read();
  }
  video_holder.beginDraw();
  video_holder.image(cam, 0, 0);
  video_holder.endDraw();
  image(video_holder,0,0);
  
  pixelmatch = new ArrayList ();
  
  for(int x = 0; x < cam.width; x++){
    for(int y = 0; y < cam.height; y++){
      color sample_color = video_holder.get(x,y);
      float r1 = red(sample_color);
      float g1 = blue(sample_color);
      float b1 = green(sample_color);
      float r2 = red(track_color);
      float g2 = blue(track_color);
      float b2 = green(track_color);
      
      float range = dist(r1,g1,b1,r2,g2,b2);
      
      if(range < 15){
        pixelmatch.add(new PVector(x,y,0));
      }
    }
  }
  
  for(int i = 0; i < pixelmatch.size(); i++){
    PVector p = pixelmatch.get(i);
    //ellipse(p.x,p.y,5,5);
    if(i%6 == 0){
      FCircle b = new FCircle(10);
      b.setPosition(p.x,p.y);
      b.setStatic(true);
      b.setRestitution(0);
      b.setNoStroke();
      b.setFill(255,0,0,0);
      world.add(b);
      rigid.add(b);
    }
  }
  
  world.draw();
  world.step();
  
  for(int i = 0; i < rigid.size(); i++){ 
    FCircle b = rigid.get(i); 
    world.remove(b); 
  } 
} 

void mouseClicked() { 
  float sz = random(20,50); 
  FCircle b = new FCircle(sz); 
  b.setPosition(mouseX, mouseY); 
  b.setVelocity(random(-100,100), -40); 
  b.setRestitution(0.7); 
  b.setDamping(0.01); 
  b.setNoStroke(); 
  b.setFill(random(255), random(255), random(255)); 
  world.add(b); 
} 

void contactEnded(FContact c) { 
  if (!c.getBody1().isStatic()) { 
    FCircle b = (FCircle)c.getBody1(); 
    if (b.getSize()>10) {
      b.setSize(b.getSize()*0.98);
    }
  } 

  if (!c.getBody2().isStatic()) {
    FCircle b = (FCircle)c.getBody2();
    if (b.getSize()>10) {
      b.setSize(b.getSize()*0.98);
    }
  }
}