Lesson 2 of 10 · Ray marching in GLSL
The sphere
An SDF: a formula that measures how far the surface is.
How does the ray know it hit something? With an SDF (signed distance function). You feed it a point in space and it returns the distance to the nearest object. The sphere is the simplest: length(p)-1.0. Negative inside, positive outside, zero right on the shell.
The ray walks forward until the SDF returns almost zero, that is the hit. For now we just paint the silhouette white against the sky.
length(p)-r
length(p) is the distance from the point to the center. Subtract the radius r and you get the distance to the surface. This subtraction is the heart of everything: change the formula, change the shape.Change the radius
1.0 to 1.6 and the sphere grows to fill the frame.The code
precision highp float;
float map(vec3 p){
return length(p)-1.0;
}
void main(){
vec2 uv=(gl_FragCoord.xy*2.0-R)/R.y;
vec3 ro=vec3(0.0,0.0,3.0);
vec3 rd=normalize(vec3(uv,-1.5));
float t=0.0;
float hit=0.0;
for(int i=0;i<48;i++){
vec3 pos=ro+rd*t;
float d=map(pos);
if(d<0.001){ hit=1.0; break; }
t+=d*0.90;
if(t>10.0) break;
}
vec3 sky=mix(vec3(0.05,0.06,0.12), vec3(0.18,0.26,0.50), uv.y*0.5+0.5);
vec3 col=mix(sky, vec3(1.0), hit);
gl_FragColor=vec4(col,1.0);
}