Unity shader学习之屏幕后期处理效果之均值模糊

均值模糊,也使用卷积来实现,之不过卷积中每个值均相等,且相加等于1。

代码如下,

子类:

1 using UnityEngine;
2 
3 public class MeanBlurRenderer : PostEffectRenderer
4 {
5     protected override string ShaderName
6     {
7         get { return "Custom/Mean Blur"; }
8     }
9 }
MeanBlurRenderer

 

shader

 1 Shader "Custom/Mean Blur"
 2 {
 3     Properties
 4     {
 5         _MainTex("Main Texture", 2D) = "white" {}
 6     }
 7 
 8     SubShader
 9     {
10         Pass
11         {
12             Cull Off
13             ZWrite Off
14             ZTest Always
15 
16             CGPROGRAM
17             #pragma vertex vert
18             #pragma fragment frag
19 
20             sampler2D _MainTex;
21             float4 _MainTex_TexelSize;
22 
23             struct appdata
24             {
25                 float4 vertex : POSITION;
26                 float2 uv : TEXCOORD0;
27             };
28 
29             struct v2f
30             {
31                 float4 pos : SV_POSITION;
32                 float2 uv[9] : TEXCOORD0;
33             };
34 
35             v2f vert(appdata v)
36             {
37                 v2f o;
38                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
39                 o.uv[0] = v.uv + _MainTex_TexelSize.xy * float2(-1, 1);
40                 o.uv[1] = v.uv + _MainTex_TexelSize.xy * float2(0, 1);
41                 o.uv[2] = v.uv + _MainTex_TexelSize.xy * float2(1, 1);
42                 o.uv[3] = v.uv + _MainTex_TexelSize.xy * float2(-1, 0);
43                 o.uv[4] = v.uv + _MainTex_TexelSize.xy * float2(0, 0);
44                 o.uv[5] = v.uv + _MainTex_TexelSize.xy * float2(1, 0);
45                 o.uv[6] = v.uv + _MainTex_TexelSize.xy * float2(-1, -1);
46                 o.uv[7] = v.uv + _MainTex_TexelSize.xy * float2(0, -1);
47                 o.uv[8] = v.uv + _MainTex_TexelSize.xy * float2(1, -1);
48                 return o;
49             }
50 
51             fixed4 frag(v2f i) : SV_TARGET
52             {
53                 float4 col = float4(0, 0, 0, 0);
54                 for(int k = 0; k < 9; k++)
55                 {
56                     float4 tex = tex2D(_MainTex, i.uv[k]);
57                     col += tex;
58                 }
59                 return col * 0.1111;
60             }
61 
62             ENDCG
63         }
64     }
65 
66     Fallback Off
67 }
View Code

效果,左边为正常,右边为均值模糊:

 

posted @ 2017-07-26 09:34  孤独の巡礼  阅读(885)  评论(0编辑  收藏  举报