Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Issue with a blur shader

Discussion in 'Shaders' started by jacasch, Feb 17, 2017.

  1. jacasch

    jacasch

    Joined:
    Jan 20, 2017
    Posts:
    16
    Hello :) Im pretty new to shader programming. So I tried to create a shader that blurrs everything behind a certain Object.
    This version is just a simple implementation of a box blur with an offset.

    Shader "Custom/Blur" {
    Properties{
    _Offset("Offset", Range(0,1)) = 0
    }
    SubShader{
    GrabPass{
    }

    Pass{
    Tags{ "Queue" = "Transparent" }

    CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag
    #include "UnityCG.cginc"

    struct v2f {
    half4 pos : SV_POSITION;
    half4 grabPos : TEXCOORD0;
    };

    sampler2D _GrabTexture;
    half _Offset;

    v2f vert(appdata_base v) {
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    o.grabPos = ComputeGrabScreenPos(o.pos);
    return o;
    }

    float4 gauss(sampler2D tex, half4 projCoord, float4 size)
    {
    float4 c = tex2Dproj(tex, projCoord + half4(-size.x, size.y,0.0,0.0)) +
    tex2Dproj(tex, projCoord + half4(0, size.y, 0.0, 0.0)) +
    tex2Dproj(tex, projCoord + half4(size.x, size.y, 0.0, 0.0)) +
    tex2Dproj(tex, projCoord + half4(-size.x, 0, 0.0, 0.0)) +
    tex2Dproj(tex, projCoord + half4(0, 0, 0.0, 0.0)) +
    tex2Dproj(tex, projCoord + half4(size.x, 0, 0.0, 0.0)) +
    tex2Dproj(tex, projCoord + half4(-size.x, -size.y, 0.0, 0.0)) +
    tex2Dproj(tex, projCoord + half4(0, -size.y, 0.0, 0.0)) +
    tex2Dproj(tex, projCoord + half4(size.x, -size.y, 0.0, 0.0));
    return c / 9;
    }

    half4 frag(v2f i) : COLOR{
    float4 col = gauss(_GrabTexture, UNITY_PROJ_COORD(i.grabPos), _Offset);
    return col;
    }
    ENDCG
    }
    }
    FallBack "Diffuse"
    }

    I want the boxblur to be always offset by the Offset value in pixels, but somehow it seems to depend on how far the camera is from the Object with the blur shader.

    I think It has something to do with

    UNITY_PROJ_COORD(i.grabPos)

    or

    o.grabPos = ComputeGrabScreenPos(o.pos);

    I dont fully Understand what they are doing.

    Make sure to set the render Queue above 2500 for it to work properly