Ray marching is a technique that simulates 3D objects inside a shader by checking distances to surfaces instead of using polygons. It’s often used for volumetric rendering, fog, and signed distance fields (SDFs).
Simple Ray Marching Example
This GLSL code renders a 3D sphere inside a shader:
float sphereSDF(vec3 p) {
return length(p) - 1.0; // Distance from a sphere of radius 1
}
float rayMarch(vec3 ro, vec3 rd) {
float depth = 0.0;
for (int i = 0; i < 64; i++) { // Loop for marching steps
vec3 pos = ro + depth * rd; // Current position
float d = sphereSDF(pos); // Distance to sphere
if (d < 0.001) return depth; // Hit the surface
depth += d; // Move forward
}
return -1.0; // No hit
}
void main() {
vec3 ro = vec3(0.0, 0.0, -3.0); // Camera position
vec3 rd = normalize(vec3(gl_FragCoord.xy / iResolution.xy - 0.5, 1.0)); // Ray direction
float dist = rayMarch(ro, rd);
vec3 color = (dist > 0.0) ? vec3(1.0, 0.5, 0.0) : vec3(0.0); // Color the sphere
gl_FragColor = vec4(color, 1.0);
}
🔹 How it works: The shader sends a ray from the camera and steps forward until it hits a sphere. The sphere is created with a Signed Distance Function (SDF).