unity Shader 磨皮

简单的实现了磨皮效果,使用双边滤波

安卓和苹果都进行测试过..可以使用

Shader "Custom/Bilateral"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		_BlurRadius ("BlurRadius",Range(0,9) ) = 0
		_BSIGMA("Size",Range(0.01,0.09)) = 0.1
	}
	SubShader
	{
		Tags { "RenderType"="Opaque" }
		LOD 100

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#pragma multi_compile_fog	
			#include "UnityCG.cginc"

			#define SIGMA 10.0
			#define BSIGMA 0.1
			#define MSIZE 20
			#define PI 3.1415927f

		    sampler2D _MainTex;
			int _BlurRadius;
			float _BSIGMA;
			struct v2f
			{
				float4 pos : SV_POSITION;
				float2 uv : TEXCOORD0;
			};
			
			v2f vert (appdata_tan v)
			{
				v2f o;
				o.pos = UnityObjectToClipPos(v.vertex);
				o.uv = v.texcoord.xy;
				return o;
			}

			float normpdf(float x,float sigma)
			{
				return 0.39894*exp(-0.5*x*x/(sigma*sigma))/sigma;
			}

			float normpdf3(fixed3 v,float sigma)
			{
				return 0.39894*exp(-0.5*dot(v,v)/(sigma*sigma))/sigma;
			}

			fixed4 GetBilateral(float2 uv)
			{
				float3 c = tex2D(_MainTex ,uv).rgb;
				float kernel[MSIZE];
				float3 final_colour = float3(0,0,0);

				float Z = 0.0;
				for (int j = 0; j <= _BlurRadius; ++j)
				{
					kernel[_BlurRadius+j] = kernel[_BlurRadius-j] = normpdf(float(j), SIGMA);
				}
				float3 cc;
				float factor;
				float bZ = 1.0/normpdf(0.0,_BSIGMA);
				for (int i=-_BlurRadius; i <= _BlurRadius; ++i)
				{
					for (int j=-_BlurRadius; j <= _BlurRadius; ++j)
					{
						cc = tex2D(_MainTex,  uv + float2(float(i),float(j))* bZ).rgb;

						factor = normpdf3(cc-c, _BSIGMA)*bZ*kernel[_BlurRadius+j]*kernel[_BlurRadius+i];
						Z += factor;
						final_colour += factor*cc;
					}
				}
				return fixed4 (final_colour/Z,1.0);
			}

			fixed4 frag (v2f i) : SV_Target
			{
				//// sample the texture
				//fixed4 col = tex2D(_MainTex, i.uv);
				//// apply fog
				//UNITY_APPLY_FOG(i.fogCoord, col);
				//return col;
				return GetBilateral(i.uv);
			}
			ENDCG
		}
	}
    Fallback "VertexLit"
}

 

你可能感兴趣的:(Unity3D,shader学习笔记,Unity3D学习日记)