LearnPatterns and noise
Lesson 16 of 30 · 55 min
Drawing with distance (2D SDF)
Draw with signed distance functions: smooth unions, outlines and shadows
In this lesson you will
- Understand signed distance (positive outside, negative inside, zero on the edge) and visualize it with contour lines
- Explain how
sdBoxandsdSegmentwork, and use contours to see why rounding, outlines, union, intersection and subtraction work — and how exact they are - Combine shapes with union, intersection and subtraction, merge them smoothly with
smin, and build metaballs - Get a smooth one-pixel edge, an outline, a shadow and a glow, all from one distance
01What signed distance means
In Circles and distance we used sdCircle as a distance that goes negative inside, and built a mask (a number that is 1 inside a shape and 0 outside) with 1.0 - smoothstep(-px, px, d). Combining shapes added sdBox and sdSegment, along with rounding, outlines, union, intersection and subtraction. This lesson pins down the idea underneath all of that — signed distance — and then moves on: a way to check by eye whether a distance is right, smooth ways to join shapes, and shadows and light made from distance. The 3D lessons later use exactly the same idea.
Let's define it properly. A signed distance function (SDF) takes any point p and returns how far it is from the nearest edge of a shape. The twist is the sign: the number is positive outside and negative inside. Right on the edge it is exactly 0.
sdCircle(p, 0.5)atp = (1.0, 0.0)…1.0 - 0.5 = 0.5: outside, 0.5 from the edge- At
p = (0.5, 0.0)…0.0: right on the edge - At
p = (0.2, 0.0)…-0.3: inside, 0.3 from the edge - At the center
(0.0, 0.0)…-0.5: the deepest point
The sign means one number tells you two things: the sign says inside or outside, and the size says how far from the edge. Inside-or-outside gives you the mask (the fill); distance from the edge gives you outlines, shadows and glows. In the playground below, outside is orange, inside is blue, and both get darker near the edge.
1
2
3
4
5
6
7
8
9
d > 0.0 to d > 0.2 and the color boundary moves to 0.2 outside the edge. Change -5.0 to -20.0 to keep the darkness close to the edgeexp(-5.0 * abs(d)) is 1 on the edge (where d is 0) and fades toward 0 as you move away. The 1.0 - flips it, so the edge is black and it brightens with distance. At 0.1 from the edge you get 1.0 - exp(-0.5), about 0.39; at 0.5 away, about 0.92.
02Seeing distance with contour lines
To read the distance more clearly, let's add lines like the contour lines on a map. cos(120.0 * d) completes one cycle every time d grows by 2π ÷ 120, about 0.052, so light and dark lines repeat every 0.052 units of distance. On the edge itself (d = 0) we draw a white line.
1
2
3
4
5
6
7
8
9
10
11
12
13
120.0 to 40.0 to spread the lines out. What do the contours look like if you replace sdCircle(…, 0.5) with abs(p.y) - 0.3 (a horizontal band)?Notice that the contour lines are evenly spaced everywhere and run parallel to the edge, like ripples around a stone dropped in a pond. That is the sign of a function returning a true distance. Turn it around: wherever the lines bunch up or spread apart, the function is not returning an exact distance. We will see examples later in this lesson.
Tip
This view is handy for checking whether a distance function you wrote behaves correctly. We use distanceColor in many playgrounds in this lesson.
03How the box and segment work
The circle's distance, length(p) - r, was simple. The box's, sdBox, takes a bit more. Let's read it line by line. b is half the width and height of the box.
1
2
3
4
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);
}
abs(p)… the box is symmetric, so this folds points on the left or bottom into the upper right. Now we only have to think about one cornerd = abs(p) - b… how far past the right edge and the top edge we are. A positived.xmeans outside the right edge; negative means insidelength(max(d, 0.0))… the outside distance. Zero out the negative parts, then measure the length. Past only the right edge it givesd.x, past only the top it givesd.y, and diagonally out it gives the distance to the corner — three cases in one expressionmin(max(d.x, d.y), 0.0)… the inside distance. Inside, bothd.xandd.yare negative, and the one closer to 0 (max) belongs to the nearest edge. Outside,min(…, 0.0)makes it 0 so it stays out of the way
Let's check with numbers, using b = (0.6, 0.3). At p = (1.0, 0.0), d = (0.4, -0.3) and the outside distance is 0.4. At p = (0.9, 0.7), d = (0.3, 0.4), and the distance to the corner is length = 0.5. At p = (0.2, 0.1), d = (-0.4, -0.2), giving -0.2 inside (0.2 from the top edge).
In the playground below, a yellow circle is drawn around the cursor position (mouse), with the distance |d| at that spot as its radius. mouse is the cursor position in the same coordinates as p (more in Touch and response; before you hover, it is (0, 0)). Check that the circle always just touches the box's edge at one point. That is what "distance to the nearest edge" means.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
vec2(0.6, 0.3) to vec2(0.3) for a squareLook at the contour shapes too. Outside, the lines round off at the corners (because there we measure the distance to the corner point). Inside, they bend sharply along diagonal creases running from the corners toward the center. That "rounded outside" is the secret behind rounded corners, coming up next.
The segment distance sdSegment(p, a, b) finds the point on the line from a to b closest to p and measures the length to it. h is the position along the line: 0 at a, 1 at b. dot(pa, ba) / dot(ba, ba) projects p onto the line, and clamp keeps it within 0–1 so it never runs past the ends. A segment has no thickness and so no inside, but subtracting r gives it thickness, turning it into a capsule with a proper inside.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 0.15 to see the plain segment distance (positive everywhere, so all orange). Change it to - 0.3 for a fatter capsule04Review: rounding, outlines and combining
Let's revisit what we built in Combining shapes — the rounded box sdBox(p, b - r) - r, the outline abs(d) - w, and union min, intersection max and subtraction max(a, -b) — through contour lines. The formulas are the same, but contours show why they work and how exact they are.
d - r is 0 on the contour line r outside the old edge. As we just saw, the box's outside contours have rounded corners, so the pushed-out shape does too — that's why rounding works. abs(d) turns both sides into the distance to the edge line, so abs(d) - w is a band of thickness 2w centered on the edge. Both results are still distances, so their contours stay clean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// from // d = abs(d) - 0.05; to hollow it into a frame; try the next line too for a double frame. Change vec2(0.6, 0.3) - r to vec2(0.6, 0.3) to see the box grow as it roundsThe sign explains union, intersection and subtraction. min(a, b) is negative when inside either shape; max(a, b) only when inside both. -b swaps the inside and outside of b, so max(a, -b) means "inside a and outside b": b cut out of a.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
The edge (the white line) is right every time, but look closely at the contours: for the union they kink and go uneven inside the shape, and for intersection and subtraction outside. There the value is not the true distance but something smaller than or equal to it. That is fine for fills and thin outlines. Thick outlines or glows can come out slightly distorted, so check with contours if something looks off. The fact that the error only ever makes the value smaller turns out to matter a lot for Raymarching in 3D.
05Joining smoothly with smin
Joining with min leaves a sharp valley where two shapes meet. When you want the seam filled in smoothly, like clay or droplets, use smin, the smooth minimum. We use exactly the same function in 3D.
1
2
3
4
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);
}
kis the width of the blend. Wherever the two distances differ bykor more, the result is justminhsays how much ofato use, from 0 to 1: 1 (alla) ifais smaller bykor more, 0 (allb) ifbis, and 0.5 if they are equal- k * h * (1.0 - h)lowers the value around the seam a little. Lower means closer to inside, so the gap between the shapes fills in. The largest dip is ath= 0.5:k * 0.25
In numbers: with a = b = 0.1 and k = 0.2, h is 0.5 and the result is 0.1 - 0.2 × 0.25 = 0.05. A spot in the gap, 0.1 from both shapes, now counts as only 0.05 away, so the shapes swell slightly and join.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
k (0.25) to 0.5 and the circles reach for each other even from afar. Enable // d = min(a, b); to compareWatch out
Setting k to 0.0 makes (b - a) / k a division by zero, and the result breaks. For a sharp seam, use a tiny k such as 0.001, or go back to min.
Tip
-smin(-a, -b, k) gives a smooth max (intersection), and -smin(-a, b, k) a smooth subtraction. They swap inside and outside, apply smin, and swap back.
06Metaballs
Join many circles with smin and you get metaballs: blobs that merge and split like beads of mercury or a lava lamp. A loop adds one circle at a time, joining each with smin. The starting d = 8.0 is a big number meaning "far from everything"; smin with the first circle simply leaves that circle's distance.
From here on, instead of visualizing the distance, we color it as artwork. Inside gets a gradient based on d, and outside gets a little light spreading from the edge. The fill uses the same mask as in Circles and distance: 1.0 - smoothstep(-px, px, d).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
0.35 in smin(…, 0.35) to 0.05 and the balls barely merge. Change i < 7 to i < 12 for more ballsThe inner gradient uses clamp(-d * 5.0, 0.0, 1.0), which is 0 on the edge and 1 at 0.2 inside it. When balls merge, the joined area is farther from the edge too, so the color deepens there and they read as one body.
07Repeating shapes
Combine distance with the grid from Repetition and tiles, and a single distance function fills the screen with a pattern. fract(g) - 0.5 puts the origin at the middle of each cell, and we measure the shape's distance in there.
One thing to watch: with g = p * 5.0, the cell coordinates are scaled up 5×, so any distance measured inside them is 5× too large. Just like scaling in Moving space, divide by 5.0 at the end to get back to p units. Then edges and glows built with px keep the right width however fine the repetition is.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
d /= n; and the edges turn jagged while the glow shrinks (the distance stays 5× too big). Set n to 8.0 and the edges stay just as crispWatch out
Keep each shape small enough to stay inside its cell. A cell only knows about its own shape, so anything that sticks out is not drawn in the neighboring cell and gets cut off in a straight line. It's the same reason we kept the points inside their cells in Cellular patterns. If a shape must stick out, check the neighboring cells too, as in that lesson's 3×3 search, and take the min of their distances.
08Fill, outline, shadow and glow from one distance
The best thing about drawing with distance is that one distance gives you many effects. Put your shape in a function such as float scene(vec2 p), and all of these come from it:
- Fill … the familiar mask
1.0 - smoothstep(-px, px, d), switching smoothly within one pixel either side of the edge - Outline … paint the slightly fattened
d - win another color first for a border of widthw; for just a line, useabs(d) - w - Shadow … call
scene(p - offset)again at a shifted position, and use a blurred fill of it as darkness - Glow … add brightness that fades away from the edge outside, such as
exp(-k * d)
Let's take another look at the mask's px = 2.0 / resolution.y. p.y runs from -1 to 1 bottom to top, so a span of 2 split across resolution.y pixels is the size of one pixel. On a screen 500 pixels tall, px is 0.004. The mask softens just the pixel or so along the edge whatever the size of the shape, because d is a true distance in p units. That is also why we divided the distance back down in the repeating pattern.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
0.04 in d - 0.04 to 0.08 for a thicker border. Change the shadow's vec2(0.06, -0.08 - bob) and the light seems to come from another directionThe shadow is just the distance measured again at a shifted position. smoothstep(-0.05, 0.08, ds) is wide, so the shadow comes out soft and blurry. For the border, paint the shape fattened by 0.04 in white first, then the original shape in color on top, so only an outer ring of white remains. Everything uses the same scene function, so change the shape and the shadow, border and glow all follow automatically.
Tip
When a scale or distortion leaves the distance impossible to correct, use fwidth(d) instead of px. fwidth(d) returns how much d changes from one pixel to the next, so 1.0 - smoothstep(-fwidth(d), fwidth(d), d) also gives a one-pixel edge.
09Exercises
For every exercise, it helps to build the shape's distance first, then add fill, border, shadow and light. If you are unsure about a shape, check its contours with distanceColor.
A pill-shaped button
Turn the sharp box into a pill-shaped button whose ends are fully round (corner radius equal to half the height). Add a darker border and a soft shadow offset below it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
A fluffy cloud
Join the lumpy circles (now merged with min) smoothly with smin to make a cloud with a flat bottom. Draw a white cloud with a faint shadow over a sky gradient.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
A waxing and waning moon
A round moon hangs in the night sky. Subtract a second circle that slides sideways, so the moon waxes and wanes into a crescent. Give it a soft halo of light too.
1
2
3
4
5
6
7
8
9
10
10Recap
- An SDF returns the distance to the edge: positive outside, negative inside, zero on the edge. Evenly spaced contours mean an exact distance
sdBoxfolds space into one corner withabs, then measures the outside and inside distances separately and adds themd - rrounds andabs(d) - woutlines. Union, intersection and subtraction come out smaller than the true distance on one side- Union is
min, intersectionmax, subtractionmax(a, -b).sminsmooths the seam, withkas its width - Distances measured in a scaled-up grid must be divided by the scale to get back to
punits - One distance gives you the fill (with a
pxedge), outlines, offset shadows and glow
Next time we dig into the glow we only touched on here. We'll handle color when bright lights pile up, and use finishing touches like vignettes and film grain to make images look far more polished.
Finished lessons get a mark in the course contents