I’m trying to go from clip space to world space and then to light clip space in a fragment shader (what you would want to do if you do shadow mapping with a deferred shader), but I can’t get it working. My generated world space coordinates don’t stand still. They get more and more misaligned the farther I move the camera from the world origin.
This is a fragment shader that only goes from clip space to world space, but it still doesn’t work very well (same problem).
uniform sampler2D depth; //The depth buffer of the scene, verified to be bound correctly and containing correct data.
uniform mat4x4 inverseProjectionMatrix, inverseViewMatrix; //Correctly set.
in vec2 position; //Interpolated from a fullscreen quad. Clip space position [-1, 1], verified to be working.
layout(location = 0) out vec4 fragColor;
void main()
{
float z = texture2D(depth, texCoords).z; //Get depth (DEPTH_COMPONENT texture), verified to be working.
vec4 eyeSpace = inverseProjectionMatrix * vec4(position.x, position.y, z, 1);
//eyeSpace /= eyeSpace.w; //Doesn't seem to affect it as I do a w-divide for worldSpace too.
vec4 worldSpace = inverseViewMatrix * eyeSpace;
worldSpace /= worldSpace.w;
fragColor = vec4(worldSpace.xyz, 1); //Colors of the same point in world space change when the camera moves.
}
Am I doing something wrong?
Matrix setup:
Matrix4f.invert(projectionMatrix, null).store(matrixBuffer);
matrixBuffer.flip();
GL20.glUniformMatrix4(volumetricShader.getUniformLocation("inverseProjectionMatrix"), false, matrixBuffer);
matrixBuffer.clear();
Matrix4f.invert(viewMatrix, null).store(matrixBuffer);
matrixBuffer.flip();
GL20.glUniformMatrix4(volumetricShader.getUniformLocation("inverseViewMatrix"), false, matrixBuffer);
matrixBuffer.clear();
Jeez… Matrices are so annoying sometimes…