chewie-Intersections

// Starter Code for "Embedded Iteration + Randomness"
var boolDoRefresh;
var lines = [];
var intersections = [];
var lineLength = 300;
var circWidth = 30;
var numLines = 12;
var numIntersections = 0;
 
function setup() {
  createCanvas(720, 480);
  boolDoRefresh = true;
}
 
function draw() {
  if (boolDoRefresh) {
    background(255);
    lines = [];
    intersections = [];
    numIntersections = 0;
    for (var i = 0; i < numLines; i++) {
      lines.push(new Line());
      for (var j = 0; j < i; j++) {
        intersects(lines[i], lines[j]);
      }
    }
    for (i = 0; i < numLines; i++) {
      lines[i].display();
    }
    for (i = 0; i < numIntersections; i++) {
      fill(100,75,125,50);
      intersections[i].display();
    }
    boolDoRefresh = false;
  }
}
 
function mousePressed() {
  boolDoRefresh = true;
}
 
function Line() {
  this.x1 = int(random(width));
  this.y1 = int(random(height));
  this.angle = int(random(360));
  this.radians = 0;
  this.display = function() {
    stroke("black");
    line(this.x1, this.y1, this.x2, this.y2);
  };
  this.updateRad = function() {
    this.radians = radians(this.angle);
  };
  this.angle = modAngle(this.angle);
  this.updateRad();
  this.x2 = this.x1 + lineLength * cos(this.radians);
  this.y2 = this.y1 + lineLength * sin(this.radians);
}
 
 
function Intersection(x, y) {
  this.x = x;
  this.y = y;
  this.display = function() {
    ellipse(this.x, this.y, circWidth, circWidth);
  }
}
 
function linePointAngle(line1, px, py) {
  var lx = line1.x1;
  var ly = line1.y1;
  //this first angle is between universal and two points
  var angle = degrees(atan((py-ly)/(px-lx)));
  if (px<lx) angle+=180;
  //angle -= line1.angle;
  angle = modAngle(angle);
  //then find the difference of the line angle and this
  //angle to get the relative angle of the point to the line
  return angle;
}
 
function modAngle(angle) {
  while(angle<0) angle += 360;
  while(angle>=360) angle -=360;
  return angle;
}
 
function splits(line1, line2) {
  var angle1 = linePointAngle(line1, line2.x1, line2.y1);
  var angle2 = linePointAngle(line1, line2.x2, line2.y2);
  if (angle1>angle2) {
		var temp = angle1;
    angle1 = angle2;
    angle2 = temp; //ang1<=ang2
  }
  if (angle2-angle1>=180) {
    return(line1.angle<=angle1 || line1.angle>=angle2);
  }
  return(line1.angle<=angle2 && line1.angle>=angle1);
}
 
function intersects(line1, line2) {
  var res = splits(line1,line2) && splits(line2,line1);
  if (res) intersection(line1, line2);
  return res;
}
 
function intersection(line1, line2) {
  var x1 = line1.x1;
  var x2 = line2.x1;
  var y1 = line1.y1;
  var y2 = line2.y1;
  var m1 = (line1.y2-y1)/(line1.x2-x1);
  var m2 = (line2.y2-y2)/(line2.x2-x2);
  var X = ((x1*m1)-y1-(x2*m2)+y2)/(m1-m2);
  var Y = m1*(X-x1)+y1;
  var res = new Intersection(X, Y);
  intersections.push(res);
  numIntersections += 1;
	return;
}