简体   繁体   中英

Unity Shader RGBA Color mask

I am working on a shader for Unity in which I want to change the color based on an mask image. In this mask image the RGB channels stand for a color that can be choosen in the shader. The idea behind the shader is that it is easy to change the look of an object without having to change the texture by hand.

Shader "Custom/MultiColor" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _MaskTex ("Mask area (RGB)", 2D) = "black" {}
        _ColorR ("Red Color", Color) = (1,1,1,1)
        _ColorG ("Green Color", Color) = (1,1,1,1)
        _ColorB ("Blue Color", Color) = (1,1,1,1)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;
        sampler2D _MaskTex;
        half4 _ColorR;
        half4 _ColorG;
        half4 _ColorB;
        half4 _MaskMult;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 main = tex2D (_MainTex, IN.uv_MainTex);
            half4 mask = tex2D (_MaskTex, IN.uv_MainTex);

            half3 cr = main.rgb * _ColorR;
            half3 cg = main.rgb * _ColorG;
            half3 cb = main.rgb * _ColorB;

            half r = mask.r;
            half g = mask.g;
            half b = mask.b;

            half minv = min(r + g + b, 1);

            half3 cf = lerp(lerp(cr, cg, g*(r+g)), cb, b*(r+g+b));
            half3 c = lerp(main.rgb, cf, minv);

            o.Albedo = c.rgb;
            o.Alpha = main.a;
        }
        ENDCG
    } 
    FallBack "Diffuse"
}

The problem with the shader is the blending between the masked color based on the green and blue channel. Between colors defined in the color supposted to be from the red region is visible. Below a sample is visable.在此处输入图像描述

The red color is create by the red mask, green by the green mask and desert yellow by the blue region. I do not know why this happens or how to solve this problem.

Best guess: anti-aliasing or image compression. Aliasing (on the brush your using) will cause an overlap in the color channels, causing them to mix. Compression usually works by averaging each pixel's color info based on the colors around it (jpeg is especially notorious for this).

Troubleshoot by using a straight pixel based brush (no aliasing, no rounded edges) in Photoshop (or whatever image suite you're using) and/or try changing the colors through your shader and see how they mix- doing either should give you a better idea of what's going on under the hood. This combined with an lossless/uncompressed image-type, such as .tga should help, though they may use more memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM