在GLES2中使用VBO和VAO对象,已经简单vs,ps绘制一个三角形。
1. 初始化操作代码,创建VBO、VAO,编译和链接shader program。
void DebugApplication::TestCreateVBO() { //顶点shader const GLchar* vertexShaderSrc = "#version 100 " "attribute vec4 a_position; " // 输入顶点属性,从外部传入 "void main() " "{ " "gl_Position = vec4(a_position.x, a_position.y, a_position.z, 1.0); " "} "; //片段shader const GLchar* fragmentShaderSrc = "#version 100 " "void main() " "{ " "gl_FragColor = vec4(1.0,0.5,0.5,1.0); " //随意指定一个输出颜色 "} "; //创建一个vertex shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSrc, NULL); //指定shader代码 glCompileShader(vertexShader); //编译shader //检查是否编译成功 GLint status; GLchar szInfo[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); if (status != 1) { GLint realSize; glGetShaderInfoLog(vertexShader, 512, &realSize, szInfo); std::cout << " Vertex Shader Error : " << szInfo << std::endl; glDeleteShader(vertexShader); return; } //创建片段shader GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragShader, 1, &fragmentShaderSrc, NULL); glCompileShader(fragShader); //检查是否编译成功 glGetShaderiv(fragShader, GL_COMPILE_STATUS, &status); if (status != 1) { GLint realSize; glGetShaderInfoLog(fragShader, 512, &realSize, &szInfo[0]); std::cout << " Fragment Shader Error : " << szInfo << std::endl; glDeleteShader(vertexShader); glDeleteShader(fragShader); return; } //链接Shader到Program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragShader); glLinkProgram(shaderProgram); //检查是否有链接错误 glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status); if (!status) { GLint realSize; glGetShaderInfoLog(shaderProgram, 512, &realSize, &szInfo[0]); std::cout << "Programe Link Error : " << szInfo << std::endl; glDeleteShader(vertexShader); glDeleteShader(fragShader); glDeleteProgram(shaderProgram); return; } m_shader = shaderProgram; //设置顶点缓存 GLfloat vertices[] = { -0.5f,-0.5f, 0.f, 0.5f, -0.5f, 0.f, 0, 0.5f, 0.f }; //创建vbo vao GLuint VBO, VAO; glGenBuffers(1, &VBO); glGenVertexArrays(1, &VAO); //绑定VAO对象 glBindVertexArray(VAO); //复制顶点数组到顶点缓冲区中 glBindBuffer(GL_ARRAY_BUFFER,VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //获取vertex attribute "a_position"的入口点 GLuint location = glGetAttribLocation(shaderProgram, "a_position"); glEnableVertexAttribArray(location); //设置顶点属性指针,传递数据vertex shader的位置0, glVertexAttribPointer(location, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (GLvoid*)0); glBindBuffer(GL_ARRAY_BUFFER, 0); //解绑 glBindVertexArray(0); m_vao = VAO; glDeleteShader(vertexShader); glDeleteShader(fragShader); }
2. 使用之前创建好的VAO 和 shader program 在每帧绘制一个带颜色的三角形。
void DebugApplication::TestDrawVBO() { //使用shader 绑定vao对象进行绘制 glUseProgram(m_shader); glBindVertexArray(m_vao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); }