SFML community forums

Help => Graphics => Topic started by: taifun93 on April 17, 2022, 06:29:00 pm

Title: [SOLVED] setColor() and shader
Post by: taifun93 on April 17, 2022, 06:29:00 pm
Having this simple program, when i use the shader the setColor() function does not take effect. Without using the shader the setColor() works just fine. I want to apply the color and the shader only after everything is drawn
Why does this happen and how can i fix it.


        sf::RenderWindow window;
        sf::RenderTexture screen_tex;
        sf::Sprite screen_sprite;
        sf::Shader shader;

        shader.loadFromFile("shader.vert", "shader.frag");

        window.create(sf::VideoMode(800, 600), "very-nice-window", 3);
        window.setFramerateLimit(60);
        window.setKeyRepeatEnabled(false);

        screen_tex.create(800, 600);
        screen_sprite = sf::Sprite(screen_tex.getTexture());

        screen_tex.clear();
        drowSomeStuff(screen_tex);
        screen_tex.display();
        screen_sprite.setColor({100,0,0});

        window.clear();
        window.draw(screen_sprite, shader);
        window.display();
 
Title: Re: setColor() and shader
Post by: kojack on April 17, 2022, 11:11:48 pm
setColor works by changing the colors of the vertices in the sprite's mesh.
Your shaders needs to be written to receive vertex colors and use them.

Here's an example that works with a sprite.
Vertex shader:
void main()
{
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
    gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
    gl_FrontColor = gl_Color;   // This passes the vertex colour to the fragment shader via the front facing colour output.
}

Fragment shader:
uniform sampler2D tex;

void main()
{
        vec4 c = texture2D(tex, gl_TexCoord[0].xy);
        gl_FragColor = c * gl_Color;  // This gl_Color is actually the interpolated value of gl_FrontColor from the vertex shader.
}
 

Title: Re: setColor() and shader
Post by: taifun93 on April 18, 2022, 12:27:25 pm
Thank you! That fixed the problem, now it works just fine.