- Home /
Question by
Selzier · Dec 30, 2020 at 04:29 AM ·
shadertextureshader programmingmaskshader writing
Shader: Mask Without a Texture?
I have a shader working that has a sampler2D for a mask. Black is hidden and white areas are visible:
void surf(Input IN, inout SurfaceOutput o) {
float2 newuv = TRANSFORM_TEX(IN.uv_ArmUpper, _MainTex);
fixed4 MainColor = tex2D(_MainTex, newuv);
fixed4 ArmUpperColor = tex2D(_ArmUpper, IN.uv_ArmUpper);
fixed4 MaskColor = tex2D(_MaskTex, IN.uv_MaskTex);
o.Albedo = ArmUpperColor * MaskColor.rgb + MainColor.rgb * (1 - MaskColor.rgb);
}
The mask is perfect square. It begins at 0,0 and ends at 256,256 (Full image is 512x512):
How can I avoid using this image and send in the data 0,0 - 256,256 as a "Mask" parameter ?
simplemask.jpg
(13.4 kB)
Comment
Best Answer
Answer by Namey5 · Dec 30, 2020 at 06:46 AM
A simple mask like this can just be done by checking if the UV coordinate is within the desired range;
//This will be 1 if the UV is within the range of [min,max] and 0 otherwise
float getMask (float2 uv, float2 min, float2 max)
{
return uv.x >= min.x && uv.x <= max.x && uv.y >= min.y && uv.y <= max.y;
//Alternatively, a faster way of doing the above
return all (abs (uv - min) <= max);
}
...
half4 MainColor = tex2D (_MainTex, newuv);
half4 ArmUpperColor = tex2D (_ArmUpper, IN.uv_ArmUpper);
//UV is in a range of [0,1], so get a mask of the first quarter [0.0,0.5];
half mask = getMask (IN.uv_ArmUpper, 0.0, 0.5);
//Note that this may be flipped vertically, so alternatively use this;
half mask = getMask (IN.uv_ArmUpper, float2 (0.0, 0.5), float2 (0.5, 1.0));
//lerp() will do the same thing as your mask in the code sample
o.Albedo = lerp (MainColor, ArmUpperColor, mask);
Yep, this is the same answer but a lot more full featured I would accept this one.
Answer by sacredgeometry · Dec 30, 2020 at 06:26 AM
UVs are normalised arent they? I think between 0 and 1 but you would have to double check that.
If they are then your logic is just
if(coord.x <= 0.5 && coord.y <= 0.5)
{
// In white square
}
else
{
// In black part
}