美文网首页
像素效果——Shader屏幕后处理效果

像素效果——Shader屏幕后处理效果

作者: LEO_青蛙 | 来源:发表于2020-06-09 21:20 被阅读0次
    像素效果

    GitHub项目地址

    屏幕后处理效果即在渲染完场景得到屏幕图像后,再进行处理的效果。
    Unity Shader中的Pass是按照顺序执行的,如果需要使用一个Pass的处理结果作为另一个Pass的输入,这个时候就需要用到OnRenderImage()函数了。
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    [ExecuteInEditMode]
    public class Pixelate : MonoBehaviour
    {
        // Start is called before the first frame update
        public Material effectMaterial;
    
        private void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            Graphics.Blit(source, destination, effectMaterial);
        }
    }
    

    像素效果的原理:定义一个行数变量_Rows和一个列数变量_Columns,将uv分别乘以这两个变量,取整,再除以这两个变量。这样一定范围内的像素点就会取到相同的颜色值,从而实现像素效果。

    Shader "Custom/PixelateShader"
    {
        Properties
        {
            _MainTex("Texture", 2D) = "white" {}
            _Columns("Pixel Columns",Float) = 64
            _Rows("Pixel Rows",Float) = 64
    
        }
            SubShader
            {
                // No culling or depth
                Cull Off ZWrite Off ZTest Always
    
                Pass
                {
                    CGPROGRAM
                    #pragma vertex vert
                    #pragma fragment frag
    
                    #include "UnityCG.cginc"
    
                    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;
                    }
    
                    sampler2D _MainTex;
                    float _Columns;
                    float _Rows;
    
                    fixed4 frag(v2f i) : SV_Target
                    {
                        float2 uv = i.uv;
                        uv.x *= _Columns;
                        uv.y *= _Rows;
                        uv.x = round(uv.x);
                        uv.y = round(uv.y);
                        uv.x /= _Columns;
                        uv.y /= _Rows;
                        fixed4 col = tex2D(_MainTex, uv);
                        return col;
                    }
                    ENDCG
                }
            }
    }
    

    相关文章

      网友评论

          本文标题:像素效果——Shader屏幕后处理效果

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