我正在创建一个简单的opengl程序。编译并链接我的着色器程序后,我尝试使用glGetAttribLocation()
检索输入属性,但它返回-1。
我编译并链接我的程序如下:
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);
这个编译和链接很好。此外,我在代码中对glGetError()
的任何调用都会返回0。
但我无法检索position
的位置:
GLuint vPosition = glGetAttribLocation(shaderProgram, "position");
//position == -1
为什么会这样?
答案 0 :(得分:2)
您必须验证着色器程序是否已正确链接,因为glGetAttribLocation
会查询链接程序的属性变量的位置。属性(或程序输入)是程序资源,其位置在链接程序时确定:
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;
.....
}