Mandelbox
By: Gijs Bellaard

Description
GLSL Code
// the amount of iterations
const int ITERATIONS = 15;
// radius of the sphere inversion
const float RADIUS = 0.25;
// the scaling factor between iterations
const float SCALE = 3.0;
// min corner of the box fold
const vec3 MIN = vec3(-1);
// max corner of the box fold
const vec3 MAX = vec3(1);
// precomputations
const float R1 = abs(SCALE - 1.0);
const float R2 = pow(abs(SCALE), float(1 - ITERATIONS));
float distanceMandelbox(vec3 p)
{
float s = 1.0;
vec3 p0 = p;
for (int i = 0; i<ITERATIONS; i++)
{
// box fold
p = clamp(p, MIN, MAX) * 2.0 - p;
// sphere inversion
float r2 = dot(p, p);
float k = clamp(max(RADIUS / r2, RADIUS), 0.0, 1.0);
p *= k;
s *= k;
// scaling and offset
p = p * SCALE/RADIUS + p0;
s = s * abs(SCALE)/RADIUS + 1.0;
}
// final distance
return (length(p) - R1) / s - R2;
}