LearnFirst steps

Lesson 7 of 30 · 55 min

Combining shapes

Add boxes and segments, and combine shapes with union, intersection and subtraction

In this lesson you will

  • Think of a shape as a single number: the distance to its edge, negative inside
  • Draw boxes (including rounded ones) with sdBox and thick line segments with sdSegment
  • Build unions, intersections and subtractions of shapes with min and max
  • Outline any shape with abs(d) - w
  • Layer shadows and parts in the right order to build simple pictures and icons

01Rethinking shapes as distances

The sdCircle(p, r) from Circles and distance returns length(p) - r. The result is negative inside the circle, 0 exactly on the edge, and positive outside. For a circle of radius 0.5, the point (0.2, 0.0) gives 0.2 - 0.5 = -0.3 (inside, 0.3 from the edge), and the point (0.8, 0.0) gives 0.8 - 0.5 = 0.3 (outside, 0.3 from the edge).

A single number like this — the distance to the edge, negative on the inside — is what we called a signed distance. Once a shape is in this form, whether it's a box, a line or a complicated combination, you fill it the same way every time: 1.0 - smoothstep(-px, px, d). In this lesson we add more shapes that can be written as distances, and learn how to combine them. First, let's set up the "distance as color" view from Circles and distance as a tool for checking new shapes.

1

2

3

4

5

6

7

8

9

10

11

Starts when it scrolls into view
Open in /edit ↗
▸Try sdCircle(p - vec2(0.5, 0.2), 0.3). Change 60.0 to 20.0 and the stripes spread out

Orange is the inside (negative d), blue is the outside (positive d), and the white line is the edge where d = 0. The stripes come from sin(d * 60.0): one appears for every change of about 0.1 in d (the same idea as the contour lines in Circles and distance). If the stripes follow the shape of the edge at even spacing, the function is returning the correct distance to the edge everywhere. From here on, we will check each new shape with this distance map.

02Boxes: sdBox

The signed distance to a box centered at the origin is given by sdBox below. b is half the box's size: the distance from the center to the right edge and to the top edge. vec2(0.6, 0.3) makes a box 1.2 wide and 0.6 tall.

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);

}

Let's go line by line. First, abs(p) drops the signs of x and y. A box is symmetric left-right and top-bottom, so the bottom-left point (-0.9, -0.1) is the same distance away as the top-right point (0.9, 0.1). Using abs to fold every point into the top-right quarter means we only have to think about the top-right corner. Next, d = abs(p) - b holds two numbers: how far the point sticks out past the right edge in x, and past the top edge in y (negative means still inside). Now there are three cases.

  • Both negative (inside the box): the nearest edge is whichever of d.x and d.y is closer to 0, i.e. max(d.x, d.y). With b = (0.6, 0.3) and p = (0.2, 0.1), d = (-0.4, -0.2) and the answer is -0.2 (0.2 from the top edge)
  • Only one positive (outside, beside an edge): the amount sticking out is the distance. With p = (0.9, 0.1), d = (0.3, -0.2) and the answer is 0.3
  • Both positive (outside, past a corner): the nearest point is the corner itself, so the distance is length(d). With p = (0.9, 0.7), d = (0.3, 0.4) and the answer is 0.5

max(d, 0.0) sets negative components to 0, so length(max(d, 0.0)) handles the second and third cases at once and is 0 inside. min(max(d.x, d.y), 0.0) gives a negative value only in the first case and is 0 outside. Adding the two gives the right answer in every case. Let's check it on the distance map.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Starts when it scrolls into view
Open in /edit ↗
▸Use vec2(0.3) for a square. Notice that the outside stripes turn round near the corners

The stripes inside shrink as squares, while the stripes outside round off near the corners. Out there, the nearest point is the corner itself, so lines of equal distance are lines of equal distance from the corner — pieces of a circle. That's the third case.

This rounding gives us rounded boxes. Subtracting r from a distance pushes the edge outward by r: every point within r of the original shape now counts as inside. Near a sharp corner, the points within r form a quarter circle, so the corner becomes round. The trick is to shrink the box first with b - r so the overall size doesn't grow by r.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Starts when it scrolls into view
Open in /edit ↗
▸Set r to 0.0 for sharp corners again. At 0.45 it becomes a capsule with semicircular ends

