Search code examples
openglshadervertex-shader

Opengl program not recognizing second vertex input


I was reading about shaders and colors, how can they be defined as a vertex input. So i folowed the tutorial and came with a mess because the program was just reading forward and not going into next rows:

GLfloat vertecies[] = {
    //vertices              colors
    0.5f, -0.5f, 0.0f,      1.0f, 0.0f, 0.0f,// Bottom Right
    -0.5f, -0.5f, 0.0f,     0.0f, 1.0f, 0.0f,// Bottom Left
    0.0f,  0.5f, 0.0f,      0.0f, 0.0f, 1.0f,// Top 
};

And here's the following code, that should be setting the second vertex input as colors:

glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertecies), vertecies, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index), index, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);

glBindVertexArray(0);

And here's my vertex shader code:

const char* VertexShaderCode =
 "#version 330 core\r\n"
 ""
 "layout(location=0) in vec3 position;"
 "layout(location=1) in vec3 color;"
 ""
 "out vec3 theColor;"
 ""
 "void main()"
 "{"
 "  gl_Position = vec4(position, 1.0);"
 "  theColor = color;"
 "}";

And here's the fragment shader code:

const char* FragmentShaderCode =
 "#version 330 core\r\n"
 ""
 "in vec3 theColor;"
 ""
 "out vec4 color;"
 ""
 "void main()"
 "{"
 "  color = theColor;"
 "}";

Tell me, if I'm doing anything wrong.


Solution

  • Your stride multiplier is wrong for attribute index 0. It should be 6 because one vertex contains 3 position elements and 3 color elements. Replace

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    

    with

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);