SAIMA/Assets//Shader/模糊/GaussianBlur.shader

115 lines
5.2 KiB
Plaintext
Raw Normal View History

Shader "Unlit/GaussianBlur"
{
//
//                                                   
//                                      
//                
//                                  
//                            
//                           
//                                     
//                         
//                           
//                             
//                                    
//                            
//                                       
//                                                                                                                      
Properties
{
_MainTex ("Texture", 2D) = "white" {} //基础贴图
_BlurRadius ("BlurRadius", Range(2, 15)) = 5 //模糊半径
_TextureSize ("TextureSize", Float) = 640
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
int _BlurRadius;
float _TextureSize;
float GetGaussWeight(float x, float y, float sigma)
{
float sigma2 = pow(sigma, 2.0f); //pow 次方公式 这里是平方
float left = 1 / (2 * sigma2 * 3.1415926f);
float right = exp(-(x*x+y*y)/(2*sigma2)); //e的指数幂
return left * right;
}
fixed4 GaussBlur(float2 uv) //高斯模糊 根据高斯公式计算出的颜色值
{
float sigma = (float)_BlurRadius / 3.0f;//权重
float4 col = float4(0, 0, 0, 0);
for (int x = - _BlurRadius; x <= _BlurRadius; ++x)
{
for (int y = - _BlurRadius; y <= _BlurRadius; ++y)
{
//获取周围像素的颜色
//转为uv上的坐标值
float4 color = tex2D(_MainTex, uv + float2(x / _TextureSize, y / _TextureSize));
//获取此像素的权重
float weight = GetGaussWeight(x, y, sigma);
//计算此点的最终颜色
col += color * weight; //颜色乘以权重
}
}
return col;
}
fixed4 SimpleBlur(float2 uv)
{
float4 col = float4(0, 0, 0, 0);
for (int x = - _BlurRadius; x <= _BlurRadius; ++x)
{
for (int y = - _BlurRadius; y <= _BlurRadius; ++y)
{
float4 color = tex2D(_MainTex, uv + float2(x / _TextureSize, y / _TextureSize));
col += color;
}
}
//取平均数,所取像素为边长为(半径*2+1)的矩阵
col = col / pow(_BlurRadius * 2 + 1, 2.0f);
return col;
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float4 col = SimpleBlur(i.uv);
return col;
}
ENDCG
}
}
}