Fabrizio255

03-06-2015, 11:47 AM

Hi!

I'm trying to write my first shader, with a fixed directional light. The vertex and fragment shaders are as below:

Vertex Shader:

#version 330

uniform mat4 mvp;

uniform mat3 nmat;

uniform vec3 lightDir;

uniform vec4 ambient;

in vec3 coord3d;

in vec3 v_color;

in vec3 v_normal;

out vec4 f_color;

void main(void)

{

float NdotL;

gl_Position = mvp * vec4(coord3d, 1.0);

f_normal = normalize(nmat * v_normal);

NdotL = max(dot(f_normal, lightDir), 0.0);

f_color = ambient * vec4(v_color,1.0);

if (NdotL > 0.0)

{

f_color += vec4(v_color, 1.0) * NdotL;

}

f_color.a = 1.0;

};

Fragment Shader:

#version 330

in vec4 f_color;

void main(void) {

gl_FragColor = f_color;

};

For nmat, I pass the model transform (converted to a mat3) so that normals and eye are all in world coordinates. With the above shaders, I'm trying to render a scene with two boxes but what I get is this (the light is directed in order to illuminate the top and right faces):

1661

So you see what the problem is: the right face of the box is visible even though it's behind the front face. Do you know why this happens and a possible way out of this problem?

Thanks!

I'm trying to write my first shader, with a fixed directional light. The vertex and fragment shaders are as below:

Vertex Shader:

#version 330

uniform mat4 mvp;

uniform mat3 nmat;

uniform vec3 lightDir;

uniform vec4 ambient;

in vec3 coord3d;

in vec3 v_color;

in vec3 v_normal;

out vec4 f_color;

void main(void)

{

float NdotL;

gl_Position = mvp * vec4(coord3d, 1.0);

f_normal = normalize(nmat * v_normal);

NdotL = max(dot(f_normal, lightDir), 0.0);

f_color = ambient * vec4(v_color,1.0);

if (NdotL > 0.0)

{

f_color += vec4(v_color, 1.0) * NdotL;

}

f_color.a = 1.0;

};

Fragment Shader:

#version 330

in vec4 f_color;

void main(void) {

gl_FragColor = f_color;

};

For nmat, I pass the model transform (converted to a mat3) so that normals and eye are all in world coordinates. With the above shaders, I'm trying to render a scene with two boxes but what I get is this (the light is directed in order to illuminate the top and right faces):

1661

So you see what the problem is: the right face of the box is visible even though it's behind the front face. Do you know why this happens and a possible way out of this problem?

Thanks!