I’m trying to implement per-pixel lighting with GLSL in my program and I just can’t get it to work. Also, sorry for the long post.
Every face has the same color. This image of an ugly skull that I rendered with my shaders should explain the problem:
Here’s my shaders. I removed everything unrelated.
Vertex shader
#version 130
in vec3 inPosition;
in vec4 inColor;
in vec3 inNormal;
smooth out vec4 color;
smooth out vec3 normal;
smooth out vec3 position;
uniform mat4 perspectiveMatrix;
uniform mat4 cameraTransformationMatrix;
uniform mat4 modelTransformationMatrix;
uniform vec3 lightPos;
void main()
{
normal = inNormal;
position = inPosition;
color = inColor;
vec4 pos = cameraTransformationMatrix * vec4(inPosition, 1);
gl_Position = perspectiveMatrix * pos;
}
Fragment shader:
#version 130
smooth in vec4 color;
smooth in vec3 normal;
smooth in vec3 position;
uniform vec3 lightPos;
void main()
{
vec3 lightDir = normalize(lightPos - position);
float diffuseLightIntensity = max(0,dot(normalize(normal),lightDir));
vec4 fragcolor = vec4(diffuseLightIntensity * color.rgb,color.a);
fragcolor.rgb += vec3(0.2,0.2,0.2);
gl_FragColor = fragcolor;
}
I’ve been trying to figure out what could cause this to happen. I’ve tried to change gl_FragColor to different things. For example, gl_FragColor = vec4(lightDir,1) draws the skull with interpolated colors (check image below).
This shows that lightDir varies with every fragment. So that can’t be the problem. Now, if i put gl_FragColor = vec4(normalize(normal),1) I get this:
Which is expected, since every face has the same normal. Now, this part is what confuses me.
float diffuseLightIntensity = max(0,dot(normalize(normal),lightDir));
I take the dot product of the normal and the direction of the light. The normal remains the same for every part of the face, while the lightDir is different for every fragment of the face. Taking the dot product should give me a different value for each fragment, since lightDir is different for each fragment. Am I correct? Either way, diffuseLightIntensity remains the same for every fragment of the face, which can be seen on the first image.
I’m probably just misunderstanding something. If I’m doing something really stupid that I should be able to fix myself, then sorry for wasting your time. But hopefully I shouldn’t make myself look like a fool.
Any help is appreciated.