NDC in perspective projection
Task
Calculate each fragment's screen position and use it to sample a texture in `iChannel0'.
Theory
Having the normalized device coordinates (NDC) of a fragment is crucial for several advanced rendering techniques in computer graphics (SSAO, SSR, Post-Processing and etc).
Getting NDC Coordinates
In the vertex shader, transform the vertex positions from model space to clip space using the model, view, and projection matrices. Pass the clip space coordinates to the fragment shader:
out vec4 clipPos;
clipPos = projection * view * model * vec4(position, 1.0);
In the fragment shader, receive the clip space coordinates clipPos from the vertex shader. Convert these coordinates to NDC by performing a perspective division (dividing by the w component).
vec3 ndc = clipPos.xyz / clipPos.w;
The division by the w component is necessary to convert from homogeneous clip space to NDC. This division accounts for the perspective effect, ensuring that objects farther from the camera appear smaller.
The resulting NDC coordinates range from -1 to 1 in all three dimensions (x, y, z). These coordinates can then be converted to normalized screen space coordinates by the usual mapping to the interval [0, 1]:
screenTexPos = ndc.xy * 0.5 + 0.5;
screenTexel = texture(screenTex, screenTexPos);
Depth Value
The fragment depth value is stored in the z component of the NDC coordinates. You may also need to convert it to the interval [0, 1]. Because depth textures typically store values in the range [0, 1], where 0 represents the near clipping plane and 1 represents the far clipping plane.