Search code examples
openglglslfragment-shaderindices

How to access Vertex Indices in Fragment Shader GLSL


I am drawing indexed GL_LINES with OpenGL. I need to access the indices in my fragment shader for both vertices. Thus I need to know the two indices my line consists of. I read about the built-in variable gl_VertexID which should not be that helpful here. As I already have stored my indices in some buffer I am trying to pass them as an attribute too. Thus my code looks like the following:

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER,vertexBuffer);
glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,0,(void*)0);

glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,indexBuffer);
glVertexAttribPointer(1,2,GL_UNSIGNED_INT,GL_FALSE,0,(void*)0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indexBuffer);

Using this seem to be the wrong way to go, right? Furthermore I use the indices to write some information via image load store atomically. Unfortunatly fetching this image via glGetTexImage yields only zeros. So either my index passing or my image writing/fetching seems to be wrong.

I would be glad for any help here.


Solution

  • For attributes that have integer types in the vertex shader, you need to use glVertexAttribIPointer() (note the additional I) instead of glVertexAttribPointer().

    Since you only have one index per vertex, the second argument, which is the size, should be 1. The call will then look like this:

    glVertexAttribIPointer(1, 1, GL_UNSIGNED_INT, 0, (void*)0);
    

    What you're doing seems somewhat unusual, but I can't think of a reason why using the index array as a vertex attribute would be illegal.

    I believe gl_VertexID is just a sequential id of the vertices produced by the draw command, which is not the same as the vertex index.