6. Shapes and Distance Functions

In the previous chapter we built the playground: one fullscreen quad, and a fragment shader that runs once for every pixel and knows its own position, the time and the mouse.
That is enough to draw anything, but "anything" is not a plan.
In this chapter we learn the most useful way to describe a shape in a fragment shader: as a distance function.

A distance function answers one question for every pixel: "how far am I from the edge of the shape, and am I inside or outside?"
With that one number we can fill shapes, give them perfectly smooth edges, draw outlines, glows and shadows, and glue shapes together like clay.
At the end of the chapter we draw a small character entirely out of circles, boxes and lines, and its eyes follow the mouse.

We only change shader/playground.glsl in this chapter.
No C code changes, so you can keep the tester running and press R after every edit.

6.1 Drawing with distances

Every example starts from the coordinate we made in chapter 5:

vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;

The origin is in the middle of the window, y goes from −1 at the bottom to 1 at the top, and x goes from about −1.33 to 1.33 in an 800×600 window.
One unit is the same length in x and y, so a circle stays round.

Now think about a circle with radius r around the origin.
A pixel at position 𝐩 is at distance ‖𝐩‖ from the centre (the length of a vector, from linear algebra chapter 3).
If we subtract the radius we get the distance to the edge:

d=‖𝐩‖−r

A circle with radius r. A point p outside has d greater than 0, a point q inside has d less than 0, and the edge itself is d = 0

The sign tells us which side we are on:

  • d>0: outside, and d is how far we have to walk to reach the shape.
  • d=0: exactly on the edge.
  • d<0: inside, and −d is how far it is to the edge.

A function like this is called a signed distance function, or SDF.
Let me check it with numbers, with r=0.5:

  • 𝐩=(0.6,0.8): ‖𝐩‖=0.36+0.64=1, so d=1−0.5=0.5. Outside, half a unit away.
  • 𝐩=(0.3,0.4): ‖𝐩‖=0.09+0.16=0.5, so d=0. On the edge.
  • 𝐩=(0,0.2): ‖𝐩‖=0.2, so d=−0.3. Inside, 0.3 from the edge.

In GLSL this is one line:

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

length(v) returns vx2+vy2 (for a vec3, also +vz2).
It is the same as sqrt(dot(v, v)).
The sd in the name means "signed distance"; it is a naming habit used by almost everyone who writes these functions, and I'll use it too.

Why go through the trouble of a distance, instead of just asking "inside or not"?
Because a distance carries much more information.
"Inside or not" gives one bit per pixel.
A distance tells us how close we are to the edge, which is exactly what we need for smooth edges, outlines, glows and soft shadows, and it lets us combine shapes with plain min and max.
We will use all of that in this chapter.

6.2 The first circle: step

To turn the distance into a picture, we need "1 inside, 0 outside".
That is what step does:

step(e,x)={0x<e1x≥e

step(0.0, d) is 1 outside the circle (d≥0) and 0 inside, so we use 1.0 - step(0.0, d) and then mix between a background colour and a foreground colour (mix(a, b, t) = a(1−t)+bt, from chapter 3).
Like most GLSL functions, step also works on vectors, one component at a time.

#version 450 core

in vec2 vUv;
out vec4 out_color;

uniform float uTime;
uniform vec2 uResolution;
uniform vec2 uMouse;

void main() {
  vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;

  float d = length(p) - 0.5;          // signed distance to the circle
  float inside = 1.0 - step(0.0, d);  // 1 if d < 0, otherwise 0

  vec3 bg = vec3(0.10, 0.10, 0.12);
  vec3 fg = vec3(1.00, 0.75, 0.20);
  vec3 color = mix(bg, fg, inside);
  out_color = vec4(color, 1.0);
}

Save, press R, and you get a circle:

A yellow circle on a dark background drawn with step

It looks fine from a distance, but look closely at the edge (the left half of the picture below is the edge of this circle, enlarged 6 times).
Every pixel is either fully yellow or fully dark, so the edge is a staircase.
This is aliasing, and on a moving shape it flickers and crawls.

Left: the jagged edge from step, enlarged. Right: the smooth edge from smoothstep, enlarged

6.3 Soft edges: smoothstep

The fix is to let the pixels right at the edge be partly covered.
A pixel that is half inside the circle should get a colour half way between the two.
We already used smoothstep for the mouse circle in chapter 5; now let's see what it actually computes.

6.3.1 The formula

smoothstep(e0, e1, x) goes from 0 to 1 while x goes from e0 to e1.
First it turns x into a value t between 0 and 1 (a straight ramp), then it bends the ramp into an S-curve:

t=clamp(x−e0e1−e0,0,1)smoothstep(e0,e1,x)=t2(3−2t)

clamp(x, lo, hi) cuts a value to a range: it is min(max(x, lo), hi).
min and max return the smaller and the larger of two values (component-wise for vectors).

step jumps from 0 to 1 at 0.5. The clamp ramp is a straight line from edge0 to edge1. smoothstep is an S-curve between the same two edges

Why t2(3−2t) and not the straight ramp t?
The polynomial 3t2−2t3 is 0 at t=0 and 1 at t=1, like the ramp, but its slope (6t−6t2) is also 0 at both ends.
So the curve leaves 0 and arrives at 1 gently, without a visible kink.
For edges you can hardly see the difference, but for animation and noise (chapter 8) it matters a lot.

A worked example: smoothstep(0.25, 0.75, 0.6).

t=0.6−0.250.75−0.25=0.350.5=0.7t2(3−2t)=0.49×(3−1.4)=0.49×1.6=0.784

The GLSL specification says the result of smoothstep is undefined when e0 >= e1. You will often see smoothstep(0.01, 0.0, d) written to get a reversed curve. It happens to work on most drivers, but it is not guaranteed. Write 1.0 - smoothstep(0.0, 0.01, d) instead.

6.3.2 One pixel of blur

How wide should the soft edge be?
About one pixel.
In our coordinate the window height (uResolution.y pixels) covers 2 units, so one pixel is

px=2uResolution.y=2600≈0.0033

units in an 800×600 window.
We blend from one pixel inside the edge to one pixel outside:

void main() {
  vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;

  float d = length(p) - 0.5;
  float px = 2.0 / uResolution.y;                // size of one pixel in p units
  float inside = 1.0 - smoothstep(-px, px, d);  // soft over one pixel on each side

  vec3 bg = vec3(0.10, 0.10, 0.12);
  vec3 fg = vec3(1.00, 0.75, 0.20);
  vec3 color = mix(bg, fg, inside);
  out_color = vec4(color, 1.0);
}

The right half of the enlarged picture above is the result.
The staircase is gone; the pixels on the edge take in-between colours, and at normal size the circle looks perfectly round.

6.4 Anti-aliasing that always fits: fwidth

2.0 / uResolution.y is correct only as long as d is measured in our p units.
In the next chapter we will scale and distort coordinates, and then one pixel no longer equals 0.0033 units of d.
It would be better to ask the GPU directly: "how much does d change from this pixel to the next?"

The GPU can answer that, because it never runs one fragment shader alone.
Fragments are always processed in little 2×2 blocks of pixels, and the shaders in a block run in lockstep.
So a shader can look at the value of an expression in its neighbour:

  • dFdx(v): how much v changes from this pixel to the next one to the right (roughly v(x + 1, y) - v(x, y)).
  • dFdy(v): the same, upwards.
  • fwidth(v): abs(dFdx(v)) + abs(dFdy(v)), the total change of v across one pixel.

fwidth(d)=|∂d∂x|+|∂d∂y|

abs(x) is the absolute value |x| (component-wise for vectors).
For our circle fwidth(d) is about 0.0033 to 0.0047 (the distance changes by one pixel's worth in the direction across the edge, a bit more diagonally), whatever the window size and whatever we did to the coordinates before.
That gives a helper we will use for the rest of the series:

// coverage (0 to 1) of a shape with signed distance d, with an anti-aliased edge
float fill(float d) {
  float w = fwidth(d);
  return 1.0 - smoothstep(-w, w, d);
}

dFdx, dFdy and fwidth only exist in fragment shaders, because only fragments come in 2×2 blocks. They are available in every desktop GLSL version we use, including macOS's 4.1. Inside an if whose condition differs between the pixels of a block, their results are undefined, so call them outside of such branches (as fill does).

6.5 Seeing the distance field

A shape only uses the place where d=0, but the function gives a number for every pixel.
All those numbers together are called a distance field.
When something goes wrong with an SDF, the best debugging tool is to look at the whole field, not just the shape.
Here is a function that turns a distance into a colour (an idea popularised by Inigo Quilez, who has written more about SDFs than anyone else):

// show a distance field as colours (outside orange, inside blue, with contour lines)
vec3 showField(float d) {
  vec3 color = d > 0.0 ? vec3(0.90, 0.60, 0.30) : vec3(0.40, 0.70, 0.90);
  color *= 1.0 - exp(-6.0 * abs(d));             // darker near the edge
  color *= 0.8 + 0.2 * cos(62.83 * d);            // stripes, one every 0.1 units
  float w = fwidth(d);
  color = mix(color, vec3(1.0), 1.0 - smoothstep(0.0, 2.0 * w, abs(d)));  // the d = 0 line
  return color;
}

void main() {
  vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;
  float d = sdCircle(p, 0.5);
  out_color = vec4(showField(d), 1.0);
}

(Put sdCircle from 6.1 above showField. In GLSL, like in C, a function must be declared before it is used.)

Line by line:

  • d > 0.0 ? a : b picks orange outside and blue inside. The ?: operator works like in C.
  • exp(x) is ex. At the edge 1−e0=0, so the colour goes black; at |d|=0.1 it is 1−e−0.6≈0.45 and at |d|=0.5 about 0.95. This shows how close to the edge a pixel is.
  • cos(62.83 * d) repeats every 2π/62.83≈0.1 units of distance, so each stripe is one tenth of a unit. Multiplying by 0.8 + 0.2 * cos(...) makes the colour wave between 60% and 100% brightness.
  • The last line draws a white line where |d| is less than two pixels: the actual shape.

The distance field of a circle: blue rings inside, orange rings outside, a white circle at d = 0

The rings are perfect circles at equal spacing.
That is what an exact distance field looks like: the contour lines are evenly spaced everywhere, because the distance grows by exactly 0.1 for every 0.1 units you walk away from the edge.

6.6 The box

A circle was easy, because every point of the edge is the same distance from the centre.
A rectangle (I'll call it a box, as most shader code does) needs more thought, but the result is short and it is worth deriving once.

6.6.1 Deriving the box SDF

The box is centred at the origin.
Its half size is 𝐛=(bx,by): it reaches from −bx to bx horizontally and from −by to by vertically.

Step 1: fold everything into one quarter.
The box is symmetric, so a point (−0.8,−0.7) is exactly as far from the box as (0.8,0.7).
Taking abs(p) mirrors every point into the top-right quarter, and from now on we only need to handle that quarter.

Step 2: measure how far past each edge we are.

𝐝=abs(𝐩)−𝐛

dx is how far we are to the right of the right edge (negative if we are left of it), and dy the same for the top edge.
The two dashed lines through the box's edges split the quarter into three regions:

The box with half size b. Corner region where both d components are positive, side region where only one is, and the inside where both are negative. A point p in another quarter is mirrored by abs

  • Corner region (dx>0 and dy>0, like 𝐩1): the nearest point of the box is the corner, and the distance is the length of (dx,dy).
  • Side region (dx>0 but dy<0, like 𝐩2): the nearest point is straight to the left on the right edge, and the distance is just dx. (Above the box it is dy.)
  • Inside (both negative, like 𝐩3): we are inside, and the nearest edge is the one we are closer to. Both numbers are negative, and the closer edge is the one whose number is nearer to zero, which is the larger one: max(dx,dy).

Step 3: write all three cases as one formula.
max(d, 0.0) sets the negative components to zero.
In the corner region nothing changes, so its length is dx2+dy2.
In the side region it becomes (dx,0), with length dx.
Inside it becomes (0,0), with length 0.
So length(max(d, 0.0)) handles both outside cases and is 0 inside.
For the inside we add min(max(d.x, d.y), 0.0), which is max(dx,dy) inside and 0 everywhere outside (where at least one component is positive).

f(𝐩)=‖max(𝐝,𝟎)‖+min(max(dx,dy),0)

// box centred at the origin with half size b
float sdBox(vec2 p, vec2 b) {
  vec2 d = abs(p) - b;
  return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
}

Note max(d, 0.0): when one argument is a vector and the other a float, GLSL compares every component with the same float.

6.6.2 Checking with numbers

Take a box with 𝐛=(0.5,0.3).

Corner region, 𝐩=(0.8,0.7):

𝐝=(0.8−0.5,0.7−0.3)=(0.3,0.4)‖max(𝐝,𝟎)‖=0.09+0.16=0.5min(max(0.3,0.4),0)=0f=0.5

Side region, 𝐩=(0.8,0.1):

𝐝=(0.3,−0.2)‖max(𝐝,𝟎)‖=‖(0.3,0)‖=0.3min(max(0.3,−0.2),0)=min(0.3,0)=0f=0.3

Inside, 𝐩=(0.1,0.1):

𝐝=(−0.4,−0.2)‖max(𝐝,𝟎)‖=0min(max(−0.4,−0.2),0)=−0.2f=−0.2

The point is 0.2 below the top edge and 0.4 left of the right edge, so the nearest edge is the top one, 0.2 away. Correct.
And 𝐩=(−0.8,−0.7) becomes (0.8,0.7) after abs, so it also gets 0.5.

Swap the sdCircle call for sdBox(p, vec2(0.6, 0.3)) and look at the field:

The distance field of a box: rectangular rings inside, rings with rounded corners outside

Outside, the contour lines get round corners, because in the corner regions the distance is measured to a single point.
Inside they stay sharp rectangles.
This picture is a good sanity check: if your contour lines are not evenly spaced, your function is not a true distance.

6.7 The line segment

Lines are everywhere in 2D drawing: strokes, arrows, clock hands (next chapter), graphs.
The distance to a line segment from 𝐚 to 𝐛 is a direct use of the projection from linear algebra chapter 4.

The segment from a to b. The point p projects onto a + h(b − a), and d is the perpendicular distance. A point p′ beyond b gets h clamped to 1

  1. Measure everything from 𝐚: 𝐩−𝐚 and 𝐛−𝐚.
  2. Project 𝐩−𝐚 onto the segment direction. The dot product divided by the squared length gives how far along the segment the closest point is, as a fraction h: 0 at 𝐚, 1 at 𝐛.
  3. Clamp h to [0,1], because the segment ends. A point beyond 𝐛 (like 𝐩′) is closest to 𝐛 itself.
  4. The distance is the length from 𝐩 to that closest point.

h=clamp((𝐩−𝐚)⋅(𝐛−𝐚)(𝐛−𝐚)⋅(𝐛−𝐚),0,1),f=‖(𝐩−𝐚)−h(𝐛−𝐚)‖

A worked example with 𝐚=(−0.5,0), 𝐛=(0.5,0) and 𝐩=(0.2,0.3):

𝐩−𝐚=(0.2,0.3)−(−0.5,0)=(0.7,0.3)𝐛−𝐚=(1,0)h=0.7×1+0.3×01×1+0×0=0.7f=‖(0.7,0.3)−0.7×(1,0)‖=‖(0,0.3)‖=0.3

And 𝐩=(0.9,0.3) gives h=1.4 before clamping, so h=1 and f=‖(1.4,0.3)−(1,0)‖=‖(0.4,0.3)‖=0.5: the distance to the end point 𝐛.

dot(a, b) is the dot product axbx+ayby (linear algebra chapter 4).

// distance to the segment from a to b
float sdSegment(vec2 p, vec2 a, vec2 b) {
  vec2 pa = p - a;
  vec2 ba = b - a;
  float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
  return length(pa - ba * h);
}

This is an unsigned distance: it is never negative, because a segment has no inside.
To give it thickness, subtract a radius: sdSegment(p, a, b) - 0.1 is a capsule, a thick line with round ends.

Let's make one end follow the mouse.
uMouse is in pixels, so we convert it exactly like gl_FragCoord:

void main() {
  vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;
  vec2 m = (2.0 * uMouse - uResolution) / uResolution.y;  // the mouse in the same coordinates

  float d = sdSegment(p, vec2(-0.5, -0.2), m) - 0.1;  // a line 0.1 thick (a capsule)
  out_color = vec4(showField(d), 1.0);
}

The distance field of a capsule from the lower left to the mouse position at the upper right

Move the mouse around.
The capsule stretches to follow it, and the field stays evenly spaced.

6.8 Modifying shapes: rounding and outlines

Because the SDF tells us the distance to the edge, we can move the edge by changing the distance.
Two tiny tricks give us a lot of new shapes.

Rounding: subtracting a number r from any distance makes the shape grow by r in every direction, and all its corners become round with radius r (look again at the outside contour lines of the box: each one is the box grown by some amount, with round corners).
To get a rounded box of the original size, shrink the box first and then grow it:

// rounded box: make a smaller box, then subtract r from the distance
float sdRoundBox(vec2 p, vec2 b, float r) {
  return sdBox(p, b - r) - r;
}

Outlines: abs(d) is the distance to the edge without the sign, so it is small on both sides of the edge.
abs(d) - w is negative only in a band of width 2w around the edge: an outline, or a ring when we use it on a circle.
This works on any SDF, and even on the result of another abs: abs(abs(d) - 0.1) - 0.02 gives two thin rings.

Here are all our shapes together, each moved to its own place by subtracting a position from p (the next chapter explains why subtracting moves the shape forward).
Combining them with min puts them all in the same picture; we will see why in the next section.

void main() {
  vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;

  vec3 color = vec3(0.10, 0.10, 0.12);
  vec3 ink = vec3(1.00, 0.75, 0.20);

  // top row
  float d1 = sdCircle(p - vec2(-0.85, 0.45), 0.3);
  float d2 = sdBox(p - vec2(0.0, 0.45), vec2(0.3, 0.2));
  float d3 = sdRoundBox(p - vec2(0.85, 0.45), vec2(0.3, 0.2), 0.1);
  // bottom row
  float d4 = sdSegment(p, vec2(-1.1, -0.65), vec2(-0.6, -0.25)) - 0.06;  // capsule
  float d5 = abs(sdCircle(p - vec2(0.0, -0.45), 0.25)) - 0.04;          // ring
  float d6 = abs(sdRoundBox(p - vec2(0.85, -0.45), vec2(0.3, 0.2), 0.1)) - 0.02;  // outline

  float d = min(min(min(d1, d2), min(d3, d4)), min(d5, d6));
  color = mix(color, ink, fill(d));
  out_color = vec4(color, 1.0);
}

Six shapes: circle, box, rounded box, capsule, ring and rounded box outline

6.9 Combining shapes

Two SDFs a and b can be combined like sets:

Operation Formula Meaning
Union min(a, b) inside either shape
Intersection max(a, b) inside both shapes
Subtraction max(a, -b) inside a but not inside b

Why does this work?
A point is inside the union if it is inside at least one shape, that is, if at least one of a, b is negative, and that is exactly when the smaller one is negative.
A point is inside the intersection only if both are negative, which is when the larger one is negative.
For subtraction we flip the sign of b: −b is the SDF of "everything outside b", and we intersect a with that.

  // three circle and box pairs: left = union, middle = intersection, right = subtraction
  vec2 c0 = vec2(-0.85, 0.0), c1 = vec2(0.0, 0.0), c2 = vec2(0.85, 0.0);
  vec2 ca = vec2(-0.1, 0.06), cb = vec2(0.1, -0.06);
  float a0 = sdCircle(p - c0 - ca, 0.26), b0 = sdBox(p - c0 - cb, vec2(0.2));
  float a1 = sdCircle(p - c1 - ca, 0.26), b1 = sdBox(p - c1 - cb, vec2(0.2));
  float a2 = sdCircle(p - c2 - ca, 0.26), b2 = sdBox(p - c2 - cb, vec2(0.2));

  float d = min(min(
    min(a0, b0),     // union
    max(a1, b1)),    // intersection
    max(a2, -b2));   // subtraction (a minus b)

Left: union of a circle and a box. Middle: their intersection. Right: the circle minus the box. Grey lines show the original shapes

(The grey lines are the two original shapes, drawn with an outline helper: 1.0 - smoothstep(0.0, 1.5 * fwidth(d), abs(d)).)

One honest warning.
The union is an exact distance outside the shapes, but the intersection and subtraction are not always exact: they can report a distance that is too small (never too large).
For drawing in 2D this does not matter at all, since the edge is in the right place.
In chapter 14 (raymarching) we will rely on distances being "never too large", and these operations keep that promise.

6.10 Smooth union

min glues shapes together with a sharp crease where they meet.
Organic shapes (blobs, clay, metaballs, a character's ears joining its head) need a soft join instead.
The trick is a smooth minimum: a function that behaves like min when the two values are far apart, but rounds off the corner when they are close.

6.10.1 The formula

The popular polynomial version:

h=clamp(12+b−a2k,0,1)smin(a,b,k)=mix(b,a,h)−kh(1−h)

// smooth union (k is the size of the blended region)
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);
}

How it works:

  • If a is smaller than b by k or more, then b−a2k≥12, so h=1. mix(b, a, 1) is a, and k⋅1⋅0=0. Result: exactly a, the same as min.
  • If b is smaller by k or more, h=0 and the result is exactly b.
  • In between, h slides from 0 to 1, mix blends the two distances, and the extra term kh(1−h) pulls the result down a little. It is largest when a=b (h=12), where it subtracts k4.

Pulling the distance down means the surface moves outwards there, so the gap between the shapes fills in.
Because h(1−h) is a parabola that is 0 at both ends, the blend joins min without a kink.

A cross-section of two circles. The red min has a sharp peak where the two distances meet; the yellow smin rounds it off and lies k/4 lower at the peak

A worked example with k=0.3, a=0.1, b=0.2:

h=clamp(0.5+0.2−0.10.6,0,1)=0.5+0.16‾=0.6‾mix(0.2,0.1,0.6‾)=0.2+(0.1−0.2)×0.6‾=0.13‾kh(1−h)=0.3×0.6‾×0.3‾=0.06‾smin=0.13‾−0.06‾=0.06‾

min(0.1, 0.2) would be 0.1; the smooth version is 0.067, a bit further "inside".
With a=0.1 and b=0.5 the difference 0.4 is more than k, so h=1 and the result is exactly 0.1.

6.10.2 Trying it out

Two circles of radius 0.15 with a small gap between them, joined with min, with smin and k=0.1, and with smin and k=0.3:

  // three pairs of circles: left = min, middle = smin (k = 0.1), right = smin (k = 0.3)
  vec2 c0 = vec2(-0.85, 0.0), c1 = vec2(0.0, 0.0), c2 = vec2(0.85, 0.0);
  vec2 o = vec2(0.17, 0.0);
  float d0 = min(sdCircle(p - c0 + o, 0.15), sdCircle(p - c0 - o, 0.15));
  float d1 = smin(sdCircle(p - c1 + o, 0.15), sdCircle(p - c1 - o, 0.15), 0.1);
  float d2 = smin(sdCircle(p - c2 + o, 0.15), sdCircle(p - c2 - o, 0.15), 0.3);
  float d = min(min(d0, d1), d2);

Left: two separate circles. Middle: a thin neck joins them. Right: they melt into one peanut shape

The gap between the circles is 0.04, so with min they stay apart.
With k=0.1 they reach towards each other and form a neck; with k=0.3 they melt into one shape.
It looks best in motion.
Here two circles move apart and together with uTime; the grey lines are the circles themselves:

  float x = 0.38 + 0.22 * cos(uTime * 2.0944);  // one cycle every 3 seconds
  float a = sdCircle(p - vec2(-x, 0.0), 0.3);
  float b = sdCircle(p - vec2(x, 0.0), 0.3);
  float d = smin(a, b, 0.3);

Two circles joined by smin, close together

2.0944≈2π3, so the cosine completes one cycle every 3 seconds.

6.11 Putting it together: a small character

Now we have enough pieces to draw something real.
This is the final playground.glsl of this chapter.
Every part is a shape from this chapter, and the colours are painted one layer over the other, from back to front, like a painter would.

#version 450 core

in vec2 vUv;
out vec4 out_color;

uniform float uTime;       // seconds since start
uniform vec2 uResolution;  // window size in pixels
uniform vec2 uMouse;       // mouse position in pixels, origin at the bottom left

// ---- chapter 6: signed distance functions (negative inside, 0 on the edge, positive outside) ----

// circle centred at the origin with radius r
float sdCircle(vec2 p, float r) {
  return length(p) - r;
}

// box centred at the origin with half size b
float sdBox(vec2 p, vec2 b) {
  vec2 d = abs(p) - b;
  return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
}

// distance to the segment from a to b
float sdSegment(vec2 p, vec2 a, vec2 b) {
  vec2 pa = p - a;
  vec2 ba = b - a;
  float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
  return length(pa - ba * h);
}

// rounded box: make a smaller box, then subtract r from the distance
float sdRoundBox(vec2 p, vec2 b, float r) {
  return sdBox(p, b - r) - r;
}

// coverage (0 to 1) of a shape with signed distance d, with an anti-aliased edge
float fill(float d) {
  float w = fwidth(d);
  return 1.0 - smoothstep(-w, w, d);
}

// smooth union (k is the size of the blended region)
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);
}

// head: a circle with two ears smoothly attached
float sdHead(vec2 p) {
  float head = sdCircle(p, 0.6);
  float earL = sdCircle(p - vec2(-0.45, 0.5), 0.17);
  float earR = sdCircle(p - vec2(0.45, 0.5), 0.17);
  return smin(head, min(earL, earR), 0.12);
}

// paint a shape over the current colour
vec3 paint(vec3 base, vec3 ink, float d) {
  return mix(base, ink, fill(d));
}

void main() {
  // origin in the centre, y from -1 to 1 (chapter 5)
  vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;
  vec2 m = (2.0 * uMouse - uResolution) / uResolution.y;  // the mouse in the same coordinates

  // background: vertical gradient
  vec3 color = mix(vec3(0.16, 0.12, 0.22), vec3(0.08, 0.06, 0.10), p.y * 0.5 + 0.5);

  // shadow: the same distance function, shifted and blurred
  float shadow = sdHead(p - vec2(0.05, -0.06));
  color *= 1.0 - 0.5 * (1.0 - smoothstep(-0.05, 0.12, shadow));

  // head fill and outline
  float head = sdHead(p);
  color = paint(color, vec3(1.00, 0.80, 0.30), head);
  color = paint(color, vec3(0.35, 0.18, 0.10), abs(head) - 0.012);

  // cheeks: circles with a very wide soft edge
  float cheek = min(sdCircle(p - vec2(-0.36, -0.12), 0.09),
                    sdCircle(p - vec2(0.36, -0.12), 0.09));
  color = mix(color, vec3(1.0, 0.50, 0.50), 0.6 * (1.0 - smoothstep(-0.04, 0.04, cheek)));

  // eyes: vertical capsules
  vec2 eyeL = vec2(-0.2, 0.12);
  vec2 eyeR = vec2(0.2, 0.12);
  float eyes = min(sdSegment(p, eyeL - vec2(0.0, 0.06), eyeL + vec2(0.0, 0.06)),
                   sdSegment(p, eyeR - vec2(0.0, 0.06), eyeR + vec2(0.0, 0.06))) - 0.075;
  color = paint(color, vec3(1.0), eyes);
  color = paint(color, vec3(0.35, 0.18, 0.10), abs(eyes) - 0.01);

  // pupils: look towards the mouse (limit the length so they stay inside the eyes)
  vec2 look = m - (eyeL + eyeR) * 0.5;
  look = look / max(length(look), 1.0) * 0.05;
  float pupils = min(sdCircle(p - eyeL - look, 0.04), sdCircle(p - eyeR - look, 0.04));
  color = paint(color, vec3(0.12, 0.08, 0.06), pupils);

  // mouth: the lower half of a ring (a ring intersected with a half-plane)
  float ring = abs(sdCircle(p - vec2(0.0, 0.02), 0.3)) - 0.022;
  float below = p.y + 0.12;  // negative where y < -0.12
  color = paint(color, vec3(0.35, 0.18, 0.10), max(ring, below));

  out_color = vec4(color, 1.0);
}

