Menger Sponge
https://scrapbox.io/files/65f2b5ca95822600268936fb.png
code:menger_sponge_sdf.glsl
// distance to a menger sponge of n = 1
float crossDist( in vec3 p ) {
vec3 absp = abs(p);
// get the distance to the closest axis
float maxyz = max(absp.y, absp.z);
float maxxz = max(absp.x, absp.z);
float maxxy = max(absp.x, absp.y);
float cr = 1.0 - (step(maxyz, absp.x)*maxyz+step(maxxz, absp.y)*maxxz+step(maxxy, absp.z)*maxxy);
// cube
float cu = max(maxxy, absp.z) - 3.0;
// remove the cross from the cube
return max(cr, cu);
}
// menger sponge fractal
float fractal( in vec3 p ) {
float scale = 1.0;
float dist = 0.0;
for (int i = 0 ; i < FRACTAL_ITER ; i++) {
dist = max(dist, crossDist(p)*scale);
p = fract((p-1.0)*0.5) * 6.0 - 3.0;
scale /= 3.0;
}
return dist;
}
Livecoded
code:menger_sponge_sdf.glsl
float cd( in vec3 p ) {
p = abs(p);
float d=0.,m;
for(int i=0;i++<3.;){
d+=step(m=max(p.y,p.z),p.x)*m;
p = p.yzx;
}
return max(max(p.x,max(p.y,p.z))-3,1.-d);
}
// menger sponge fractal
float fractal( in vec3 p ) {
float s = 1.,d=0.;
for (int i=0;i<6;i++){
d = max(d, cd(p)*s);
p = fract((p-1.)*.5)*6.-3.;
s /= 3.0;
}
return d;
}