Lesson 1 of 10 · Ray marching in GLSL
The ray
A camera, one ray per pixel. The sky is its direction.
Until now each pixel asked what color am I?. In 3D it asks something else: which way am I looking? Every pixel shoots a ray from the camera eye into the scene.
The eye is ro (ray origin). The direction is rd (ray direction), built from screen coordinates: normalize(vec3(uv,-fov)). Nothing to hit yet, so we paint the sky by where the ray points: one color up, another down.
ro and rd
ro is where the ray starts (the camera). rd is where it goes, a unit-length vector. All raymarching begins with these two. fov spreads the rays: higher = tighter lens, more zoom.Reading the code
uv: the pixel’s position, centered and scaled by the screen’s height.vec3: from here on, positions carry three numbers: x, y and depth, z.normalize(vec3(uv,-fov)): one direction per pixel, of length 1, pointing into the screen.rd.y*0.5+0.5: how high the ray looks, from 0 (down) to 1 (up). The sky’s gradient.dot(rd,sunDir): how straight the ray points at the sun. 1 means right at it.pow(…,12.0): squeezes that number so only the rays near the sun light up. The sun’s disc.Push
fov=1.5 to 2.5 and the world comes closer. The second slider sharpens the horizon sun (12.0).The code
precision highp float;
void main(){
vec2 uv=(gl_FragCoord.xy*2.0-R)/R.y;
vec3 ro=vec3(0.0,0.0,3.0);
float fov=1.5;
vec3 rd=normalize(vec3(uv,-fov));
float h=rd.y*0.5+0.5;
vec3 col=mix(vec3(0.42,0.16,0.12), vec3(0.10,0.14,0.40), h);
vec3 sunDir=normalize(vec3(0.3,0.25,-1.0));
float sun=pow(max(0.0,dot(rd,sunDir)),12.0);
col+=vec3(0.98,0.70,0.38)*sun*0.9;
gl_FragColor=vec4(col,1.0);
}