Tip

The b you pass to sdBox is half the size: for a box 1.0 wide, pass 0.5. And just like sdCircle, to move a box, subtract its center from p: sdBox(p - vec2(0.5, 0.0), b).

03Line segments: sdSegment

The distance to the line segment from point a to point b is given by sdSegment below. A segment has no thickness, so the answer is always 0 or more — there is no inside. To get a thick line, subtract the thickness from the distance, just as with rounded corners. sdSegment(p, a, b) - 0.05 covers everything within 0.05 of the segment, a line 0.1 thick, with naturally rounded ends.

1

2

3

4

5

float sdSegment(vec2 p, vec2 a, vec2 b) {

vec2 pa = p - a, ba = b - a;

float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);

return length(pa - ba * h);

}

The idea is: find the closest point on the segment, then measure the distance to it. pa is the arrow from a to p, and ba is the arrow from a to b. dot(u, v) computes u.x * v.x + u.y * v.y (the dot product), and dot(pa, ba) / dot(ba, ba) says how far along from a to b the point p lands when projected onto the line, as a fraction. Call it h: 0 means at a, 1 means at b.

Take a concrete example: the horizontal segment from a = (-0.5, 0.0) to b = (0.5, 0.0). For p = (0.25, 0.3), pa = (0.75, 0.3) and ba = (1.0, 0.0), so h = 0.75 ÷ 1.0 = 0.75. The closest point on the segment is a + ba × 0.75 = (0.25, 0.0), at a distance of 0.3. For p = (1.0, 0.0), h comes out as 1.5, but the segment stops at b, so clamp cuts it to 1.0. The closest point is the end b, at a distance of 0.5. That clamping is why the area around each end is round.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Starts when it scrolls into view
Open in /edit ↗
▸Change 0.05 to 0.2 for a thick stroke. Make a equal to b and the segment shrinks to a point: just a circle

04Union, intersection and subtraction

In Circles and distance you merged two circles with min(d1, d2) and kept only their overlap with max(d1, d2). These two, plus subtraction, work for any shape written as a distance, not just circles. The reason lies in the rule that the inside is negative.

  • Union min(d1, d2) … inside if inside either. If either is negative, the smaller one is negative
  • Intersection max(d1, d2) … inside only where both are. If even the larger one is negative, both are
  • Subtraction max(d1, -d2) … inside the first and outside the second. -d2 flips the second shape inside out

Let's check with numbers. Say a point is inside the circle (dc = -0.2) and outside the box (db = 0.1). The union is min(-0.2, 0.1) = -0.2: inside. The intersection is max(-0.2, 0.1) = 0.1: outside, since it isn't in both. The subtraction is max(-0.2, -0.1) = -0.1: inside, since it's in the circle but not in the box. Every answer is what we'd expect.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Starts when it scrolls into view
Open in /edit ↗
▸Remove the leading // on one line at a time to compare intersection and subtraction. max(db, -dc) subtracts the circle from the box instead

Tip

As in Circles and distance, if you combine masks (1.0 inside, 0.0 outside), the union is max. With distances (negative inside) it flips, and min is the union, because the sign runs the other way. Also, the result of an intersection or subtraction can drift slightly from the true distance outside the shape. It's plenty for drawing edges; we look at this closely in Drawing with distance (2D SDF).

With subtraction, you can bite one circle out of another to make a crescent moon. Move the biting circle a little and the shape changes like the phases of the moon.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Starts when it scrolls into view
Open in /edit ↗
▸What if the biting radius 0.45 becomes 0.3? Change max(moon, -bite) to max(moon, bite) and only the overlap remains

Tip

p.y - 0.2 is a perfectly good signed distance too: the distance to the horizontal line y = 0.2, negative below it. For example, max(d, p.y) keeps only the part of a shape below y = 0. It's handy for cutting a shape in half.

