xxxxxxxxxx
96
let refresh;
let iterationAmt;
function setup() {
createCanvas(640, 480);
refresh = true;
iterationAmt = createSlider(2, 100, 12);
}
function draw() {
if (refresh) {
const iterations = iterationAmt.value();
let startpointsx = createPoints(iterations, width);
let startpointsy = createPoints(iterations, height);
let endpointsx = createPoints(iterations, width);
let endpointsy = createPoints(iterations, height);
let intpts = [];
for (let i = 0; i < iterations; i++) {
let pt;
for (let j = 0; j < iterations; j++) {
if (j != i) {
pt = intersect(startpointsx[i], startpointsy[i], endpointsx[i], endpointsy[i], startpointsx[j], startpointsy[j], endpointsx[j], endpointsy[j]);
if (pt.x > -1 || pt.y > -1) {
intpts.push(pt);
}
}
}
stroke(200);
line(
startpointsx[i], startpointsy[i],
endpointsx[i], endpointsy[i]
);
}
// So white circles are on top
for (let i = 0; i < intpts.length; i++)
{
stroke(50);
ellipse(intpts[i].x, intpts[i].y, 10, 10);
}
refresh = false;
}
}
function createPoints(iterations, max) {
let points = [];
for (let i = 0; i < iterations; i++) {
points[i] = random(0, max);
}
return points;
}
// line intercept math by Paul Bourke
// small modification to return -1 instead of false to stick with numbers (since the domain and range of the project is [0, width] [0, height]) by Lukas Hermannrespectively
//http://paulbourke.net/geometry/pointlineplane/
// Determine the intersection point of two line segments
// Return -1 if the lines don't intersect
function intersect(x1, y1, x2, y2, x3, y3, x4, y4) {
// Check if none of the lines are of length 0
if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {
return -1
}
denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))
// Lines are parallel
if (denominator === 0) {
return -1
}
let ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator
let ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator
// is the intersection along the segments
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
return -1
}
// Return a object with the x and y coordinates of the intersection
let x = x1 + ua * (x2 - x1)
let y = y1 + ua * (y2 - y1)
return {
x,
y
}
}
function mouseClicked() {
refresh = true;
console.log(iterationAmt.value());
background(255);
}