c++openglglslshadervao

Adding line to shader makes nothing draw


I have this vertex shader. When i remove in vec3 LVertexNorm and everything related to it. It render fine. But if i add it in, nothing renders anymore.

 #version 140

in vec3 LVertexNorm;
in vec3 LVertexPos2D;

uniform mat4 MVP;

out vec3 norm;

void main() {
    norm = LVertexNorm;
    gl_Position = MVP * vec4( LVertexPos2D.x, LVertexPos2D.y, LVertexPos2D.z, 1 );
}

Fragment shader

    #version 140

in vec3 norm;
out vec4 LFragment; 
void main() { 
    LFragment = vec4( 1.0,1.0,1.0, 1.0 ); 
}

And code for building the VAO

    glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, verticesCount * sizeof(GLfloat), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(program->getAttribute("LVertexPos2D"), 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, nbo);
glBufferData(GL_ARRAY_BUFFER, normalCount * sizeof(GLfloat), normals, GL_STATIC_DRAW);
glVertexAttribPointer(program->getAttribute("LVertexNorm"), 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesCount * sizeof(GLuint), indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); 
glBindVertexArray(0);

I tryd different ways. And always the same result. when LVertexNorm gets added, shader stops working. I cant ifgure out why. What might be wrong?


Solution

  • The argument to glEnableVertexAttribArray has to be the vertex attribute index:

    GLuint pos_inx = program->getAttribute("LVertexPos2D")
    glVertexAttribPointer(pos_inx, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL);
    glEnableVertexAttribArray(pos_inx);
    
    GLuint norm_inx = program->getAttribute("LVertexNorm");
    glVertexAttribPointer(norm_inx, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL);
    glEnableVertexAttribArray(norm_inx);
    

    When you have the vertex shader input variables in vec3 LVertexNorm; and in vec3 LVertexPos2D;, then possibly LVertexNorm gets the attribute index 0 and LVertexPos2D gets the attribute index 1. Since the vertex attribute 1 is not enabled, the vertex positions are not specified.
    In fact, the attribute indexes are not specified and can be any number. Most drivers, however, use ascending indexes that start at 0.