UnityShader基础(七)——屏幕后处理效果

        屏幕后处理是基于渲染纹理实现的,通过更改渲染纹理的颜色等等实现某些某些视觉效果。 

一、OnRenderImage脚本的编写

        OnRenderImage函数是MonoBehaviour提供的事件回调函数,不止MonoBehaviour拥有这个函数,Camera也拥有着这个函数,就很怪,而且普通物体上这个回调好像还不生效,官网的说法是,在相机完成渲染后,Unity 调用作为启用的相机组件OnRenderImage,附加到同一个游戏对象的 MonoBehaviours 。换句话说Camera组件必须和Mono脚本挂在同一个物体上,OnRenderImage才会生效。

private void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        throw new NotImplementedException();
    }

        第一个参数代表源纹理,第二个参数代表目标纹理。Unity会将当前渲染成的图像存储在第一个参数中,然后经过一系列函数处理,将第二个参数的结果显示到屏幕上。        

        OnRenderImage只是负责事件回调,真正的图像处理需要借助另一个函数。         

private void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        Graphics.Blit(src,dest,mat)
        throw new NotImplementedException();
    }

        即借助Blit函数实现真正的处理,关于渲染纹理在不同平台上可能会出现反转问题,这个官网的解释很详细。我就简单说一下,首先不同平台会出现渲染纹理反转问题,Unity内部自动替我们做了这件事,但当我们开启抗锯齿和图像效果的时候,Unity并不会为我们反转,但是,如果我们使用Blit函数时,即便开启了抗锯齿,Unity仍然会在Blit内部会处理这个问题。

二、屏幕亮度、饱和度、对比度的调整

        脚本:

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

public class RenderImage : MonoBehaviour
{
    public Shader shader;
    [Header("亮度")]
    public float brightness=1;
    [Header("饱和度")]
    public float saturation=1;
    [Header("对比度")]
    public float contrast=1;

    private Material _material;
    // Start is called before the first frame update
    void Awake()
    {
        if (shader==null)
        {
            Debug.Log("Shader为空");
        }

        _material = new Material(shader);
    }
    
    private void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (_material!=null)
        {
            _material.SetFloat("_Brightness",brightness);
            _material.SetFloat("_Saturation",saturation);
            _material.SetFloat("_Contrast",contrast);
            Graphics.Blit(src,dest,_material);
        }   
    }

}

        我就很好奇,Shader需要的顶点数据究竟是谁给传过去的,而且那些顶点数据又是谁的,Camera本身有没有MeshRender,但是你不写吧,结果就是一片黑。原来书中有写,Unity又单独用了一个Quad用来显示渲染纹理。

        Shader:

Shader "Custom/Test0"
{
    Properties
    {
        
        _MainTex("渲染纹理",2D)="white"{}
        _Brightness("亮度",float)=1.0
        _Saturation("饱和度",float)=1.0
        _Contrast("对比度",float)=1.0
    }
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
            sampler2D _MainTex;                        
            float4 _MainTex_ST;            
            fixed _Brightness;
            fixed _Saturation;
            fixed _Contrast;
            struct a2v
            {
                //这些数据是从哪里来的???
                float4 vertex:POSITION;
                float2 texcoord:TEXCOORD0;
            };
 
            struct v2f
            {
                float4 pos:SV_POSITION;           
                float2 uv:TEXCOORD0;
            
            };
            
            v2f vert(a2v v)
            {                
                v2f o;                                                                
                o.pos=UnityObjectToClipPos(v.vertex);
                o.uv=TRANSFORM_TEX(v.texcoord,_MainTex);                
                return o;
                
            }
 
            fixed4 frag(v2f i):SV_Target
            {                
                fixed4 texResult=tex2D(_MainTex,i.uv);
                //计算亮度                    
                fixed3 color=texResult*_Brightness;
                //计算饱和度
                fixed luminance=0.2125*texResult.r+0.7154*texResult.r+0.0721*texResult.b;
                fixed3 luminanceColor=fixed3(luminance,luminance,luminance);
                color=lerp(luminanceColor,color,_Saturation);
                //计算对比读度
                fixed3 avgColor=fixed3(0.5,0.5,0.5);
                color=lerp(avgColor,color,_Contrast);
                return fixed4(color,1);
            }
            
            ENDCG
        }
    }
}

        不要问我为什么这样写,有时候就感觉程序员要懂得东西有点多,头发又掉了一大撮。

        调过值后的结果: 

原图像(场景中无任何顶光和天空盒):       

三、边缘检测 

        利用卷积操作实现判断哪些像素点更有可能是边缘,然后对更有可能是边缘的像素点进行颜色处理,实际就是根据该像素点相邻像素点的颜色差距计算出来一个梯度值,越大越有可能是边缘。

        这种利用纯数学的方式有时会出现一些问题,如果某些像素不是边缘但像素差距较大,比如衣服上一个纽扣,我们想实现人物边缘检测,但纽扣本身也有可能会被当作边缘进行处理,而且物体的阴影,纹理等等都会影响边缘检测的效果,在后续文章中,我们会使用更加准确的方式。

        我们使用Sobel算子进行边缘检测。

        脚本:

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

[ExecuteInEditMode]
public class RenderImage : MonoBehaviour
{
    public Shader shader;
    [Header("边缘颜色")]
    public Color edgeColor=Color.black;
    [Header("仅显示边缘")][Range(0,1)]
    public float edgeOnly=0;

    private Material _material;

    private void Awake()
    {
        if (shader==null)
        {
            //Debug.Log("Shader为空");
            return ;
        }
        _material = new Material(shader);
    
    }

    private void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (_material!=null)
        {
            _material.SetColor("_EdgeColor",edgeColor);
            _material.SetFloat("_EdgeOnly",edgeOnly);
            Graphics.Blit(src,dest,_material);
            
        }
        else
        {
            Graphics.Blit(src,dest); 
        }
        
    }

}

        Shader:

Shader "Custom/Test0"
{
    Properties
    {
        _MainTex("渲染纹理",2D)="white"{}
        //边缘颜色
        _EdgeColor("边缘颜色",Color)=(0,0,0,1)
        //仅显示边缘
        _EdgeOnly("边缘范围",float)=1.0
    }
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
            sampler2D _MainTex;                        
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;
            fixed _EdgeColor;
            fixed _EdgeOnly;        
            struct a2v
            {
                float4 vertex:POSITION;
                float2 texcoord:TEXCOORD0;
            };
 
            struct v2f
            {
                float4 pos:SV_POSITION;           
                float2 uv[9]:TEXCOORD0;
            
            };
            
            v2f vert(a2v v)
            {                
                v2f o;                                                                
                o.pos=UnityObjectToClipPos(v.vertex);
                //将纹理坐标计算放在顶点着色器中,由于传递是线性插值,所以并不会影响结果
                o.uv[0]=v.texcoord+_MainTex_TexelSize.xy*fixed2(-1,-1);
                o.uv[1]=v.texcoord+_MainTex_TexelSize.xy*fixed2(0,-1);
                o.uv[2]=v.texcoord+_MainTex_TexelSize.xy*fixed2(1,-1);
                o.uv[3]=v.texcoord+_MainTex_TexelSize.xy*fixed2(-1,0);
                o.uv[4]=v.texcoord+_MainTex_TexelSize.xy*fixed2(0,0);
                o.uv[5]=v.texcoord+_MainTex_TexelSize.xy*fixed2(1,0);
                o.uv[6]=v.texcoord+_MainTex_TexelSize.xy*fixed2(-1,1);
                o.uv[7]=v.texcoord+_MainTex_TexelSize.xy*fixed2(0,1);
                o.uv[8]=v.texcoord+_MainTex_TexelSize.xy*fixed2(1,1);
                
                return o;
                
            }
            
            float Sobel(v2f i)
            {
                fixed Gx[9]={-1,-2,-1,
                            0,0,0,
                            1,2,1};
                fixed Gy[9]={-1,0,1,
                            -2,0,2,
                            -1,0,1};
                half edgeX=0;
                half edgeY=0;
                for (int j=0;j<9;j++)
                {
                    //用0饱和度颜色进行卷积
                    half texColor=Luminance(tex2D(_MainTex,i.uv[j]));
                    edgeX+=texColor*Gx[j];
                    edgeY+=texColor*Gy[j];                    
                }
                return  1-abs(edgeX)-abs(edgeY);
            }
            
            fixed luminance(fixed4 color)
            {
                //得到对比度为0的颜色
                return 0.2125*color.r+0.7154*color.r+0.0721*color.b;
            }
 
            fixed4 frag(v2f i):SV_Target
            {
                float edge=Sobel(i);
                //卷积得到的边缘结果
                fixed4 edgeColor=lerp(_EdgeColor,tex2D(_MainTex,i.uv[4]),edge);               
                //控制是否只显示边缘,你不写这句话也没影响
                fixed4 edgeColor1=lerp(_EdgeColor,(1,1,1,1),edge);

                fixed4 color=lerp(edgeColor,edgeColor1,_EdgeOnly);
   
                return color;
            }
            
            ENDCG
        }
    }
}

