Shader2.0-高斯模糊的实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/coolbeliever/article/details/81948323

要实现高斯模糊,大致的思路是,当某个游戏物体渲染完成后,将该游戏物体交给Shader进行二次渲染,从而实现高斯模糊,C#中有一个回调函数OnRenderImage,这个函数会在渲染完成后调用,我们可以在这个函数中调用Graphics.Blit方法会把传进来的图片与第三个参数中的材质进行二次计算,然后将二次计算的结果赋值给第二个参数。恰好OnRenderImage的第一个参数和第二个参数分别是Graphics.Blit方法的第一个和第二个参数。由于博主语言表达能力不好,还是见代码。

1.新建一个 C#脚本挂在到MainCamera上,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRendener : MonoBehaviour {
    public Material gaosiMaterial;
    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        Graphics.Blit(source, destination, gaosiMaterial);
    }
}

新建一个材质和一个Shader,将Shader指定给新建的材质,并将材质复制到刚才脚本的材质变量中,然后开始编写Shader代码:

Shader "Hidden/TestStruct"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		_Amb("Double",Float) = 0.001  //表示模糊的程度
	}
	SubShader
	{

		Pass
		{
			CGPROGRAM  
			#pragma vertex vert  
			#pragma fragment frag	
			
			#include "UnityCG.cginc"	
			sampler2D _MainTex;
			float _Amb;
			struct appdata
			{
				float4 vertex : POSITION;	
				float2 uv : TEXCOORD0;	
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;	
			};

			
			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = v.uv;
				return o;
			}
			
			
			fixed4 frag (v2f i) : SV_Target	
			{
                                //高斯模糊,原理请自行百度,博主语言表达实在不行
				fixed4 col = tex2D(_MainTex, i.uv);
				fixed4 col1 = tex2D(_MainTex, i.uv + float2(_Amb, 0));
				fixed4 col2 = tex2D(_MainTex, i.uv + float2(-_Amb, 0));
				fixed4 col3 = tex2D(_MainTex, i.uv + float2(0, _Amb));
				fixed4 col4 = tex2D(_MainTex, i.uv + float2(0, -_Amb));
				return (col+col1+col2+col3+col4)/5.0;
			}
			ENDCG
		}
	}
}

猜你喜欢

转载自blog.csdn.net/coolbeliever/article/details/81948323