Search code examples
openglglsllighting

OpenGL Light moving with moving object even though its not supposed to


C++ , OpenGL , Glad ->
I have a light which is supposed to cause some diffuse lighting in the scene.
The problem is that when i rotate my object that is being render on the Y (UP) axis , it seems that the light is also moving with the object. The movement of the light is not synchronized with the rotation of the object.
WHy is this happening and how do i fix this? This is the Shader.
The Vertex Shader

#version 330 core

layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 coords;
layout (location = 2) in vec3 normals;

out vec2 Texture_Coords;
out vec3 normal;
out vec3 toLightVector;

uniform mat4 p;
uniform mat4 m;
uniform mat4 v;
uniform vec3 light_position;

void main(){
    vec4 world_position = m * vec4(pos,1.0);
    gl_Position = p * v * world_position;

    Texture_Coords = coords;
    normal = (vec4(normals,1.0) * m).xyz;

    toLightVector = light_position - world_position.xyz;
}

The Fragment Shader

#version 330 core

out vec4 Pixel;

in vec2 Texture_Coords;
in vec3 normal;
in vec3 toLightVector;

uniform vec4 color;
uniform sampler2D Texture;
uniform float ambient;
uniform vec3 light_color;

void main(){

    vec3 unitNormal = normalize(normal);
    vec3 unitToLightVector = normalize(toLightVector);

    float light_factor = dot(unitNormal, unitToLightVector);
    float brightness = max(light_factor, ambient);
    vec3 diffuse = brightness * light_color;

    Pixel = vec4(diffuse,1.0) * texture(Texture, Texture_Coords);
}

enter image description here


Solution

  • Matrix multiplications are not commutative v * m is not the same as m * v:

    normal = (vec4(normals,1.0) * m).xyz;

    normal = mat3(m) * normals;
    

    I also recommend reading Why is the transposed inverse of the model view matrix used to transform the normal vectors? and Why transforming normals with the transpose of the inverse of the modelview matrix?:

    normal = transpose(inverse(mat3(m))) * normals;