Shader- Blur(转)

作者: 树上的cat_ee3c | 来源:发表于2017-09-28 23:15 被阅读28次

    Blur模糊其实理解了以后非常简单。核心原理就是

    1个点的颜色 并不用该点的颜色,而是用该点周围所有点的均值

    (1)确定取点范围, 例如周围3个像素 或者周围10个像素

    (2)确定各点权重,这也是高斯模糊的由来,主要颜色分配的比重为正态分布,即高斯分布。

    例子1:最简单的模糊

    (1)新场景,plane上面放一张贴图

    (2)plane上的shader如下

    Shader "Custom/ObjectBlur" {

    Properties {

    _MainTex ("Base (RGB)", 2D) = "white" {}

    }

    SubShader

    {

    Tags{"Queue"="Transparent"}

    pass

    {

    CGPROGRAM

    #pragma vertex vert

    #pragma fragment frag

    #include "UnityCG.cginc"

    sampler2D _MainTex;

    float4 _MainTex_ST;

    float uvOffset;

    struct v2f {

    float4pos : SV_POSITION;

    float2uv : TEXCOORD0;

    } ;

    v2f vert (appdata_base v)

    {

    v2f o;

    o.pos = mul(UNITY_MATRIX_MVP,v.vertex);

    o.uv =TRANSFORM_TEX(v.texcoord,_MainTex);

    return o;

    }

    float4 frag (v2f i) : COLOR

    {

    float4 s1 = tex2D(_MainTex,i.uv + float2(uvOffset,0.00));

    float4 s2 = tex2D(_MainTex,i.uv + float2(-uvOffset,0.00));

    float4 s3 = tex2D(_MainTex,i.uv + float2(0.00,uvOffset));

    float4 s4 = tex2D(_MainTex,i.uv + float2(0.00,-uvOffset));

    float4 texCol = tex2D(_MainTex,i.uv);

    float4 outp;

    float pct=0.2;

    outp = texCol* (1- pct*4) + s1* pct + s2* pct+ s3* pct + s4* pct;

    return outp;

    }

    ENDCG

    }

    }

    }

    以及BlurManager.cs脚本,如下

    using UnityEngine;

    using System.Collections;

    public class BlurManager : MonoBehaviour {

    private float length =3f;

    private float showTime = -100;

    private float hideTime = -100;

    void Update () {

    if(showTime >0)

    {

    showTime -= Time.deltaTime;

    Shader.SetGlobalFloat("uvOffset", (showTime/length) * 0.005f);

    }

    if(hideTime >0)

    {

    hideTime -= Time.deltaTime;

    Shader.SetGlobalFloat("uvOffset", (1- hideTime/length) * 0.005f);

    }

    }

    void OnGUI()

    {

    if(GUI.Button(new Rect(0,0,100,50),"Show"))

    {

    showTime = length;

    }

    if(GUI.Button(new Rect(100,0,100,50),"Hide"))

    {

    hideTime = length;

    }

    }

    }

    运行后,点击show按钮,图会从模糊变清晰,点击hide按钮会从清晰变模糊。

    这基本是最简单的模糊了,取本点 和其上下左右的4个偏移点。各点权重均为0.2。uv偏移从0至0.005

    效果如下图还不错。

    原图

    模糊后的效果

    相关文章

      网友评论

        本文标题:Shader- Blur(转)

        本文链接:https://www.haomeiwen.com/subject/rrhbextx.html