0
votes

I implemented a per fragment lighting and light attenuation using a window to camera transforms:

vec4 ndcPos;
ndcPos.xy = ((gl_FragCoord.xy / windowSize.xy) * 2.0) - 1.0;
ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) / (gl_DepthRange.far - gl_DepthRange.near);
ndcPos.w = 1.0;

vec4 clipPos = ndcPos / gl_FragCoord.w;

vec3 cameraPos = vec3(clipToCameraMatrix * clipPos);

Then I use lightPos and cameraPos to calculate lighting. lightPos has a fixed position in world space. I have ViewMatrix to handle a fps-style camera and ModelMatrix. Earlier I was using vertex position instead of window to camera transforms and everything was ok. Now I get a incorrect lighting when I move around objects using a camera. Before uploading to fragment shader lightPos is multiplied by ViewMatrix.

glUniform3fv(dirToLightUniformLocation, 1, glm::value_ptr(ViewMatrix * lightPos));

I have no idea what I'm doing wrong.

2
Your code looks correct, so the bug is in code that you're not posting.Nicol Bolas

2 Answers

1
votes

You have one problem here:

ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) / (gl_DepthRange.far - gl_DepthRange.near);

unless you're using a orthographic projection gl_FragCoord.z does not map linear to the depth range, wich is caused by the w-division. Although it is possible (and not difficult) to back-project it, I suggest you just pass the viewspace eye position from the vertex shader to the fragment shader using an additional varying in/out.

0
votes

What is wrong with the lighting? By any chance is the lighting remaining static as you move the view? (i.e. specular highlights never move).

your lightPos should be the normalised Vec3 of: lightPosition - (worldMatrix * vertexPosition)