Skip to content

Instantly share code, notes, and snippets.

@andrewgotow
Last active February 22, 2019 17:18
Show Gist options
  • Save andrewgotow/526a35671734d4537c5eca3caf79d844 to your computer and use it in GitHub Desktop.
Save andrewgotow/526a35671734d4537c5eca3caf79d844 to your computer and use it in GitHub Desktop.
Post-process shader for separable gaussian blur with linear sampling.
Shader "Postprocess/Simple Blur"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
CGINCLUDE
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_TexelSize;
// Performs a guassian blur on MainTex in one dimension.
//
// Gaussian blurs, box blurs, and many other simple convolutions are "seperable".
// Performing a 1D blur horizontally, and then another vertically on the result
// is the same as performing a blur over the whole kernel! Exploiting this, we can
// take our blur from n^2 to 2*n texture samples!
//
// This uses a linear sampling approach which exploits hardware bilinear filtering
// to take two blur samples at once.
//
// More info about this technique can be found here.
// http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/
fixed4 blur(float2 uv, float2 dir) {
const float offset[3] = { 0.0, 1.3846153846, 3.2307692308 };
const float weight[3] = { 0.2270270270, 0.3162162162, 0.0702702703 };
// Take our input direction and scale it down to a 1px step.
float2 step = dir * _MainTex_TexelSize.xy;
fixed4 col = tex2D( _MainTex, uv ) * weight[0];
// Might want to double-check that this loop is unrolled. You may get slightly
// better performance if you unroll this loop, and unpack the constants.
for (int i=1; i<3; i++) {
col += tex2D( _MainTex, uv - step * offset[i] ) * weight[i];
col += tex2D( _MainTex, uv + step * offset[i] ) * weight[i];
}
return col;
}
ENDCG
Pass
{
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag_horz
fixed4 frag_horz (v2f_img i) : SV_Target
{
return blur(i.uv, float2(1,0));
}
ENDCG
}
Pass
{
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag_vert
fixed4 frag_vert (v2f_img i) : SV_Target
{
return blur(i.uv, float2(0,1));
}
ENDCG
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment