Gradient map shader - sample project

gradient-shader_itch

A popular to way to re-color assets in other engines is to use a gradient mapping shader. I put together a sample project that uses a gradient map shader to color sprites.

The way it works is the gradientmap material has 2 samplers one for the sprites/animations and one for the gradient(s). The sprites are converted to weighted greyscale sum using a luma-Y component. This value is then used to get dot product with the sprites sampler then the returned values are used in the gradients texture coordinates in the U axis to lookup matching scale and the gradients color is then used. To make the sample project demonstrate the gradient I supplied 4 gradients with size of 64x1-pixels added to a single atlas. The V axis sampling position is then moved between 0.0 - 1.0 to read from the other maps when switched. For the sample project I repurposed the tint.w constant component to use for the gradient sampling V axis value. Values listed in the image are used to center the sampling from each gradient rows

GradientMap.fp
#version 140

in mediump vec2 var_texcoord0;
out vec4 out_fragColor;

uniform mediump sampler2D texture_sampler;
uniform mediump sampler2D gradient;
uniform fs_uniforms
{
    mediump vec4 tint;
};

vec3 lumaY = vec3(0.2126, 0.7152, 0.0722);

void main()
{
    mediump vec4 tint_pm = vec4(tint.xyz * 1.0, 1.0);
    vec4 texture_color = texture(texture_sampler, var_texcoord0.xy) * tint_pm;
    mediump float lookup_luma = dot(texture_color.rgb,lumaY);
    vec4 new_color = texture(gradient, vec2(lookup_luma, tint.w))*texture_color.a;
    vec4 final_color = vec4(new_color.rgb, texture_color.a);
    
    out_fragColor = final_color;
}

Possible Improvements?: Test coloring with vertex attributes for drawcall improvement.

sample project:
https://github.com/FlexYourBrain/sample_gradientmap-shader?tab=readme-ov-file

Cheers~ :artist_palette:

19 Likes