xxxxxxxxxx
82
//When R^2 plane is divided into small grids, dragon curves will pass through each grid only once, without intersecting with other cruves. In other words, dragon curves can "fill" (space-filling) entire R^2 plane.
let dirArr = []; //Direciton Array storing Left or Right turn for each line segments
let count = 0; //Counter for recursive function
let colorArr = ["green", "red", "blue", "magenta", "cyan"]; //Array storing predefined colors
function setup() {
createCanvas(600,600);
translate(width / 2, height / 2); //Shift reference point to the canvas center
strokeWeight(1.5);
let lineLength = 1; //Declare length of each straight line segment
let coordX = 0; //X Coordinate of the first line segment
let coordY = 0 - lineLength; //Y Coordinate of the second line segment
let angleDiff = PI/2; //Angle difference between each dragon curve to draw
dirArr = []; //reset dirArr
dirArr[0] = 1;
fillDirArr(19, dirArr); //Store Left or Right turns into dirArr. 1 = Right turn, -1 = Left turn
for (let i = 0; i < (2 * PI) / angleDiff; i++) {
//Draw multiple dragon curves
coordX = 0;
coordY = 0;
rotate(i * angleDiff); //Rotate reference point
line(0, 0, coordX, coordY); //Draw first line segment of the curve
//stroke(colorArr[i]);
if (i % 2) stroke(i * 60);
else stroke(128*i,45*i,60*i);
drawDragonCurve(coordX, coordY, lineLength); //Draw dragon curve based on dirArr
}
}
function draw() {}
//Draw dragon curve based on dirArr
function drawDragonCurve(X, Y, L) {
let dirSum = 0; //1 or -1 act as "weights".
for (let i = 0; i < dirArr.length; i++) {
let currDir = dirArr[i];
dirSum = (dirSum + currDir) % 4;
if (dirSum == 0) {
//UP
//line(X, Y, X + L * currDir, Y);
line(X, Y, X + round(random(0,5*L)) * currDir, Y);
X += L * currDir;
} else if (dirSum == 1 || dirSum == -3) {
//RIGHT
//line(X, Y, X, Y + L * currDir);
line(X, Y, X, Y + round(random(0,8*L)) * currDir);
Y += L * currDir;
} else if (dirSum == -1 || dirSum == 3) {
//LEFT
//line(X, Y, X, Y - L * currDir);
line(X, Y, X, Y - round(random(0,5*L)) * currDir);
Y -= L * currDir;
} else if (dirSum == 2 || dirSum == -2) {
//DOWN
//line(X, Y, X - L * currDir, Y);
line(X, Y, X - round(random(0,5*L)) * currDir, Y);
X -= L * currDir;
}
}
}
function fillDirArr(iteration, myArr) {
//Store Left or Right turns into dirArr. 1 = Right turn, -1 = Left
count++;
let tempArr = myArr.slice(); //tempary array to store dirArr
myArr.push(1);
let tempArrLength = tempArr.length;
for (let i = 0; i < tempArrLength; i++) {
let currDir = tempArr.pop(); //Read tempArr from the end
myArr.push(-1 * currDir); //Reverse direction and push to currDir
}
if (iteration == count) {
count = 0;
dirArr = myArr;
return;
} else fillDirArr(iteration, myArr); //recursion until given iteration
}