I wrote a simple 3d flood-filling algorithm to draw a diamond shape into an array (that array is pseudo multi dimensional as described in this post). The actual method looks like this:
/**
* Draws a 3d diamond shape into an array using a flood fill algorithm.
*
* @param data The array to "draw" the diamond shape in. Must be of length 100 * 100 * 100 and all values must be 0.
* @param pos Tupel of x, y, z position to be the center of the diamond.
*/
export function flood3dDiamondShape(data: Uint8Array, pos: [number, number, number], distance = 0): void {
if (distance > 10) {
return;
}
const [x, y, z] = pos;
const index = (x) + (z * 100) + (y * 100 * 100);
if (data[index] > 0) {
return;
}
data[index] = 1;
flood3dDiamondShape(data, [x + 1, y, z], distance + 1);
flood3dDiamondShape(data, [x - 1, y, z], distance + 1);
flood3dDiamondShape(data, [x, y + 1, z], distance + 1);
flood3dDiamondShape(data, [x, y - 1, z], distance + 1);
flood3dDiamondShape(data, [x, y, z + 1], distance + 1);
flood3dDiamondShape(data, [x, y, z - 1], distance + 1);
}
However, this doesn't result in the expected result but draws a strangely shaped "blob" into the array (refer to image 2). I tried to debug that behavior by wrapping the six calls to flood3dDiamondShape(...)
into a setTimeout
callback. It looks like this:
setTimeout(() => {
flood3dDiamondShape(data, [x + 1, y, z], distance + 1);
flood3dDiamondShape(data, [x - 1, y, z], distance + 1);
flood3dDiamondShape(data, [x, y + 1, z], distance + 1);
flood3dDiamondShape(data, [x, y - 1, z], distance + 1);
flood3dDiamondShape(data, [x, y, z + 1], distance + 1);
flood3dDiamondShape(data, [x, y, z - 1], distance + 1);
}, 1);
This still works but now the strange "blob" isn't there anymore. It now is the expected diamond shape as you may see in image 3.
Note that using the second method I of course waited for the algorithm to finish before actually drawing the shape.
The question now actually is: Why am I experiencing this behavior? I would like to get the diamond shape 3 but without using setTimeout
.
Minimum working example: I created a 2d version in html to show the algorithm. Please refer to: https://pastebin.com/raw/MvyJzR5x. How it looks: 4