Search code examples
openglglslfragment-shader

Optimizing pixel-swapping shader


I'm using a shader that swaps colors/palettes on a texture. The shader checks a pixel for transparency and then sets the pixel if not transparent. Is there an efficient way to ignore 0 alpha pixels other than a potential branch? In this case, where I set pixel = newPixel:

uniform bool alternate;
uniform sampler2D texture;

void main()
{
    vec4 pixel = texture2D(bitmap, openfl_TextureCoordv);

    if(alternate)
    {
        vec4 newPixel = texture2D(texture, vec2(pixel.r, pixel.b));

        if(newPixel.a != 0.0)
            pixel = newPixel;
    }

    gl_FragColor = pixel;

}

Solution

  • You can use mix and step:

    void main()
    {
        vec4 pixel = texture2D(bitmap, openfl_TextureCoordv);
        vec4 newPixel = texture2D(texture, vec2(pixel.r, pixel.b));
        gl_FragColor = mix(pixel, newPixel, 
                           float(alternate) * (1.0 - step(newPixel.a, 0.0)));
    }
    

    You may want to make a smooth transition depending on the alpha channel. In this case you only need mix:

    gl_FragColor = mix(pixel, newPixel, float(alternate) * newPixel.a);