← Back to index

Signed distance field — box

Inigo Quilez's classic box SDF: pull the point into the first quadrant via abs, then split into a corner term (outside) and an inside term. To handle rotation, just transform the query point into the box's local frame first. The box rotates continuously; move it with the mouse.

See also: SDF of a circle — the simplest SDF; Rotate a point around a pivot — how the box-local transform works.

Pseudocode

// Box centred at origin with half-extents (bx, by)
d = |p| - b                            // componentwise
sdfBox(p) = length(max(d, 0)) + min(max(d.x, d.y), 0)

Source

function sdfBox(px, py, bx, by) {
    const dx = Math.abs(px) - bx
    const dy = Math.abs(py) - by
    const ox = Math.max(dx, 0)
    const oy = Math.max(dy, 0)
    return Math.sqrt(ox * ox + oy * oy) + Math.min(Math.max(dx, dy), 0)
}