OpenGL会阻止颜色影响其他几何体

时间:2013-11-25 11:42:03

标签: java opengl

我在使用glColor着色的3D视口上有文本,然后我还将几何图形存储在渲染文本之前渲染的VBO中。由于某种原因,文本颜色实际上影响VBO颜色。我现在实际上并没有为我的VBO着色,所以这可能是问题的一部分。但我尝试在文本渲染中使用glPushAttrib来在调用文本渲染之前保留颜色,并且它不起作用。代码:

public static void renderString(Font font, String string, int gridSize, float x, float y, float charWidth, float charHeight, float scale, Color4f color) {
    glPushAttrib(GL_TEXTURE_BIT | GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);
    glEnable(GL_CULL_FACE);
    glEnable(GL_TEXTURE_2D);
    font.bind();

    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE);

    glColor4f(color.r, color.g, color.b, color.a);

    glPushMatrix();
    glScalef(scale, scale, 0f);
    glTranslatef(x, y, 0);
    glBegin(GL_QUADS);

    for(int i = 0; i < string.length(); i++){
        int code = (int) string.charAt(i);
        float cellSize = 1.0f / gridSize;
        float cellX = ((int) code % gridSize) * cellSize;
        float cellY = ((int) code / gridSize) * cellSize;
        glTexCoord2f(cellX, cellY + cellSize);
        glVertex2f(i * charWidth / 3, y);

        glTexCoord2f(cellX + cellSize, cellY + cellSize);
        glVertex2f(i * charWidth / 3 + charWidth / 2, y);

        glTexCoord2f(cellX + cellSize, cellY);
        glVertex2f(i * charWidth / 3 + charWidth / 2, y + charHeight);

        glTexCoord2f(cellX, cellY);
        glVertex2f(i * charWidth / 3, y + charHeight);
    }
    glEnd();
    glPopMatrix();
    glPopAttrib();
}

它被称为:

public void render() {
    render3D();

    camera.applyTranslations();
    world.render();
    glLoadIdentity();

    if (renderText) {
        render2D();
        renderText();
    }
}

World.render拥有我的VBO,正如您所看到的,它是在调用文本后调用的。那怎么可能呢?如何重置颜色以免影响其他几何体?

2 个答案:

答案 0 :(得分:3)

您似乎想知道为什么使用glPushAttrib / glPopAttrib在进行更改之前没有将OpenGL状态机返回到状态所需的效果。

让我们暂时注意attrib堆栈已被弃用,现代OpenGL不再支持,但你还是没有使用现代功能集。

快速浏览documentation of glPushAttrib会发现GL_COLOR_BUFFER_BIT不会使OpenGL存储颜色属性状态。这是由GL_CURRENT_BIT标志完成的,它会影响整个顶点属性状态。

答案 1 :(得分:0)

OpenGL是一种状态机 - 没有“特定于对象”颜色的感觉。设置颜色后,它会保持这种状态,直到您明确更改颜色。通常,如果您希望以某种颜色绘制某些内容,则必须在绘图调用该对象之前(或期间)设置该颜色。

相关问题