0

we are tasked to create diffuse lighting for a sphere, but we think we have a bug in our shaders. when we put our shader like this:

vertex shader:

#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 aNormal;


uniform mat4 u_MVP;
uniform mat4 model;
out vec3 FragPos;
out vec3 Normal;

void main() {
    //lighting calculations
    gl_Position = u_MVP * vec4(position,1.0);
    FragPos = vec4(model * vec4(position,1.0)).xyz;
    Normal = aNormal;
};

fragment shader

#version 330 core

layout (location = 0) out vec4 color;

uniform vec3 u_Light;
uniform vec4 u_Color;
in vec3 Normal;
in vec3 FragPos;

void main() {
    // Light emission properties
    // You probably want to put them as uniforms
    vec3 LightColor = vec3(1.0, 1.0, 1.0);
    vec3 ambient = vec3(0.2, 0.2, 0.16);

    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(u_Light - FragPos);
    float diff = clamp(dot(norm, lightDir), 0.0, 1.0);
    vec3 diffuse = diff * LightColor;


    color = (vec4(ambient,1.0f)+vec4(diffuse,1.0)) *u_Color;
    color.a = u_Color[3];
    //color = vec4(0.0, 0.0, 0.5, 0.1);
};

When we put the positions with the model we have no diffuse lighting. When we put the FragPos with the coords of the position (FragPos = position;) it kind of works, but the light does not change direction. We should note that the normals of the sphere were calculated by a tutorial and were not a creation of ours. Do we have a glaring bug and what did we do wrong?

genpfault
  • 51,148
  • 11
  • 85
  • 139

1 Answers1

1

It is not sufficient to transform the vertex position from model space to world space. You also need to transform the normal vector:

FragPos = vec4(model * vec4(position,1.0)).xyz;
Normal = normalize(transpose(inverse(mat3(model))) * aNormal);

I used the inverse transposed top left 3x3 of the 4x4 model matrix to transform the normal vector. See:

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • The problem is still there sadly. Now there is no diffuse lighting even if I calculate the FragPos without the multiplication. Can you imagine why it could be? – Stamatis Mat Nov 22 '20 at 22:00
  • 1
    There is no point in guessing. There are so many possible mistakes (the lightsource is inside the mesh, thn normal vectors are inverted, ...). I can only see the shader. The problem I pointed out in the answer was obvious. – Rabbid76 Nov 22 '20 at 22:02
  • 1
    @Rabbid76 you forgot normalizing the resulting vector, especially since you were going for the most generic case with the inverse-transpose here. – derhass Nov 22 '20 at 22:43