I want to lerp a color into a gray scale range. The gray scale is a single texture channel.
The additional color should be fade in and out at some predefined values. In this case 0.2 - 0.5. But should be also anything else inside 0 and 1. Between in and out the transition should be linear simply.
Does anyone has an idear to solve this in a fast way in shader code?
Thanks a lot…
I honestly don’t understand quite what you’re asking for. As best I can understand you have a grayscale texture and you want to colorize a range of values of that texture?
fixed g = tex2D(_GreyTex, i.uv).g;
// rescale the range 0.2 … 0.5 to 0.0 … 1.0
fixed desaturation = saturate((g - 0.2) / (0.5 - 0.2));
Ah … because “0.5” or 128/255 in the shader isn’t where you think it is when you’re using the linear color space. Where 128 / 255 appears in the texture (when checked in an image editor) will be ~0.72 in the shader because in linear rendering the texture is converted from sRGB to a linear color when the shader uses it.
You can set the texture to be linear (set it to texture type “Advanced” and click on “bypass sRGB”) then do this:
fixed g = tex2D(_MainTex, i.uv).g;
// rescale the range 0.2 .. 0.5 to 0.0 .. 1.0
fixed desaturation = saturate((g - _A) / (_B - _A));
// change 0.0 .. 0.5 .. 1.0 to 1.0 .. 0.0 .. 1.0
desaturation = abs(desaturation * 2.0 - 1.0);
// lerp between grey and colorized grey
fixed3 col = lerp(g * _Color.rgb, fixed3(g, g, g), desaturation);
if (!IsGammaSpace())
col = GammaToLinearSpace(col);
This will get identical results regardless of being in gamma or linear!
Alternatively you can keep the texture as is and do extra math in the shader, or do the same amount of math but have slightly different results from linear and gamma color space.
Unfortunately I got strange results >= 2019.2 If I use this shader in Linear with the old one:
Set the texture property to srgb texture = false gives better LO HI position results.