A yellow bear-like face with round ears, white eyes looking to the upper right, pink cheeks and a smile, with a soft shadow

What each part teaches:

  • Head: one circle plus two ear circles, joined with smin, so the ears grow out of the head instead of being stuck on. Putting the shape in its own function sdHead lets us use it twice.
  • Shadow: the same sdHead, moved a little to the lower right, with a very wide smoothstep (from −0.05 to 0.12 instead of one pixel). A wide edge is a blur, and a blurred dark copy of a shape is a soft shadow. With bitmaps this needs a blur pass; with an SDF it is one line.
  • Outline: abs(head) - 0.012 is the outline trick from 6.8, painted after the fill.
  • Cheeks: again a wide smoothstep, mixed only 60% so the yellow shows through.
  • Eyes: capsules (6.7) standing upright.
  • Pupils: the direction from between the eyes to the mouse. look / max(length(look), 1.0) keeps short vectors as they are and shortens long ones to length 1, so the pupils move at most 0.05 and never leave the eyes. (Why not normalize(look)? normalize divides by the length, and when the mouse is exactly between the eyes the length is 0. max avoids the division by zero.)
  • Mouth: a ring intersected (max) with the half-plane p.y + 0.12. A half-plane is the simplest SDF of all: the signed distance to the horizontal line y=−0.12, negative below it. The intersection keeps the part of the ring below that line.

