我正在使用OpenGL渲染我的应用程序中的文本,在我的实现中,字形是小的纹理,渲染工作正常,但是性能太低。以下是我的代码片段,当布局包含8000个字形时,大约需要200毫秒才能完成渲染(render函数),我认为“ for循环”是减慢渲染过程的关键,也许将每个字形渲染为纹理是一种“愚蠢的方式” :(,有没有一种方法可以改善文本渲染性能?
#define FONT_BITMAP_WIDTH 128
#define FONT_BITMAP_HEIGHT 128
void setupOpenGL() {
...
...
// create pixel buffer object to render texture
glGenBuffers(1, &_pixelBuffer);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _pixelBuffer);
glBufferData(GL_PIXEL_UNPACK_BUFFER,
FONT_BITMAP_WIDTH * FONT_BITMAP_HEIGHT,
NULL,
GL_STREAM_DRAW);
...
...
// create texture
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RED,
FONT_BITMAP_WIDTH,
FONT_BITMAP_HEIGHT,
0,
GL_RED,
GL_UNSIGNED_BYTE,
NULL);
...
...
}
void render(Glyph** glyphs, int count) {
// render every single glyph
for (int i = 0; i < count; i ++) {
// caculate glyph vertex position
float x0 = glyphs[i]->rect.origin.x;
float y0 = glyphs[i]->rect.origin.y;
float x1 = x0 + FONT_BITMAP_WIDTH;
float y1 = y0 + FONT_BITMAP_HEIGHT;
float positions[] = {
x0, y1, 0.0, 1.0,
x1, y1, 0.0, 1.0,
x0, y0, 0.0, 1.0,
x1, y0, 0.0, 1.0,
};
float textureCoords[] = {
0.0f, 1.0f,
1.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f,
};
// submit vertex and texture coordinate data
glBufferSubData(GL_ARRAY_BUFFER,
0,
sizeof(positions),
positions);
glBufferSubData(GL_ARRAY_BUFFER,
sizeof(positions),
sizeof(textureCoords),
textureCoords);
// submit texture image data
glBufferSubData(GL_PIXEL_UNPACK_BUFFER,
0,
FONT_BITMAP_WIDTH * FONT_BITMAP_HEIGHT,
glyphs[i]->bitmap_ref);
glTexSubImage2D(GL_TEXTURE_2D,
0,
0,
0,
FONT_BITMAP_WIDTH,
FONT_BITMAP_HEIGHT,
GL_RED,
GL_UNSIGNED_BYTE,
0);
// render glyph
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
// present render result
openglFlushBuffer();
}