可以看到,在花朵相连处并不会有边缘检测的结果。

四、高斯模糊

        在三中利用卷积实现了物体边缘检测,卷积还有另一个常见作用,高斯模糊。实现模糊的方法有很多种,例如均值模糊,中值模糊等等,但相对而言,高斯的效果会更好。

        高斯模糊卷积操作的卷积核,其计算依据是二维高斯滤波方程,这里使用的是5x5的卷积核,但如果直接使用二维卷积核采样,计算量非常大,高斯核可以被拆成两个一维核,一维核的计算依据是一维高斯滤波方程,数学证明不做说明。使用两个Pass,在行不变的情况下,对列进行卷积,列同理。得到的结果与二维卷积相同,可以有效降低计算量,但即便如此,计算量依然非常大。

        高斯模糊有一个最简单的写法,就是对渲染纹理只进行一次迭代,而且计算时也不用考虑优化问题(即降采样)。这里会放出不简单的写法。

        一个很容易理解的方式,一个像素点的颜色由周围像素点的颜色和本像素点的颜色共同决定。

        脚本:        

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

[ExecuteInEditMode]
public class RenderImage : MonoBehaviour
{
    public Shader shader;
    private Material _material;
    [Header("迭代次数")] [Range(0, 4)] public int iterations = 3;

    [Header("模糊范围")] [Range(0.2f, 3.0f)] public float blurArea = 0.6f;

    [Header("降采样")] [Range(1, 8)] private int downSample = 2;

    private void Awake()
    {
        if (shader == null)
        {
            //Debug.Log("Shader为空");
            return;
        }

        _material = new Material(shader);
    }

    private void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (_material != null)
        {
            //降采样纹理计算
            int rtW = src.width / downSample;
            int rtH = src.height / downSample;
            
            //申请缓存用于存放渲染纹理的空间
            RenderTexture buffer0 = RenderTexture.GetTemporary(rtW, rtH);

            //写不写均可,优化问题
            buffer0.filterMode = FilterMode.Bilinear;

            //实现降采样
            Graphics.Blit(src, buffer0);

            //实现高斯迭代,关于这里面的内存何时释放申请释放。
            //看不懂建议多翻翻引用,指针的使用。
            for (int i = 0; i < iterations; i++)
            {
                _material.SetFloat("_BlurArea", 1.0f + i * blurArea);

                RenderTexture buffer1 = RenderTexture.GetTemporary(rtW, rtH);
                
                Graphics.Blit(buffer0, buffer1, _material, 0);
                
                RenderTexture.ReleaseTemporary(buffer0);
                
                buffer0 = buffer1;
                
                buffer1 = RenderTexture.GetTemporary(rtW, rtH);
                
                Graphics.Blit(buffer0, buffer1, _material, 1);
                
                RenderTexture.ReleaseTemporary(buffer0);
                
                buffer0 = buffer1;
            }

            Graphics.Blit(buffer0, dest);
            RenderTexture.ReleaseTemporary(buffer0);
        }
        else
        {
            Graphics.Blit(src, dest);
        }
    }
}

        Shader:

Shader "Custom/Test0"
{
    Properties
    {
        _MainTex("渲染纹理",2D)="white"{}
        _BlurArea("模糊范围",float)=1.0

    }
    SubShader
    {
        //类似C++的头文件,可以减少重复代码    
        CGINCLUDE
        #include "UnityCG.cginc"

        sampler2D _MainTex;
        float4 _MainTex_TexelSize;
        float _BlurArea;

        struct a2v
        {
            float4 vertex:POSITION;
            float2 texcoord:TEXCOORD0;
        };

        struct v2f
        {
            float4 pos:SV_POSITION;
            float2 uv[5]:TEXCOORD0;
        };

        v2f vertVertical(a2v v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex);
            //将纹理坐标计算放在顶点着色器中,由于传递是线性插值,所以并不会影响结果
            o.uv[0] = v.texcoord;
            o.uv[1] = v.texcoord + float2(0, _MainTex_TexelSize.y * 1.0) * _BlurArea;
            o.uv[2] = v.texcoord - float2(0, _MainTex_TexelSize.y * 1.0) * _BlurArea;
            o.uv[3] = v.texcoord + float2(0, _MainTex_TexelSize.y * 2.0) * _BlurArea;
            o.uv[4] = v.texcoord - float2(0, _MainTex_TexelSize.y * 2.0) * _BlurArea;

            return o;
        }

        v2f vertHorizontal(a2v v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos(v.vertex);
            //注意这里是x方向的偏移
            o.uv[0] = v.texcoord;
            o.uv[1] = v.texcoord + float2(_MainTex_TexelSize.x * 1.0, 0) * _BlurArea;
            o.uv[2] = v.texcoord - float2(_MainTex_TexelSize.x * 1.0, 0) * _BlurArea;
            o.uv[3] = v.texcoord + float2(_MainTex_TexelSize.x * 2.0, 0) * _BlurArea;
            o.uv[4] = v.texcoord - float2(_MainTex_TexelSize.x * 2.0, 0) * _BlurArea;

            return o;
        }

        fixed4 frag(v2f i):SV_Target
        {
            float weight[3] = {0.4026, 0.2442, 0.0545};
            fixed3 color = tex2D(_MainTex, i.uv[0]) * weight[0];
            //权重计算
            for (int j = 1; j < 3; j++)
            {
                color += tex2D(_MainTex, i.uv[j * 2 - 1]) * weight[j];
                color += tex2D(_MainTex, i.uv[j * 2]) * weight[j];
            }
            return fixed4(color, 1);
        }
        ENDCG
        

        Pass
        {
            NAME "GAUSSIAN_VERTICAL"
            CGPROGRAM
            #pragma vertex vertVertical
            #pragma fragment frag
            ENDCG
        }
        Pass
        {
            NAME "GAUSSIAN_HORIZONTAL"
            CGPROGRAM
            #pragma vertex vertHorizontal
            #pragma fragment frag
            ENDCG
        }
    }
}

结果:

 五、Bloom效果(泛光、光晕)

        根据阈值提取纹理中较亮的区域,并存储在一张渲染纹理中,然后进行模糊处理,最后再和原图像混合,模拟光线扩散,实现泛光。

        脚本:

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

[ExecuteInEditMode]
public class RenderImage : MonoBehaviour
{
    public Shader shader;
    private Material _material;
    [Header("迭代次数")] [Range(0, 4)] public int iterations = 3;

    [Header("模糊范围")] [Range(0.2f, 3.0f)] public float blurArea = 0.6f;

    [Header("降采样")] [Range(1, 8)] private int downSample = 2;

    [Header("泛光区域")] [Range(0, 1)] public float bloomArea;

    private void Awake()
    {
        if (shader == null)
        {
            //Debug.Log("Shader为空");
            return;
        }

        _material = new Material(shader);
    }

    private void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (_material != null)
        {
            _material.SetFloat("_BloomArea",bloomArea);

            int rtW = src.width / downSample;
            int rtH = src.height / downSample;

            RenderTexture buffer0 = RenderTexture.GetTemporary(rtW, rtH);
            
            buffer0.filterMode = FilterMode.Bilinear;
            //提取降采样后的高亮区域
            Graphics.Blit(src, buffer0,_material,0);
            
            for (int i = 0; i < iterations; i++)
            {
                _material.SetFloat("_BlurArea", 1.0f + i * blurArea);

                RenderTexture buffer1 = RenderTexture.GetTemporary(rtW, rtH);
                
                Graphics.Blit(buffer0, buffer1, _material, 1);
                
                RenderTexture.ReleaseTemporary(buffer0);
                
                buffer0 = buffer1;
                
                buffer1 = RenderTexture.GetTemporary(rtW, rtH);
                
                Graphics.Blit(buffer0, buffer1, _material, 2);
                
                RenderTexture.ReleaseTemporary(buffer0);
                
                buffer0 = buffer1;
            }
            //此时buffer0中存放着模糊处理后的高亮区域
            //然后与原图像结混合
            _material.SetTexture("_BloomTex",buffer0);
            Graphics.Blit(src, dest,_material,3);
            RenderTexture.ReleaseTemporary(buffer0);
        }
        else
        {
            Graphics.Blit(src, dest);
        }
    }
}

        Shader:        