Move the mouse and the eyes follow it.

To see what the shader "sees", replace the body of main with out_color = vec4(showField(sdHead(p)), 1.0); (with showField from 6.5 added to the file):

The distance field of the head: the contour lines bend smoothly around the ears

Notice how the contours near the ears are smooth: no creases, thanks to smin.

6.12 New GLSL functions in this chapter

Function What it computes
length(v) vx2+vy2(+vz2+vw2)
dot(a, b) axbx+ayby(+…)
abs(x) x if x≥0, otherwise −x (per component)
min(a, b), max(a, b) the smaller, the larger value (per component; b may be a float)
clamp(x, lo, hi) min(max(x, lo), hi)
step(e, x) 0 if x<e, otherwise 1
smoothstep(e0, e1, x) t2(3−2t) with t=clamp((x−e0)/(e1−e0),0,1)
exp(x) ex
dFdx(v), dFdy(v) change of v to the neighbouring pixel in x or y (fragment shaders only)
fwidth(v) abs(dFdx(v)) + abs(dFdy(v))

6.13 SDFs in real games and engines

Distance functions are not just a demo-scene trick; they are all over real software.

  • Text: in 2007 Valve published a short paper by Chris Green on rendering text and decals from a small texture that stores a distance field instead of colours. The shader does exactly what our fill does: smoothstep around the 0.5 level. Text stays sharp at any size, and outlines, glows and drop shadows come almost free. Unity's TextMesh Pro and many other UI systems use this. A refinement called multi-channel SDF (MSDF) keeps sharp corners.
  • UI: rounded buttons, progress rings, health bars, icons and selection outlines are often drawn with exactly the sdRoundBox, abs(d) - w and fill you wrote here, because they scale to any resolution and need no textures.
  • Decals and effects: shockwave rings, target markers on the ground, area-of-effect circles in strategy games and MOBAs are usually a quad with a circle or ring SDF in its fragment shader.
  • 3D: Unreal Engine stores a 3D distance field for each mesh and uses it for soft shadows and ambient occlusion. Media Molecule's Dreams on PS4 builds its whole sculpting system on SDFs combined with smooth unions. And raymarching (chapter 14) draws complete 3D scenes from 3D versions of the functions in this chapter.

6.14 Summary

  • A signed distance function returns the distance to a shape's edge: negative inside, 0 on the edge, positive outside.
  • Circle: length(p) - r. Box: fold with abs, then length(max(d, 0.0)) + min(max(d.x, d.y), 0.0). Segment: projection with dot, clamped to the segment.
  • step gives hard, aliased edges; smoothstep with a width of about one pixel gives smooth ones. fwidth measures that width for you, whatever you did to the coordinates.
  • d - r rounds and grows a shape; abs(d) - w turns it into an outline.
  • Union min, intersection max, subtraction max(a, -b); smin joins shapes smoothly, subtracting at most k4.
  • Visualise the whole field (showField) when debugging: evenly spaced contour lines mean a correct distance.
  • A wide smoothstep on a shifted SDF gives soft shadows and glows for free.

6.15 Challenges

  1. ★ Compute the signed distance of the points (0.9,0.0), (0.0,0.0) and (0.8,0.6) to a box with half size 𝐛=(0.5,0.2). (You should get one positive value from a side region, one negative value and one value from a corner region.)
  2. ★ Compute smoothstep(0.0, 2.0, 0.5) and smin(0.3, 0.3, 0.4) by hand. Check your answers by drawing them as colours in the playground.
  3. ★★ Draw a target: five concentric rings in alternating red and white, using only one sdCircle and fract on the distance. The rings should stay perfectly smooth when you resize the window.
  4. ★★ Draw an equilateral triangle by intersecting three half-planes (a half-plane is dot(p, n) - c for a unit normal n). Then try to round its corners with - r. The triangle grows by r, but unlike the rounded box of 6.8 its corners stay sharp. Explain why, using the warning about max at the end of 6.9.
  5. ★★ Give the character from 6.11 a blink: every 3 seconds, squash the eye capsules to a line for 0.15 seconds (hint: make the capsule's half height depend on fract(uTime / 3.0)). The pupils should disappear while the eyes are closed.
  6. ★★ Make the mouse cursor a soft light: draw a glow around the head whose strength is exp(-8.0 * max(head, 0.0)) and whose brightness depends on how close the mouse is to the head. Outside the head the glow should fade smoothly to the background.
  7. ★★★ The intersection max(a, b) of two circles is not an exact distance field outside the shape. Draw showField(max(a, b)) for two overlapping circles and find where the contour lines stop being evenly spaced. Explain why max reports a distance that is too small there.

Download the diff

ファイル: a/shader/playground.glsl | b/shader/playground.glsl

前新
@@ -7,16 +7,97 @@ uniform float uTime; // 起動してからの秒数
7 uniform vec2 uResolution; // 画面の大きさ(ピクセル) 7 uniform vec2 uResolution; // 画面の大きさ(ピクセル)
8 uniform vec2 uMouse; // マウスの位置(ピクセル、左下が原点) 8 uniform vec2 uMouse; // マウスの位置(ピクセル、左下が原点)
9   9  
    10 // ---- 第6章:符号付き距離関数(負=内側、0=境界、正=外側) ----
    11  
    12 // 円(中心が原点、半径r)
    13 float sdCircle(vec2 p, float r) {
    14 return length(p) - r;
    15 }
    16  
    17 // 箱(中心が原点、半分の大きさがb)
    18 float sdBox(vec2 p, vec2 b) {
    19 vec2 d = abs(p) - b;
    20 return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
    21 }
    22  
    23 // 線分abまでの距離
    24 float sdSegment(vec2 p, vec2 a, vec2 b) {
    25 vec2 pa = p - a;
    26 vec2 ba = b - a;
    27 float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
    28 return length(pa - ba * h);
    29 }
    30  
    31 // 角の丸い箱:小さい箱を作ってから、距離からrを引く
    32 float sdRoundBox(vec2 p, vec2 b, float r) {
    33 return sdBox(p, b - r) - r;
    34 }
    35  
    36 // 符号付き距離から、アンチエイリアス付きの塗り(0〜1)を作る
    37 float fill(float d) {
    38 float w = fwidth(d);
    39 return 1.0 - smoothstep(-w, w, d);
    40 }
    41  
    42 // 滑らかな和集合(kは繋がる部分の大きさ)
    43 float smin(float a, float b, float k) {
    44 float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);
    45 return mix(b, a, h) - k * h * (1.0 - h);
    46 }
    47  
    48 // 頭:円に2つの耳を滑らかにくっつける
    49 float sdHead(vec2 p) {
    50 float head = sdCircle(p, 0.6);
    51 float earL = sdCircle(p - vec2(-0.45, 0.5), 0.17);
    52 float earR = sdCircle(p - vec2(0.45, 0.5), 0.17);
    53 return smin(head, min(earL, earR), 0.12);
    54 }
    55  
    56 // 図形を色で塗り重ねる
    57 vec3 paint(vec3 base, vec3 ink, float d) {
    58 return mix(base, ink, fill(d));
    59 }
    60  
10 void main() { 61 void main() {
11 // ピクセル座標を0〜1に正規化 62 // 中心が原点、縦が-1〜1になる座標(第5章)
12 vec2 uv = gl_FragCoord.xy / uResolution; 63 vec2 p = (2.0 * gl_FragCoord.xy - uResolution) / uResolution.y;
    64 vec2 m = (2.0 * uMouse - uResolution) / uResolution.y; // マウスも同じ座標に
    65  
    66 // 背景:縦のグラデーション
    67 vec3 color = mix(vec3(0.16, 0.12, 0.22), vec3(0.08, 0.06, 0.10), p.y * 0.5 + 0.5);
    68  
    69 // 影:同じ距離関数をずらして、ぼかして使う
    70 float shadow = sdHead(p - vec2(0.05, -0.06));
    71 color *= 1.0 - 0.5 * (1.0 - smoothstep(-0.05, 0.12, shadow));
    72  
    73 // 頭の塗りと輪郭
    74 float head = sdHead(p);
    75 color = paint(color, vec3(1.00, 0.80, 0.30), head);
    76 color = paint(color, vec3(0.35, 0.18, 0.10), abs(head) - 0.012);
    77  
    78 // ほっぺ:境界を広くぼかした円
    79 float cheek = min(sdCircle(p - vec2(-0.36, -0.12), 0.09),
    80 sdCircle(p - vec2(0.36, -0.12), 0.09));
    81 color = mix(color, vec3(1.0, 0.50, 0.50), 0.6 * (1.0 - smoothstep(-0.04, 0.04, cheek)));
    82  
    83 // 目:縦のカプセル
    84 vec2 eyeL = vec2(-0.2, 0.12);
    85 vec2 eyeR = vec2(0.2, 0.12);
    86 float eyes = min(sdSegment(p, eyeL - vec2(0.0, 0.06), eyeL + vec2(0.0, 0.06)),
    87 sdSegment(p, eyeR - vec2(0.0, 0.06), eyeR + vec2(0.0, 0.06))) - 0.075;
    88 color = paint(color, vec3(1.0), eyes);
    89 color = paint(color, vec3(0.35, 0.18, 0.10), abs(eyes) - 0.01);
13   90  
14 // 時間で動くグラデーション 91 // 瞳:マウスの方を見る(目の中から出ない様に長さを制限)
15 vec3 color = 0.5 + 0.5 * cos(uTime + uv.xyx + vec3(0.0, 2.0, 4.0)); 92 vec2 look = m - (eyeL + eyeR) * 0.5;
    93 look = look / max(length(look), 1.0) * 0.05;
    94 float pupils = min(sdCircle(p - eyeL - look, 0.04), sdCircle(p - eyeR - look, 0.04));
    95 color = paint(color, vec3(0.12, 0.08, 0.06), pupils);
16   96  
17 // マウスの周りに白い円 97 // 口:リングの下半分(リングと半平面の積集合)
18 float d = length(gl_FragCoord.xy - uMouse); 98 float ring = abs(sdCircle(p - vec2(0.0, 0.02), 0.3)) - 0.022;
19 color = mix(color, vec3(1.0), 1.0 - smoothstep(18.0, 20.0, d)); 99 float below = p.y + 0.12; // y < -0.12 の部分が負
    100 color = paint(color, vec3(0.35, 0.18, 0.10), max(ring, below));
20   101  
21 out_color = vec4(color, 1.0); 102 out_color = vec4(color, 1.0);
22 } 103 }


コメント(0)

まだコメントはありません。