Rounded Rectangle

12 / 18
Practice core GLSL math building blocks used across shaders.

The rounded rectangle SDF is identical to sdBox with one extra parameter — a corner radius r:

Let's break it down.


Difference from sdBox

Plain sdBox returns the distance to the rectangle boundary, leaving sharp corners.

sdRoundBox subtracts the corner radius r from the return value: return … - r. This effectively "expands" the shape outward by r. Because the corners are computed with length, that expansion naturally rounds them into arcs — corner radius appears.

A larger r gives rounder corners. When r equals the smaller half-extent, you get an ellipse or circle.


What the parameters mean

Calling sdRoundBox(p, vec2(0.22, 0.14), 0.05):

  • p = pixel position relative to center (vUv - 0.5)
  • vec2(0.22, 0.14) = half-width 0.22, half-height 0.14
  • 0.05 = corner radius

Actual box: 0.44 wide × 0.28 tall, with 0.05-radius arcs at each corner.


Try changing it

ChangeEffect
Change 0.05 to 0.14Very rounded corners, approaches an ellipse
Change 0.05 to 0.0Equivalent to a plain sharp-cornered rectangle
Change vec2(0.22, 0.14) to vec2(0.2, 0.2)Square with rounded corners
Change 0.01 to 0.04Softer, blurrier edge

Exercise

Call sdRoundBox(p, vec2(0.22, 0.14), 0.05) to compute the distance d, and display a white rounded rectangle.

Answer Breakdown

sdRoundBox works exactly like sdBox but subtracts the corner radius r = 0.05 at the end. This shaves off the sharp corners and replaces them with smooth arcs of radius 0.05. 1.0 - smoothstep(0.0, 0.01, d) maps negative values (inside) to white and positive values (outside) to black.

The exercise starts with float d = 0.0 — every pixel appears to be exactly at the boundary, giving an incorrect result. Replacing it with the sdRoundBox call produces the correct shape.

Try changing the corner radius from 0.05 to 0.12 and watch the corners grow rounder.

GLSL Code Editor

Correct Code Preview

Current Code Preview