Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: [SOLVED] setColor() and shader  (Read 1929 times)

0 Members and 1 Guest are viewing this topic.

taifun93

  • Newbie
  • *
  • Posts: 9
    • View Profile
[SOLVED] setColor() and shader
« 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();
 
« Last Edit: April 18, 2022, 12:30:57 pm by taifun93 »

kojack

  • Sr. Member
  • ****
  • Posts: 343
  • C++/C# game dev teacher.
    • View Profile
Re: setColor() and shader
« Reply #1 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.
}
 


taifun93

  • Newbie
  • *
  • Posts: 9
    • View Profile
Re: setColor() and shader
« Reply #2 on: April 18, 2022, 12:27:25 pm »
Thank you! That fixed the problem, now it works just fine.

 

anything