PDA

View Full Version : Shader lighting and see-through faces



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!

Betrayal
03-06-2015, 12:17 PM
Seems like you didn't enable the depth test.



glEnable(GL_DEPTH_TEST);

Fabrizio255
03-06-2015, 12:30 PM
Hi Betrayal,

I've checked and the depth test is enabled.

Betrayal
03-06-2015, 12:56 PM
Hmm, are you sure?

What library are you using to setup an OpenGL context?
Don't forget to setup a number of bits != 0 for the depth buffer in context creation.


If this doesn't help and nobody else is going to answer, just post the full code an i'll try to search the error tomorrow.

Fabrizio255
03-06-2015, 01:05 PM
Here is the code I use for initialization


int glWin::init(int argc, char* argv[], const char* title, int width, int height, glm::vec4& bgColor)
{
m_bgColor = bgColor;
glutInit(&argc, argv);
glutInitContextVersion(2, 0);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
//glutCreateWindow("My first triangle");
glutCreateWindow(title);
GLenum glew_status = glewInit();
if (glew_status != GLEW_OK)
{
fprintf(stderr, "Error: %s\n", glewGetErrorString(glew_status));
return EXIT_FAILURE;
}
if (!GLEW_VERSION_2_0)
{
fprintf(stderr, "Error: your graphic card does not support OpenGL 2.0\n");
return 1;
}

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
return 1;
}

Betrayal
03-06-2015, 01:12 PM
Well, can you please post the full code?

Fabrizio255
03-06-2015, 04:27 PM
I fixed the problem. Actually the shader and the GL initialization was fine, I've just set up the vertices and indices incorrectly!

Thanks!