Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use glVertexAttrib

Tags:

c++

opengl

For my shader, I don't want to enable all attributes for all draw calls. For example in one draw call, I want to use different color for each vertex which is stored in vertex buffer. So I use glEnableVertexAttribArray and glVertexAttribPointer to bind the buffer and it works fine.

However I can't use glVertexAttrib methods for constant colors. Did I misunderstood of these methods? Can you tell if a vertex attribute is enabled from within a vertex shader? says that

If an attribute is disabled, its value comes from regular OpenGL state. Namely, the state set by the glVertexAttrib functions

But when I disable glDisableVertexAttribArray and use glVertexAttrib to set it to a constant, it does not render anything. If I try to use that attribute in the shader, it simply renders black.

What am I missing?

edit:

My code is something like this (it has some abstraction but call order for gl functions is this)

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glEnableVertexAttribArray(position);
    glVertexAttribPointer(position, 3, GL_FLOAT, false, sizeof(Vertex), 0);
    glEnableVertexAttribArray(normal);
    glVertexAttribPointer(normal, 3, GL_FLOAT, true, sizeof(Vertex), (void*)(sizeof(Vec3)));
    glEnableVertexAttribArray(color);
    glVertexAttribPointer(color, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(sizeof(Vec3)+sizeof(Vec3)));

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);

    glDrawElements(
        GL_TRIANGLES,
        (edgeCount - 1)*(edgeCount - 1) * 6,
        GL_UNSIGNED_INT,
        (void*)0
        );

This works however when I replace glEnableVertexAttribArray(color); glVertexAttribPointer(color, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(sizeof(Vec3)+sizeof(Vec3)));

with

glDisableVertexAttribArray(color);
glVertexAttrib4f(color, 1.0f, 0.0, 0.0, 1.0);

It does not work.


1 Answers

It looks like my problem was location of color attribute was being 0, If that location is not enabled it does not render anything.

I moved my position attribute to location 0 (layout(location = 0) attribute vec3 aVertexPosition;) and I can safely enable or disable color attribute now