Closest point to axis aligned cube

Suppose you have a box in three dimensions, as defined by its lower left and upper right corners. Suppose also that you have a point (shown in blue) outside the cube. What's the minimum distance from the outer point to any point on the surface of the cube? Equivalently, how do you calculate the closest point on the surface of the cube to the outer point?

My initial thought was to test the distances to all the corners and take the minimum, but that doesn't work if the outer point is close to a face.

Second, I reasoned: okay, so, we can play tricks by projecting the point onto the planes aligned with the faces of the cuboid, and do four modified point-to-line distance tests per plane. It would be a bear to code, but should work in theory.

I also realized that we could use the 26 (9+9+8) implicit half-spaces defined by the faces to classify points based on which face, corner, or edge they would be closest to. But that, too, would be... unpleasant.

There is a nice trick you can do to avoid all that pain, though, if your box happens to be axis-aligned. If it's not, the easist solution is probably to just rotate your coordinate space until it is.

Once you have an axis-aligned box, the trick is to simply clamp() the individual components of the outer point to the corners of the square. To illustrate how the trick works, it's probably easiest to show a two-dimensional case instead.

Closest point to axis aligned (2D) square

Below is an interactive canvas demo showing how the two-dimensional case works. It's trivial in one dimension, easy to see in two, and very pretty in three. Mouse over the box below to see the closest (green) point on the white box to the mouse's position (blue).

Conceptually, the dark red areas should be mapped to the corners, and the light orange and blue get mapped to the edges; anything inside the white stays in place. Luckily, that's precisely the behavior that clamp() provides!