Raymarching & Signed Distance Fields (SDF)

🔮 Raymarching & Signed Distance Fields (SDF)

While traditional 3D graphics rasterize polygon meshes, Raymarching renders volumetric clouds, fractals, fluid metaballs, and CSG geometry using Signed Distance Fields (SDFs) in a single fullscreen fragment shader.


📐 1. What is a Signed Distance Field?

An SDF is a mathematical function that takes a 3D point p and returns the shortest distance to the surface of a shape:

Primitive SDF Formulas

// Sphere centered at origin with radius r
float sdSphere(vec3 p, float r) {
    return length(p) - r;
}

// Box with half-extents b
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);
}

⚡ 2. The Raymarching Sphere Tracing Loop

vec3 ray_origin = camera_pos;
vec3 ray_dir = normalize(ray_target - camera_pos);
float distance_traveled = 0.0;

for (int i = 0; i < 100; i++) {
    vec3 current_pos = ray_origin + ray_dir * distance_traveled;
    float dist = sdSphere(current_pos, 1.0); // Distance to closest surface
    
    if (dist < 0.001) {
        // Hit surface! Calculate normal and shade pixel
        break;
    }
    
    distance_traveled += dist; // Step forward safely by minimum distance
    if (distance_traveled > 100.0) break; // Missed all objects
}