Shadows represent the absence of light. For our purpose, a shadow means that some object has interposed itself between the light source and the fragment being rendered. The goal of shadow mapping is to be able to say, for each fragment to be rendered, whether light is being blocked by something (even if that thing is part of the same mesh).
Since being in shadow means that no light from that light source reaches your current fragment, each fragment needs two things:
Its current distance from the light source.
The distance of the object nearest to that light source.
If #2 is greater than #1, then the nearest object to the light source is creating a shadow over that fragment. So you don’t add the contribution of that light source to the overall lighting effect.
#1 is easy enough to compute. For a directional light, you just compute the distance to the near plane, as viewed from the light source. For a point light, you compute the distance to the light position. All of these distances have to be taken using the correct spaces. So you’ll need to [transform the current fragment’s position into different spaces, or just passing the depth or position as a vertex shader output, in the correct space. But they’re all doable easily enough.
The whole purpose of shadow mapping is to provide a shader with access to value #2, which cannot be computed locally.
OK, so you have this shadow map that you rendered from the point of view of the light source. And you have a fragment in the scene. The question you’re probably asking is, “how do I find the right texture coordinate to fetch the correct distance value from?”
That’s really the easy part: texture projection.
Texture projection is a thing where you generate texture coordinates based on the position of vertices. You effectively transform those vertices via normal projection, only you transform them [url=http://alfonse.bitbucket.org/oldtut/Texturing/Tut17%20Projective%20Texture.html]into the space of the texture, rather than into the space of the screen](https://www.opengl.org/wiki/Compute_eye_space_from_window_space). But it’s more or less the same math.
This is commonly used for flashlights and projected lights. But shadow mapping uses it also. For lights, you are using the texture to determine the color and intensity of a light source by projecting the texture across a scene. For shadows, you are using using the texture to determine the depth value nearest the camera for that particular position in the rendered scene.