我的理解是,如果您具有視圖投影矩陣,屏幕寬度和屏幕高度的反轉,則可以將gl_FragCoord轉換爲片段着色器中世界座標中的點。首先,將gl_FragCoord.x
和gl_FragCoord.y
從屏幕空間轉換爲標準化的設備座標,方法是分別除以寬度和高度,然後縮放並將它們偏移到[-1,1]範圍內。接下來,通過逆視投影矩陣進行變換,得到一個世界空間點,只有在用w分量除以後才能使用該點。如何將gl_FragCoord轉換爲片段着色器中的世界空間點?
下面是片段着色器代碼我有不工作。注意inverse_proj
實際上被設爲逆視圖投影矩陣:
#version 450
uniform mat4 inverse_proj;
uniform float screen_width;
uniform float screen_height;
out vec4 fragment;
void main()
{
// Convert screen coordinates to normalized device coordinates (NDC)
vec4 ndc = vec4(
(gl_FragCoord.x/screen_width - 0.5) * 2,
(gl_FragCoord.y/screen_height - 0.5) * 2,
0,
1);
// Convert NDC throuch inverse clip coordinates to view coordinates
vec4 clip = inverse_proj * ndc;
vec3 view = (1/ndc.w * clip).xyz;
// ...
}
通過從頂點着色器變化的世界位置變得更容易(更高效)。 – BDL