Adjusting brightness and contrast of a sprite

Because shaders are black magic and unknowable, it’s not with a small amount of pride I’m happy to share this Shadertoy shader I managed to cobble together for Defold.

This also allows the pure black in an image to become gray, which is the reason I needed it in the first place.

Original shader:
https://www.shadertoy.com/view/ldXXRj

Defold Fragment Program:

uniform lowp sampler2D texture_sampler;
varying mediump vec2 var_texcoord0;
uniform lowp vec4 tint;
uniform lowp vec4 brightness;
uniform lowp vec4 contrast;

vec4 get_contrast(vec4 colors, float contrast)
{
    colors.rgb /= colors.a;
    colors.rgb = ((colors.rgb - 0.5) * max(contrast + 1.0, 0.0)) + 0.5;
    colors.rgb *= colors.a;
    return colors;
}


vec4 get_brightness(vec4 colors, float brightness)
{
    colors.rgb /= colors.a;
    colors.rgb += brightness;
    colors.rgb *= colors.a;
    return colors;
}

void main()
{
    vec2 res = vec2(1.0, 1.0); 
    vec2 uv = var_texcoord0.xy / res.xy;
    vec4 colors = texture2D(texture_sampler, uv);
    lowp vec4 tint_pm = vec4(tint.xyz * tint.w, tint.w);
    gl_FragColor = get_brightness(get_contrast(colors, contrast.x),brightness.x) * tint_pm;
}

The three files for the material zipped up:
TilemapBrightness.zip (1.1 KB)

5 Likes