Frank
Frank

Reputation: 335

Why can't I find my shader attributes?

I'm creating a simple opengl program. After I compile and link my shader program, I try to retrieve an input attribute with glGetAttribLocation(), but it returns -1.

I compile and link my program like this:

GLuint vsID = glCreateShader(GL_VERTEX_SHADER);
GLuint fsID = glCreateShader(GL_FRAGMENT_SHADER);

char vsSource[] = "#version 330 core\n\
in vec4 position;\
void main(void)\
{\
  gl_Position = position;\
}";

char fsSource[] = "#version 330\n\
out vec4 color;\
void main(void)\
{\ 
  color = vec4(1.0, 0.0, 0.0, 1.0);\
}";

const char *p_vsSrc = &vsSource[0];
const char *p_fsSrc = &fsSource[0];

glShaderSource(vsID, 1, &p_vsSrc, nullptr);
glShaderSource(fsID, 1, &p_fsSrc, nullptr);

glCompileShader(vsID);
glCompileShader(fsID);

//Check shader for errors
GLint vsCompiled = GL_FALSE;
GLint fsCompiled = GL_FALSE;
glGetShaderiv(vsID, GL_COMPILE_STATUS, &vsCompiled);
glGetShaderiv(fsID, GL_COMPILE_STATUS, &fsCompiled);
if (vsCompiled != GL_TRUE)
{
  //Error...
}
if (fsCompiled != GL_TRUE)
{
  //Error...
}

GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vsID);
glAttachShader(shaderProgram, fsID);
glLinkProgram(shaderProgram);

This compiles and links fine. Also any calls to glGetError() I place in the code return 0.

However I cannot retrieve the location of position:

GLuint vPosition = glGetAttribLocation(shaderProgram, "position");
//position == -1

Why is this?

Upvotes: 2

Views: 112

Answers (1)

Rabbid76
Rabbid76

Reputation: 211278

You have to verify if the shader program has been linked correctly, because glGetAttribLocation queries the location of an attribute variable of a linked program. The attribute (or program input) is program resource and its location is determined when linking the program:

glLinkProgram( shaderProgram );
GLint status = GL_TRUE;
glGetProgramiv( shaderProgram, GL_LINK_STATUS, &status );
if ( status == GL_FALSE )
{
    GLint logLen;
    glGetProgramiv( shaderProgram, GL_INFO_LOG_LENGTH, &logLen );
    std::vector< char >log( logLen );
    GLsizei written;
    glGetProgramInfoLog( shaderProgram, logLen, &written, log.data() );
    std::cout  << "link error:" << std::endl << log.data() << std::endl;

    .....
}

Upvotes: 2

Related Questions