# Why does my lighting look incorrect?

I have a problem with lighting calculations. I am rotating the camera around a cube which was supposed to be illuminated by the light but the resulting lighting is very weird. Check out the image above, fragment shader and vertex shader below.

#version 330 core

layout (location = 0) in vec3 pos;
layout (location = 1) in vec3 norm;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform vec3 lightPos;

out vec3 ourNormal;
out vec3 fragPos;
out vec3 ourLightPos;

void main()
{
gl_Position = projection*view*model*vec4(pos,1.0);
fragPos = vec3(view * model * vec4(pos, 1.0f));
ourNormal = mat3(transpose(inverse(view * model))) * norm;
ourLightPos = vec3(view * vec4(lightPos, 1.0));
}

#version 330 core

//Output variables
out vec4 finalColor;

//Input variables
in vec3 ourNormal;
in vec3 fragPos;
in vec3 ourLightPos;

//Uniform variables

struct Material
{
vec3 ambient;
vec3 diffuse;
vec3 specular;
float shininess;
};

struct Light
{
vec3 ambient;
vec3 diffuse;
vec3 specular;
};

uniform Light light;
uniform Material material;
uniform vec3 viewPos;

void main()
{
//Ambient
vec3 ambient = light.ambient*material.ambient;

//Diffuse
vec3 normal = normalize(ourNormal);
vec3 lightDir = normalize(ourLightPos - fragPos);
float diffuseStrength = max(dot(lightDir,normal),0.0);
vec3 diffuse = light.diffuse*(diffuseStrength*material.diffuse);

//Specular
vec3 viewDir = normalize(viewPos - fragPos);
vec3 reflectDir = reflect(-lightDir,normal);
float specularStrength =         pow(max(dot(viewDir,reflectDir),0.0),material.shininess);
vec3 specular = light.specular * (specularStrength*material.specular);

//Last step
vec3 result = (ambient+diffuse+specular);
finalColor = vec4(result,1.0);
}

As you can see, I transformed all the positions, normals and light source position in view space, i.e camera space, but I don't know why it's not working.

• Maybe your model of the box has a wrong normal. – user1888 Feb 7 '16 at 10:05
• This might not be the error, but you have a uniform "viewPos" which is, I assume, the camera position. But you do all calculations in Camera-Space, so this should always be $(0.0, 0.0, 0.0)$ and thereby the viewDir becomes $-1 * fragPos$. – Dragonseel Feb 7 '16 at 14:30
• @Dragonseel Yup!! That was the problem! Thank you for taking out some time for this question! – Ankit singh kushwah Feb 8 '16 at 17:41
• @Dragonseel: since it was the correct observation, could you turn the comment into an answer? – Julien Guertault Apr 7 '16 at 2:53
• @JulienGuertault yes. Done – Dragonseel Apr 7 '16 at 14:59

The problem with your calculations is that you use a uniform for viewPos which is the camera position. The rest of your calculations is in Camera-Space, so the viewPos should always be $(0.0, 0.0, 0.0)$ and thereby the $viewDir$ becomes $-1*\text{fragPos}$.