[Unity Shaders] 半透明材質的混合效果
阿新 • • 發佈:2019-02-19
// Test_Effect.shader
// This shader is used for overlay effects with transparent blending textures.
// Last edit: 2017-08-29
Shader "Custom/Test_Effect" {
Properties {
_MainTex ("RGBA Texture Image", 2D) = "white" {} // note "RGBA Texture Image" instead of "Base (RGB)" or "Base Texture"
_BlendTex ("Blend Texture", 2D) = "white" {}
}
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform sampler2D _BlendTex;
struct vertexInput {
float4 vertex : POSITION;
float4 texcoord : TEXCOORD0;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 tex : TEXCOORD0;
};
vertexOutput vert(vertexInput input) {
vertexOutput output;
output.tex = input.texcoord;
output.pos = UnityObjectToClipPos(input.vertex);
return output;
}
// the blending function for overlay effects
fixed OverlayBlendMode(fixed basePixel, fixed blendPixel) {
if(basePixel < 0.5) {
return (2.0 * basePixel * blendPixel);
} else {
return (1.0 - 2.0 * (1.0 - basePixel) * (1.0 - blendPixel));
}
}
// core function HERE
float4 frag(vertexOutput input) : COLOR {
float4 renderTex = tex2D(_MainTex, input.tex.xy); // get the current pixel of the base picture
float4 blendTex = tex2D(_BlendTex, input.tex.xy); // get the current pixel of the blending texture
float4 blendedImage = renderTex;
float4 img = blendTex;
// rgba blending
if(img.a > 0.1) {
// blend when the blending texture's alpha is greater than 0.1
blendedImage.r = OverlayBlendMode(renderTex.r, blendTex.r);
blendedImage.g = OverlayBlendMode(renderTex.g, blendTex.g);
blendedImage.b = OverlayBlendMode(renderTex.b, blendTex.b);
blendedImage.a = blendTex.a;
} else {
// do not blend if the blending texture's alpha is close to 0
blendedImage = renderTex;
}
// blend by the alpha of the current blending pixel
renderTex = lerp(renderTex, blendedImage, img.a);
return renderTex;
}
ENDCG
}
}
FallBack "Diffuse" // use "Diffuse" if the upper subshader fails
}