Skip to content

Instantly share code, notes, and snippets.

@jose-villegas
Created March 14, 2015 19:13
Show Gist options
  • Save jose-villegas/961e0517f24199cd4493 to your computer and use it in GitHub Desktop.
Save jose-villegas/961e0517f24199cd4493 to your computer and use it in GitHub Desktop.
Diffusion Limited Aggregation Fractal
private class Node
{
public Node parent = null;
public int x = 0;
public int y = 0;
public void Visit()
{
Heightmap.Instance[x, y] += 1;
if(parent != null)
{
parent.Visit();
}
}
public Node() { }
public Node(Node parent, int x, int y)
{
this.x = x;
this.y = y;
this.parent = parent;
}
}
public void DiffusionLimitedAggregation(int seed, float occupationPercent = 0.15f, int numberNodes = 1)
{
// start fractal
Random rand = new Random(seed);
Node[,] nodes = new Node[_width, _height];
for(int i = 0; i < numberNodes; i++)
{
nodes[rand.Next(_width), rand.Next(_height)] = new Node();
}
int total = rand.Next(_width * _height - (int)(_width * _width * occupationPercent), _width * _height);
int x, y;
while(total < _width * _height)
{
x = rand.Next(Width);
y = rand.Next(Height);
if(nodes[x, y] != null)
{
continue;
}
bool hit = false;
// random walk until hit something
while(!hit)
{
int prevX = x;
int prevY = y;
int[] newValues = { rand.Next(-1, 2), rand.Next(-1, 2) };
if(newValues[0] == newValues[1] && newValues[0] == 0)
{
newValues[rand.Next(2)] = rand.Next(2) == 0 ? 1 : -1;
}
x += newValues[0];
y += newValues[1];
// out of bounds
if(x < 0 || y < 0 || y > Height - 1 || x > Width - 1)
{
break;
}
Node n = nodes[x, y];
if(n != null)
{
hit = true;
total += 1;
n = new Node(n, prevX, prevY);
nodes[prevX, prevY] = n;
n.Visit();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment