随机彩色块

时间:2016-08-07 06:43:42

标签: c++ opengl

我最近使用了一个freetype库来读取文本文件,并遵循了一些如何在2D中显示文本的指南。 我试图扩展代码以支持3D文本呈现,但我开始遇到与opengl相关的问题。 在某些角度,文本图片开始淡化,文本所在的整个轴开始继承其颜色。 Fading; Black Slice

所有相关代码均为:

绘图功能(继承自learnopengl.com)

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Activate corresponding render state  
glActiveTexture(GL_TEXTURE0);
glBindVertexArray(VAO);
glEnableVertexAttribArray(0);

scale /= RESOLUTION;
vec2 start(x, y);
// Iterate through all characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
    Character ch = Characters[*c];
    if (*c == '\r' || (x-start.x > xMax && xMax != 0.0f))
    {
        y += ((ch.Advance >> 6) + 16) * scale ;
        x = start.x;
        continue;
    }

    GLfloat xpos = x + ch.Bearing.x * scale;
    GLfloat ypos = y + (ch.Size.y - ch.Bearing.y) * scale;

    GLfloat w = ch.Size.x * scale;
    GLfloat h = ch.Size.y * scale;
    // Update VBO for each character
    GLfloat vertices[6][4] = {
        { xpos,     ypos - h,   0.0, 0.0 },
        { xpos,     ypos,       0.0, 1.0 },
        { xpos + w, ypos,       1.0, 1.0 },

        { xpos,     ypos - h,   0.0, 0.0 },
        { xpos + w, ypos,       1.0, 1.0 },
        { xpos + w, ypos - h,   1.0, 0.0 }
    };
    // Render glyph texture over quad
    glBindTexture(GL_TEXTURE_2D, ch.TextureID);

    // Update content of VBO memory
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    // Render quad
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    // Now advance cursors for next glyph (note that advance is number of 1/64 pixels)
    x += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64)
}
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);

着色器统一初始化

ShaderBuilder::LoadShader(shader)->Add_mat4("projection", projection).Add_mat4("view", view).
    Add_mat4("model", model).Add_vec3("textColor", color).Add_texture("text", 0);

顶点着色器     #version 400核心     vec4顶点的布局(位置= 0); //     vec2 TexCoords;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main()
{
    vec2 vertexGL = (vertex.xy - vec2(400,300)) / vec2(400,300);
    vertexGL = vertex.xy;
    vec4 position = projection * view * model * vec4(vertexGL.xy, 0.0, 1.0);
    gl_Position = position / position.w;

    TexCoords = vertex.zw;
}  

Fragment Shader     #version 400核心     在vec2 TexCoords;     vec4颜色;

uniform sampler2D text;
uniform vec3 textColor;

void main()
{    
    vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r);
    color = vec4(textColor, 1.0) * sampled;
    //color = vec4(1);
}  

1 个答案:

答案 0 :(得分:0)

我终于找到了错误,由于一些未知的原因,我认为在应用矩阵乘法后对顶点坐标进行归一化将是一个很好的做法。 显然它不是。

vec4 position = projection * view * model * vec4(vertexGL.xy, 0.0, 1.0);
    gl_Position = position;// / position.w;

因此评论声明,这消除了错误。