Shaders From Zero · Episode 17
Hello Raymarcher
Hello Raymarcher is Episode 17 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Until this episode every shader you wrote ran on a mesh — a sphere, a plane, a set of points. The vertex shader transformed positions; the fragment shader colored surfaces that already existed. This is the way 99% of real-time graphics works.
The other 1% is what Shadertoy does, and it's what this season is about. The mesh becomes a single full-screen quad. The fragment shader's job becomes: for every pixel, figure out what's in front of the camera at that pixel. You spawn a ray from the camera through the pixel, step it forward through empty space, and when it hits something, color the pixel based on what it hit. This is raymarching, and once it clicks, you can render entire scenes in one fragment shader.
The setup — a full-screen quad
Three.js is barely involved this season. We render one rectangle that covers the entire screen and put all the logic in the fragment shader.
const geometry = new THREE.PlaneGeometry(2, 2);
// vertex shader: pass-through, project to clip space directly
const vertexShader = /*glsl*/`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position.xy, 0.0, 1.0);
}
`;
Three things changed from S1+S2:
- The plane is exactly 2 units wide. Combined with
gl_Position = vec4(position.xy, 0, 1)(skipping the model/view/projection matrices), this maps directly to clip space coordinates[-1, 1]— full screen, no transformations. - The camera is irrelevant. Three.js still needs one, but our shader makes its own camera ray, ignoring Three.js's projection.
- All scene rendering happens in the fragment shader. The geometry just gives the GPU something to rasterize.
The ray
A ray has two pieces: an origin (where it starts) and a direction (where it
points). For a basic camera at (0, 1, -3) looking at the origin:
vec2 ndc = vUv * 2.0 - 1.0; // [-1, 1] both axes
ndc.x *= uResolution.x / uResolution.y; // aspect correction
vec3 ro = vec3(0.0, 1.0, -3.0); // ray origin (camera)
vec3 rd = normalize(vec3(ndc, 1.5)); // ray direction (toward scene)
The 1.5 in rd.z is the focal length. Larger values are
a telephoto lens (narrow field of view); smaller values are wide-angle. Tune to
taste.
That's the camera. No matrices. No imports. Five lines.
The march
The core loop. Start at ro, sample the scene's SDF, step forward
by that distance, repeat. The SDF tells you how far to the nearest surface from
any point — so you're guaranteed to never overshoot.
float t = 0.0; // distance traveled along the ray
for (int i = 0; i < 100; i++) {
vec3 p = ro + rd * t; // current position
float d = sceneSDF(p); // distance to nearest surface
if (d < 0.001) break; // HIT — close enough to a surface
if (t > 50.0) break; // MISS — too far, give up
t += d; // step forward by the SDF distance
}
This is called sphere tracing. Each step is the maximum safe
advance — the SDF promised no surface within distance d, so we can
skip that entire empty region in one jump. Near surfaces, the steps get tiny and
the loop converges; far from anything, the steps are huge and we cover ground
fast.
After the loop, t holds the distance from camera to surface (if we
hit). If we maxed out the loop or exceeded 50.0, we missed.
The scene SDF — a sphere at origin
float sceneSDF(vec3 p) {
return length(p) - 1.0; // sphere radius 1, at origin
}
The same circle SDF from Episode 06, in 3D. length(p) is the
distance from origin; subtract the radius to shift the zero crossing outward. Done.
Layer 1 — Background gradient
Start with NO raymarching. Just color every pixel with a simple gradient — a sanity check that the full-screen quad is rendering and the UVs are correct.
void main() {
vec3 sky = mix(vec3(0.05, 0.08, 0.15), vec3(0.5, 0.65, 0.9), vUv.y);
gl_FragColor = vec4(sky, 1.0);
}
Layer 2 — One sphere, hit/miss
Now the march. Pixels whose ray hit the sphere get a flat color; pixels whose ray missed show the background.
void main() {
vec2 ndc = vUv * 2.0 - 1.0;
ndc.x *= uResolution.x / uResolution.y;
vec3 ro = vec3(0.0, 1.0, -3.0);
vec3 rd = normalize(vec3(ndc, 1.5));
float t = 0.0;
bool hit = false;
for (int i = 0; i < 100; i++) {
vec3 p = ro + rd * t;
float d = length(p) - 1.0;
if (d < 0.001) { hit = true; break; }
if (t > 50.0) break;
t += d;
}
vec3 sky = mix(vec3(0.05, 0.08, 0.15), vec3(0.5, 0.65, 0.9), vUv.y);
vec3 col = hit ? vec3(0.9, 0.4, 0.3) : sky;
gl_FragColor = vec4(col, 1.0);
}
You should see an orange disc on a blue background. That's a 3D sphere — but it looks flat because we have zero lighting yet. The shape is correct; the shading is nonexistent. That's Episode 19.
Layer 3 — Depth visualization
Color by distance from camera. Closer = warm, farther = cool. Demonstrates
that t really is a meaningful 3D distance.
if (hit) {
vec3 closeCol = vec3(0.95, 0.5, 0.3);
vec3 farCol = vec3(0.2, 0.4, 0.7);
col = mix(closeCol, farCol, smoothstep(2.0, 6.0, t));
}
The center of the sphere is brighter (closer); the edges are darker (further). Real depth, computed without ever creating a mesh.
Layer 4 — Step count heatmap
The most useful debug visualization in raymarching. Color pixels by how many iterations the loop needed before hitting (or giving up).
int steps = 0;
for (int i = 0; i < 100; i++) {
steps = i;
vec3 p = ro + rd * t;
float d = length(p) - 1.0;
if (d < 0.001) break;
if (t > 50.0) break;
t += d;
}
float heat = float(steps) / 100.0;
col = vec3(heat, 0.0, 1.0 - heat); // red = expensive, blue = cheap
Watch what happens at the sphere's silhouette. The ray gets close to the surface but doesn't quite hit — each step is tiny, and the loop runs many iterations before giving up. That's why silhouettes are the most expensive pixels in any raymarcher. Knowing this guides optimization.
Layer 5 — Add a floor plane
Combine two SDFs in sceneSDF: sphere + infinite floor plane at
y = 0.
float sceneSDF(vec3 p) {
float sphere = length(p - vec3(0.0, 1.0, 0.0)) - 1.0;
float plane = p.y; // flat floor at y = 0
return min(sphere, plane); // union — nearest of either
}
The floor extends to infinity in every direction (in concept; the marching loop
terminates when t > 50.0). Now you have a scene with depth and
horizon — the sphere floating above the ground.
Putting it together
The full Stage-5 fragment shader. Memorize the shape — every episode this season uses this exact pattern.
uniform vec2 uResolution;
uniform float uTime;
varying vec2 vUv;
float sceneSDF(vec3 p) {
float sphere = length(p - vec3(0.0, 1.0, 0.0)) - 1.0;
float plane = p.y;
return min(sphere, plane);
}
void main() {
vec2 ndc = vUv * 2.0 - 1.0;
ndc.x *= uResolution.x / uResolution.y;
vec3 ro = vec3(0.0, 1.5, -3.5);
vec3 rd = normalize(vec3(ndc, 1.5));
float t = 0.0;
bool hit = false;
for (int i = 0; i < 100; i++) {
vec3 p = ro + rd * t;
float d = sceneSDF(p);
if (d < 0.001) { hit = true; break; }
if (t > 50.0) break;
t += d;
}
vec3 sky = mix(vec3(0.05, 0.08, 0.15), vec3(0.5, 0.65, 0.9), vUv.y);
vec3 col = sky;
if (hit) {
vec3 closeCol = vec3(0.95, 0.5, 0.3);
vec3 farCol = vec3(0.2, 0.35, 0.5);
col = mix(closeCol, farCol, smoothstep(2.0, 8.0, t));
}
gl_FragColor = vec4(col, 1.0);
}
Common pitfalls
- Forgot to aspect-correct. The sphere is an oval. Multiply
ndc.xbyuResolution.x / uResolution.y. - Forgot to normalize
rd. Rays of different lengths step at different speeds. Alwaysrd = normalize(...). - Step count too low. 50 iterations is too few for complex scenes; 256 is the standard upper bound. We use 100 in the demo as a balance.
- Hit threshold too tight.
d < 0.0001can run forever on grazing rays.0.001is plenty for visible accuracy. - Max distance too high. If you set the miss threshold to
1000.0on a scene where most rays escape, every miss costs the full loop budget. Tune to your scene scale.
Exercises
- Move the sphere with
uTime:length(p - vec3(sin(uTime), 1.0, 0.0)) - 1.0. - Replace the sphere with a torus (we'll cover this in Ep 18, but you can peek at the IQ SDF library now).
- Change the focal length from
1.5to0.8for a fisheye effect. Try3.0for a telephoto compression. Notice how the sphere's perspective distortion changes.
What's next
Episode 18 — Shape Library. We extend Episode 06's 2D SDFs into 3D: box, torus, capsule, cylinder. Plus smooth combinations and domain repetition for an infinite tiled scene.