TExcelTAD
Home › Shaders & Graphics Programming › Shapes with SDFs

Shapes with SDFs

A fragment shader cannot "draw a circle" the way a canvas API does. It can only answer, for one pixel at a time, is this pixel inside the circle? The most useful way to answer is a signed distance function (SDF): a function that returns the distance from a point to the edge of a shape, negative inside, positive outside and zero on the edge.

That one number gives you much more than inside/outside. It tells you how far you are from the edge, so you get anti-aliasing, outlines, glows and shadows almost for free. The same idea, in 3D, powers the raymarched scenes later in this course.

The circle

The distance from point p to a circle of radius r centered at the origin is the distance to the center minus the radius:

glsl
float sdCircle(vec2 p, float r) { return length(p) - r; }

Visualizing the SDF itself is the best way to understand it. Below, orange is outside, blue is inside, the stripes are lines of equal distance, and the white line is the edge (d = 0):

glsl · try it yourself
float sdCircle(vec2 p, float r) { return length(p) - r; }

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    float d = sdCircle(p, 0.25);

    vec3 color = d > 0.0 ? vec3(0.9, 0.6, 0.3) : vec3(0.4, 0.7, 0.9);
    color *= 1.0 - exp(-12.0 * abs(d));                 // darker near the edge
    color *= 0.8 + 0.2 * cos(120.0 * d);               // distance stripes
    color = mix(color, vec3(1.0), 1.0 - smoothstep(0.0, 0.006, abs(d)));
    fragColor = vec4(color, 1.0);
}

Filling with anti-aliasing

To fill the shape, turn the distance into a coverage value. A hard step(0.0, -d) gives jagged edges because each pixel is either fully in or fully out. A smoothstep over the width of about one pixel gives smooth edges. One pixel in our p units is 1.0 / iResolution.y:

glsl · try it yourself
float sdCircle(vec2 p, float r) { return length(p) - r; }

float sdBox(vec2 p, vec2 halfSize) {
    vec2 q = abs(p) - halfSize;
    return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    float px = 1.0 / iResolution.y;

    float circle = sdCircle(p - vec2(-0.35, 0.0), 0.2);
    float box    = sdBox(p - vec2(0.35, 0.0), vec2(0.2, 0.12));

    vec3 color = vec3(0.12);
    color = mix(color, vec3(0.95, 0.4, 0.3), 1.0 - smoothstep(-px, px, circle));
    color = mix(color, vec3(0.3, 0.7, 0.95), 1.0 - smoothstep(-px, px, box));
    // An outline is just |d| below a thickness:
    float ring = abs(box) - 0.01;
    color = mix(color, vec3(1.0), 1.0 - smoothstep(-px, px, ring));
    fragColor = vec4(color, 1.0);
}

The box SDF deserves a closer look. abs(p) folds all four quadrants onto one, so we only handle the top-right corner. q = abs(p) - halfSize is the offset from the corner. If both components of q are positive, the point is diagonally outside and the distance is length(q). If only one is positive, max(q, 0.0) keeps that one. Inside, both are negative and the distance to the nearest side is max(q.x, q.y).

Tip: abs(d) - thickness turns any filled shape into an outline (a ring). d - r rounds it by r. These two operators work on every SDF.

Combining shapes

Because SDFs are just numbers, you combine shapes with math:

Operation Formula Result
union min(a, b) either shape
intersection max(a, b) only the overlap
subtraction (a minus b) max(a, -b) a with b cut out
smooth union smin(a, b, k) blobby merge with blend radius k
rounding a - r rounded corners
annulus (ring) abs(a) - t outline of thickness 2t

The smooth minimum is what makes metaballs and organic shapes possible. This is the polynomial version; k is the blend size:

glsl · try it yourself
float sdCircle(vec2 p, float r) { return length(p) - r; }

float smin(float a, float b, float k) {
    float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);
    return mix(b, a, h) - k * h * (1.0 - h);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    float px = 1.0 / iResolution.y;

    vec2 c1 = vec2(-0.25 + 0.2 * sin(iTime), 0.0);
    vec2 c2 = vec2(0.2, 0.05);
    float a = sdCircle(p - c1, 0.15);
    float b = sdCircle(p - c2, 0.2);

    float d = p.y > 0.0 ? smin(a, b, 0.15) : min(a, b);   // top: smooth, bottom: hard union
    vec3 color = mix(vec3(0.1), vec3(0.9, 0.85, 0.3), 1.0 - smoothstep(-px, px, d));
    color = mix(color, vec3(0.5), 1.0 - smoothstep(0.0, px, abs(p.y)));   // divider line
    fragColor = vec4(color, 1.0);
}

Watch the moving circle: in the top half it melts into its neighbor, in the bottom half the shapes just overlap.

Glow and shadow from the same distance

Since d is the distance to the edge, a glow is a function that decays with d, and a drop shadow is the same shape sampled at an offset. No extra geometry, no blur:

glsl · try it yourself
float sdBox(vec2 p, vec2 b) {
    vec2 q = abs(p) - b;
    return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    float px = 1.0 / iResolution.y;
    vec3 color = vec3(0.9, 0.92, 0.95);

    float shadow = sdBox(p - vec2(0.03, -0.04), vec2(0.25, 0.12)) - 0.04;
    color *= 1.0 - 0.35 * (1.0 - smoothstep(-0.02, 0.06, shadow));   // soft shadow

    float card = sdBox(p, vec2(0.25, 0.12)) - 0.04;                     // rounded card
    color = mix(color, vec3(0.2, 0.45, 0.9), 1.0 - smoothstep(-px, px, card));

    float glow = 0.006 / max(abs(card), 0.002);                        // neon edge
    color += vec3(0.3, 0.6, 1.0) * glow * 0.5;
    fragColor = vec4(color, 1.0);
}

Where to find more SDFs

Inigo Quilez maintains the standard reference of exact 2D and 3D distance functions (segments, triangles, stars, hearts, Bézier curves) at iquilezles.org/articles/distfunctions2d/. Copy the formula, but test it the way this lesson does: visualize the field with stripes, so you see at once if it is exact or only a "bound" that underestimates distance.

Test yourself

What does an SDF return for a point inside the shape?

  1. A positive distance
  2. A negative distance
  3. Exactly zero
  4. The shape's area

How do you subtract shape b from shape a with SDFs?

  1. min(a, b)
  2. max(a, b)
  3. max(a, -b)
  4. a - b

Why use smoothstep(-px, px, d) instead of step(0.0, d) to fill a shape?

  1. It is faster
  2. It blends over about one pixel, anti-aliasing the edge
  3. step does not work on floats
  4. It makes the shape bigger