
//Woobly Wall-er Polyliner 0.1
//Uses incoming data from Woobly Wall-er (pairs of XY coordinates) and plots a polyline
//Mauro Herrero - Fab Academy 2021
//serialEvent from Marta Verde
//CC BY-SA 4.0 - Attribution-ShareAlike 4.0 International

import processing.serial.*; //load library to read from serial port
import processing.svg.*; //load library to export svg file

float [] values; //array of incoming data, comma separated values
String inString; //incoming data through myPort
Serial myPort; //port open for serial communication
FloatList xCoord; //declare list of stored X coordinates
FloatList yCoord; //idem Y coordinates
int i; //declare variable i to use as counter in for loops
float cX; //declare variable cX to store X coordinates when constructing points
float cY; //idem Y coordinates
boolean record;

void setup(){
  size(1440, 270);
  background(0);
  myPort = new Serial(this, "/dev/ttyUSB0", 115200); // set myPort to connected /dev/ttyUSB0 @115200 bps
  xCoord = new FloatList(); // initialize xCoord FloatList
  yCoord = new FloatList(); // initialize xCoord FloatList
}

void serialEvent(Serial myPort) { //function used to capture data from serial
  inString = myPort.readStringUntil('\n'); // read incoming data up to line next line break
  if (inString != null){ // if there is data...
    inString = trim(inString); // remove whitespace characters from the beginning and end
    values = float(split(inString, ",")); //assemble an array of elements, of the data separated by commas
    if (values.length >=1) { // if the array has data...
      xCoord.append(values[0]); // append data on index 0 to xCoord FloatList
      yCoord.append(values[1]); // append data on index 1 to yCoord FloatList
    }
  }
}

void polyline(){  //create function outside draw() loop
  noFill(); //open shape, no fill
  beginShape(); //self explanatory
    for (i = 1; i < xCoord.size(); i++) { //for loop, use method size() to get number of items in list
      cX = xCoord.get(i)+200; //get x coordinate at index i and store it in var cX
      cY = (-yCoord.get(i)+600); //get y coordinate at index i and store it in var cY
      vertex(cX, cY); // add vertex at cX, cY
    }
  endShape(); //self explanatory
}

void draw() {
  if (record) {
    beginRecord(SVG, "curve-####.svg");
  }
  strokeWeight(3);
  stroke(180);
  polyline(); // call polyline function; with every loop, it will have more vertices
  if (cX > 800) {  
    textSize(36);
    fill(120);
    textAlign(CENTER);
    
    text("press 's' to save svg", width/2, height/4);
  }
  if (record) {
    endRecord();
    record = false;
  }
}

void keyPressed() {
  if (key == 's') {
    record = true;
  }
}
  
