Menger Sponge
By: Gijs Bellaard

Description
The Menger Sponge is made by repeatedly dividing all cubes in 27 smallers cubes of which the centers are removed.
GLSL Code
// the amount of iterations
const int ITERATIONS = 15;
// distance to a unit cube
float distanceUnitCube(vec3 p)
{
vec3 d = abs(p) - 1.0;
return length(max(d, 0.0)) + min(max(d.x,max(d.y,d.z)), 0.0);
}
float distanceMengerSponge(vec3 p)
{
float s = 1.;
for(int n=0; n<ITERATIONS; n++)
{
// fold
p = abs(p);
// scaling
p *= 3.;
s *= 3.;
// folds
if(p.y<p.x) p.xy = p.yx;
if(p.z<p.x) p.xz = p.zx;
if(p.y<p.z) p.zy = p.yz;
// offset
p -= 2.;
// offset
p.x += 1.;
// fold
p.x = abs(p.x);
// offset
p.x -= 1.;
}
// distance to a unit cube
float d = distanceUnitCube(p);
return d/s;
}