总结:1.生成vbo–>2.绑定vbo–>3.开辟一个缓存,然后把数据存进去–>4.设置顶点属性指针(顶点,纹理等)–>5.使能顶点属性的位置索引
举例1:
顶点着色器中:"attribute vec2 pos;\n""attribute vec2 in_uv;\n"//代表顶点和纹理数据
const GLfloat texture2d_vertex_linear[24] =
{//Position //UV-0.9f, 0.9f, 0.0f, 0.9f,-0.1f, 0.9f, 0.9f, 0.9f,-0.9f, 0.1f, 0.0f, 0.0f,-0.1f, 0.1f, 0.9f, 0.0f,-0.1f, 0.9f, 0.9f, 0.9f,-0.9f, 0.1f, 0.0f, 0.0f,};glGenBuffers(1, &texture2d_vbo_linear); //生成缓冲对象glBindBuffer(GL_ARRAY_BUFFER, texture2d_vbo_linear); //绑定//将客户端(通常是CPU)内存中的数据上传到GPU的内存中,并初始化或更新一个已//绑定到当前OpenGL上下文中的缓冲区对象glBufferData(GL_ARRAY_BUFFER, sizeof(texture2d_vertex_linear),texture2d_vertex_linear, GL_STATIC_DRAW); //为顶点着色器指定如何从缓冲区对象中读取顶点属性数据 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GL_FLOAT), NULL);glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GL_FLOAT),(void *)(2 * sizeof(GL_FLOAT)));glEnableVertexAttribArray(0); //启用位置索引为0的顶点属性数组,用于顶点位置数据
glEnableVertexAttribArray(1);//启用位置索引为1的顶点属性数组,用于纹理位置数据
举例2
顶点着色器中:"attribute vec2 a_position; \n""attribute vec3 a_color; \n""attribute vec2 a_center; \n"glGenBuffers(1, &optimizeVBO); //生成
glBindBuffer(GL_ARRAY_BUFFER, optimizeVBO); //绑定//分配一个空的缓冲区,再使用 glBufferSubData 填充
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(color) + sizeof(centers) + sizeof(radii) + sizeof(indices), NULL, GL_STATIC_DRAW);
//填充缓冲区数据(顶点数据,...)
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(vertices), sizeof(color), color);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(color), sizeof(centers), centers);//获取顶点属性位置(这些应该在着色器中定义)positionLocation = glGetAttribLocation(shaderProgram, "a_position");colorLocation = glGetAttribLocation(shaderProgram, "a_color");centerLocation = glGetAttribLocation(shaderProgram, "a_center");
// 设置顶点属性指针(注意偏移量和步长的计算)
// 假设每个顶点位置由2个float组成,每个颜色由3个float组成,每个中心由2个float组成
// 并且这些属性在缓冲区中是连续排列的
glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
glVertexAttribPointer(colorLocation, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)(sizeof(vertices)));
glVertexAttribPointer(centerLocation, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(sizeof(vertices) + sizeof(color)));glEnableVertexAttribArray(positionLocation);
glEnableVertexAttribArray(colorLocation);
glEnableVertexAttribArray(centerLocation);