Shader "Custom/Test0"
{
    Properties
    {
        _MainTex("渲染纹理",2D)="white"{}
        _BlurArea("模糊范围",float)=1.0
        _BloomArea("泛光区域",float)=1.0
        _BloomTex("泛光纹理",2D)="white"{}
    }
    SubShader
    {
        CGINCLUDE
        #include "UnityCG.cginc"

        sampler2D _MainTex;
        float4 _MainTex_TexelSize;
        float _BlurArea;
        float _BloomArea;
        sampler2D _BloomTex;

        struct a2v
        {
            float4 vertex:POSITION;
            float2 texcoord:TEXCOORD0;
        };

        struct v2fGaussian
        {
            float4 pos:SV_POSITION;
            float2 uv[5]:TEXCOORD0;
        };

        struct v2fBloom
        {
            float4 pos:SV_POSITION;
            float2 uv:TEXCOORD0;
        };

        struct v2fBlend
        {
            float4 pos:SV_POSITION;
            float4 uv:TEXCOORD0;
        };

        fixed luminance(fixed4 color)
        {
            return 0.2125 * color.r + 0.7154 * color.r + 0.0721 * color.b;
        }

        v2fBloom vert_Bloom(a2v v)
        {
            v2fBloom o;
            o.pos = UnityObjectToClipPos(v.vertex);
            o.uv = v.texcoord;
            return o;
        }

        v2fGaussian vertVertical(a2v v)
        {
            v2fGaussian o;
            o.pos = UnityObjectToClipPos(v.vertex);
            //将纹理坐标计算放在顶点着色器中,由于传递是线性插值,所以并不会影响结果
            o.uv[0] = v.texcoord;
            o.uv[1] = v.texcoord + float2(0, _MainTex_TexelSize.y * 1.0) * _BlurArea;
            o.uv[2] = v.texcoord - float2(0, _MainTex_TexelSize.y * 1.0) * _BlurArea;
            o.uv[3] = v.texcoord + float2(0, _MainTex_TexelSize.y * 2.0) * _BlurArea;
            o.uv[4] = v.texcoord - float2(0, _MainTex_TexelSize.y * 2.0) * _BlurArea;

            return o;
        }

        v2fGaussian vertHorizontal(a2v v)
        {
            v2fGaussian o;
            o.pos = UnityObjectToClipPos(v.vertex);
            //注意这里是x方向的偏移
            o.uv[0] = v.texcoord;
            o.uv[1] = v.texcoord + float2(_MainTex_TexelSize.x * 1.0, 0) * _BlurArea;
            o.uv[2] = v.texcoord - float2(_MainTex_TexelSize.x * 1.0, 0) * _BlurArea;
            o.uv[3] = v.texcoord + float2(_MainTex_TexelSize.x * 2.0, 0) * _BlurArea;
            o.uv[4] = v.texcoord - float2(_MainTex_TexelSize.x * 2.0, 0) * _BlurArea;

            return o;
        }

        v2fBlend vert_Blend(a2v v)
        {
            v2fBlend o;
            o.pos = UnityObjectToClipPos(v.vertex);
            o.uv.xy = v.texcoord;
            o.uv.zw = v.texcoord;
            return o;
        }

        fixed4 frag_Bloom(v2fBloom i):SV_Target
        {
            fixed4 texResult = tex2D(_MainTex, i.uv);
            fixed val = clamp(luminance(texResult) - _BloomArea, 0, 1);
            return texResult * val;
        }

        fixed4 frag(v2fGaussian i):SV_Target
        {
            float weight[3] = {0.4026, 0.2442, 0.0545};
            fixed3 color = tex2D(_MainTex, i.uv[0]) * weight[0];
            //权重计算
            for (int j = 1; j < 3; j++)
            {
                color += tex2D(_MainTex, i.uv[j * 2 - 1]) * weight[j];
                color += tex2D(_MainTex, i.uv[j * 2]) * weight[j];
            }
            return fixed4(color, 1);
        }

        fixed4 frag_Blend(v2fBlend i):SV_Target
        {
            return tex2D(_MainTex, i.uv.xy) + tex2D(_BloomTex, i.uv.zw);
        }
        ENDCG


        //用于高亮区域提取
        Pass
        {
            CGPROGRAM
            #pragma vertex vert_Bloom
            #pragma fragment frag_Bloom
            ENDCG
        }
        //以下两个用于高亮区域模糊
        Pass
        {
            NAME "GAUSSIAN_VERTICAL"
            CGPROGRAM
            #pragma vertex vertVertical
            #pragma fragment frag
            ENDCG
        }
        Pass
        {
            NAME "GAUSSIAN_HORIZONTAL"
            CGPROGRAM
            #pragma vertex vertHorizontal
            #pragma fragment frag
            ENDCG
        }
        //用于高亮模糊与原图像混合
        Pass
        {
            CGPROGRAM
            #pragma vertex vert_Blend
            #pragma fragment frag_Blend
            ENDCG
        }
    }
}

 原图像:

泛光效果:

         

        不知道是不是图片原因,效果感觉没有想象中的好 。

        而且这个Bloom写法还有一些问题,大致就是亮度提取那里,会受到其他物体或场景灯光的影响,有时比如说一个发光的球体,它可能只会提取球的上半部分进行模糊。目前想到的是分层处理。待实验。       

六、运动模糊

        一是累积缓存,入门精要中的解释没看懂,感觉这种实现怪怪的。二是速度缓存,计算出像素的速度,用这个模糊。三是保存上一帧的渲染纹理,然后的把当前帧的纹理叠加上去。

       内容不展示了。

        书上运动模糊写的有问题,混合是一直在进行的,物体的运动轨迹会一直出现,不会消失,除非你模糊程度降低。

 可以看到周围一圈之前的运动轨迹一直存在。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值