Skip to content

Instantly share code, notes, and snippets.

@tiagosr
Last active October 31, 2023 10:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tiagosr/2b4a71ca23800f0ad6bc to your computer and use it in GitHub Desktop.
Save tiagosr/2b4a71ca23800f0ad6bc to your computer and use it in GitHub Desktop.
Unity3D point-sampled shader with subpixel multisampling
Shader "esque.ma/Anti-Aliased Point-Sampled"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Feather ("Feather", Range(0.1, 0.9)) = 0.25
_Ratio ("Ratio", Range(0.0, 0.25)) = 0.15
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
// to be able to use derivatives in the fragment shader
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Ratio;
float _Feather;
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// screen-space derivatives
float ddxx = ddx(i.uv.x);
float ddxy = ddx(i.uv.y);
float ddyx = ddy(i.uv.x);
float ddyy = ddy(i.uv.y);
// 5-point sampling
// sampling pattern is a cross around the center of the pixel
// different configurations will give different results
float2 p1 = float2(ddxx+ddyx, ddxy+ddyy)*_Feather;
float2 p2 = float2(ddxx+ddyx, -(ddxy+ddyy))*_Feather;
float2 p3 = float2(-(ddxx+ddyx), ddxy+ddyy)*_Feather;
float2 p4 = float2(-(ddxx+ddyx), -(ddxy+ddyy))*_Feather;
fixed4 col = tex2D(_MainTex, i.uv) * (1.0-4.0*_Ratio) + tex2D(_MainTex, i.uv+p1)*_Ratio + tex2D(_MainTex, i.uv+p2)*_Ratio + tex2D(_MainTex, i.uv+p3)*_Ratio + tex2D(_MainTex, i.uv+p4)*_Ratio;
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment