我正在为iOS创建一个简单的OpenGL ES 2.0应用程序,每当我调用glDraw Arrays时.我发现这是在我之前为我的两个属性(位置和颜色)调用glEnableVertexAttribArray时发生的,然后发现glGetAttribLocation返回
这是我的代码:
compileShaders函数:
-(void)compileShaders { GLuint vertShader = [self compileShader:@"Shader" ofType:GL_VERTEX_SHADER]; GLuint fragShader = [self compileShader:@"Shader" ofType:GL_FRAGMENT_SHADER]; GLuint program = glCreateProgram(); glAttachShader(program, vertShader); glAttachShader(program, fragShader); glLinkProgram(program); GLint success; glGetProgramiv(program, GL_LINK_STATUS, &success); if (success == GL_FALSE) { GLchar messages[256]; glGetProgramInfoLog(program, sizeof(messages), 0, &messages[0]); NSLog(@"%@", [NSString stringWithUTF8String:messages]); exit(1); } glUseProgram(program); _positionSlot = glGetAttribLocation(program, "position"); _colorSlot = glGetAttribLocation(program, "color"); //Returns 0 _mvpSlot = glGetUniformLocation(program, "MVP"); //Returns 0 if (!_positionSlot || !_colorSlot || !_mvpSlot) { NSLog(@"Failed to retrieve the locations of the shader variables:\n Position:%i\n Color:%i\n MVP:%i", _positionSlot, _colorSlot, _mvpSlot); //Prints out the values of 1, 0, 0 } glEnableVertexAttribArray(_positionSlot); glEnableVertexAttribArray(_colorSlot);
我的渲染功能:
-(void)render:(CADisplayLink *)displayLink { glClearColor(0.5, 0.5, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); GLfloat mvp[16] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; glUniformMatrix4fv(_mvpSlot, 1, 0, mvp); glViewport(0, 0, width, height); glVertexAttribPointer(_positionSlot, 3, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(_colorSlot, 4, GL_UNSIGNED_BYTE, GL_FALSE, 0, colors); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); [_context presentRenderbuffer:GL_RENDERBUFFER]; }
我的顶点着色器:
attribute vec4 position; attribute vec4 color; uniform mat4 MVP; varying vec4 v_color; void main(void) { gl_Position = MVP * position; v_color = color; }0是有效值,-1是“错误”或“未找到”值.统一位置和属性位置的空间是分开的,因此将位置0统一和位置0属性都很好.
您应该发布顶点和颜色数组以检查它们是否具有正确的大小,这可能会导致崩溃.