Ray Marching & SDFs
Ray marching with SDFs renders complex 3-D scenes entirely in a fragment shader (Shadertoy style).
30.1 Sphere tracing
Ray marching with SDFs renders complex 3-D scenes entirely in a fragment shader (Shadertoy style).
// 3-D SDF primitives
float sdSphere(vec3 p, float r) { return length(p) - r; }
float sdBox(vec3 p, vec3 b) { vec3 q = abs(p) - b; return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0); }
float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; }
float sdPlane(vec3 p) { return p.y; }
float sdCapsule(vec3 p, vec3 a, vec3 b, float r) {
vec3 pa = p - a, ba = b - a;
float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
return length(pa - ba * h) - r;
}
float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }
float map(vec3 p) { // the whole scene as one distance function
float sphere = sdSphere(p - vec3(0.0, 1.0 + 0.3 * sin(iTime), 0.0), 1.0);
float torus = sdTorus(p - vec3(0.0, 1.0, 0.0), vec2(1.6, 0.25));
float ground = sdPlane(p);
vec3 q = p; q.xz = mod(q.xz + 2.0, 4.0) - 2.0; // infinite repetition
float pillars = sdBox(q - vec3(0, 1, 0), vec3(0.2, 1.0, 0.2));
return min(min(smin(sphere, torus, 0.4), ground), pillars);
}
vec3 calcNormal(vec3 p) {
…30.2 Beyond basics
Fractals (Mandelbulb, Menger sponge, Kaleidoscopic IFS), domain deformations (twist, bend), material IDs (return vec2(distance, materialID)), reflections/refraction by re-marching, volumetric clouds (march with fixed steps, accumulate density with Beer–Lambert), path tracing in fragment shaders with progressive accumulation (multi-pass buffers on Shadertoy).