05Outlines: abs(d) - w

abs(d) gives the distance to the edge as a positive number, inside or out. Subtract w and abs(d) - w is negative only within w of the edge: a band 2 * w wide that follows the edge — an outline. It works the same no matter what shape d describes, so combined shapes get an outline for free.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Starts when it scrolls into view
Open in /edit ↗
▸Change 0.015 to 0.05 for a thick line. Replace abs(d) - 0.015 with abs(abs(d) - 0.1) - 0.015 to get a double line

You get a double line because abs(d) - 0.1 is a distance whose new edge sits 0.1 away from the original edge. Take abs of that again and outline it, and you get two lines: one 0.1 inside and one 0.1 outside. The neon glow uses smoothstep over distances of 0 to 0.15 from the line, brighter the closer you are.

06Layering order and shadows

As you saw in Mixing colors, when you write col = mix(col, shapeColor, mask) several times, whatever comes later is painted on top. When building a picture, write things from back to front. A shadow, for example, is the same shape shifted slightly and painted first, blurred and dark. Blurring is just a matter of making the smoothstep range wider than px.

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

Starts when it scrolls into view
Open in /edit ↗
▸Move the two shadow lines below the three base lines and the shadow ends up on top of the icon. Change the shadow's -0.08, 0.08 to -0.02, 0.02 for a crisp shadow

The icon base is sdBox(p, vec2(0.3)) - 0.15: a box of half-size 0.3 fattened by 0.15, which makes a rounded square with an outer half-size of 0.45. The check mark is the min (union) of a short segment and a long one, fattened by 0.05. Both segments have round ends, so the joint between them looks seamless.

07Assembling parts into a picture

Let's use every tool so far to assemble a robot face. All it does is repeat the same steps for each part: build a distance, combine with union or subtraction, and paint from back to front. The code looks long, but each part is a little group of two or three lines.

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

Starts when it scrolls into view
Open in /edit ↗
▸Put // in front of the mouth = max(mouth, -gaps); line and the gaps between the teeth disappear. Change the head's sdBox(p, vec2(0.4, 0.3)) - 0.1 to sdBox(p, vec2(0.3, 0.2)) - 0.2 for a rounder robot of the same overall size

The head and ears are joined with a union first, then filled and outlined together. Outline them separately and a line would remain where they overlap; take the union first and only the outer contour gets a line. The mouth works the same way: the gaps are subtracted before outlining, so each tooth gets its own outline. Combine first, then paint, and the parts join cleanly.

08Exercises

Combine shapes to make pictures and icons. If you get stuck, check the shape alone on the distance map first (orange inside, blue outside), then add color.

Exercise 1

A picture frame

Use subtraction to cut a slightly smaller box out of a box, making a wooden picture frame. Inside the frame, show a picture: a sunset gradient with a sun.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Starts when it scrolls into view
Open in /edit ↗
Exercise 2

A magnifier icon

Draw a white magnifying-glass symbol on a rounded square. The lens is an outlined circle, the handle is a thick segment running down to the right, and the two are joined with a union.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Starts when it scrolls into view
Open in /edit ↗
Exercise 3

A smiley face

Give the yellow face two eyes and a smiling mouth. The mouth is an outlined circle with only its lower part kept. If you have time, add some blush to the cheeks.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Starts when it scrolls into view
Open in /edit ↗

09Recap

  • Describe a shape as one number — the distance to its edge, negative inside — and you always fill it with 1.0 - smoothstep(-px, px, d)
  • In sdBox(p, b), b is half the size; sdBox(p, b - r) - r rounds the corners
  • sdSegment(p, a, b) - w draws a line 2 * w thick with round ends
  • Union is min(d1, d2), intersection is max(d1, d2), subtraction is max(d1, -d2)
  • abs(d) - w makes an outline; combine first, then outline, to get a line only around the outside
  • With mix, later layers go on top; paint shadows first, shifted and blurred

So far we've placed shapes with p - vec2(…). Next time we extend this idea of transforming the coordinates to rotate shapes, scale them and animate them over time.

Finished lessons get a mark in the course contents