Many animals have a gradation of body color, termed “countershading,” where the areas that are typically exposed to more light are darker. One hypothesis is that this patterning enhances visual camouflage by making the retinal image of the animal match that of the background, a fundamentally two-dimensional theory. More controversially, countershading may also obliterate cues to three-dimensional (3D) shape delivered by shading. Despite relying on distinct cognitive mechanisms, these two potential functions hitherto have been amalgamated in the literature. It has previously not been possible to validate either hypothesis empirically, because there has been no general theory of optimal countershading that allows quantitative predictions to be made about the many environmental parameters involved. Here we unpack the logical distinction between using countershading for background matching and using it to obliterate 3D shape. We use computational modeling to determine the optimal coloration for the camouflage of 3D shape. Our model of 3D concealment is derived from the physics of light and informed by perceptual psychology: we simulate a 3D world that incorporates naturalistic lighting environments. The model allows us to predict countershading coloration for terrestrial environments, for any body shape and a wide range of ecologically relevant parameters. The approach can be generalized to any light distribution, including those underwater.