简体   繁体   中英

Fragment Shader Rotation

I've been having a few problems with my fragment shader. After a bit of research, it appears that drivers clean up unused variables (ones which have no effect on the output?), which can cause glSetUniform and glGetUniform to return -1.

My current problem is that I'm attempting to rotate a texture 180 degrees, but it appears that I'm doing something incorrectly, as the uniform int "top" appears to be garbage collected, and cannot be found. The texture is not rotated at all, but still renders. The uniform "top" returns -1, which should not happen.

Here's my relevant code:

Rendering and Shader Enable code: (Shader.PIPE.enable() does call glUseProgram())

    Shader.PIPE.enable();
    Shader.PIPE.setUniformMat4f("vw_matrix", Matrix4f.translate(new Vector3f(xScroll * 0.03f, 0.0f, 0.0f)));    
    Pipe.getTexture().bind();
    Pipe.getMesh().bind();

    for (int i = 0; i < 5 * 2; i++) {
        Shader.PIPE.setUniformMat4f("ml_matrix", pipes[i].getModelMatrix());
        Shader.PIPE.setUniform1i("top",  i % 2 == 0 ? 1 : 0);
        Pipe.getMesh().draw();
    }
    Pipe.getMesh().unbind();
    Pipe.getTexture().unBind();

Pipe.frag:

#version 330 core

layout (location = 0) out vec4 color;

in DATA 
{
    vec2 tc;
} fs_in;

uniform sampler2D tex;
uniform int top;

void main() 
{   
    vec2 myTc = vec2(fs_in.tc.x, fs_in.tc.y);
    if (top == 1) {
        myTc.y = top - myTc.y;  
    }

    color = texture(tex, fs_in.tc);
    if (color.w  < 1.0)
        discard;
}

Pipe.vert:

#version 330 core

layout (location = 0) in vec4 position;
layout (location = 1) in vec2 tc;

uniform mat4 pr_matrix;
uniform mat4 vw_matrix = mat4(1.0);
uniform mat4 ml_matrix = mat4(1.0);

out DATA
{
    vec2 tc;
} vs_out;

void main() 
{
    gl_Position = pr_matrix * vw_matrix * ml_matrix * position;
    vs_out.tc = tc;
}

The compiler can not only eliminate completely unused variables, but also values that do not contribute to the result. In your code, top is used here:

if (top == 1) {
    myTc.y = top - myTc.y;  
}

But myTc is not used later in the shader. So the value of myTc has no effect on the output of the shader. Which in turn means that the value of top has no effect. Or in other words, the result of the shader is the same, independent of the value of top .

This changes if myTc is used later in the shader, in a way that influences the result. I actually suspect that you meant to do that, and use it as the texture coordinates to sample your texture. So instead of:

color = texture(tex, fs_in.tc);

you should use:

color = texture(tex, myTc);

Now top will be used, and you should get the desired result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM