Skip to content

Instantly share code, notes, and snippets.

@forestrf
Forked from Fewes/PixelDot.shader
Created October 10, 2020 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forestrf/6ba26eeb41353253b93355eeb0d9bc77 to your computer and use it in GitHub Desktop.
Save forestrf/6ba26eeb41353253b93355eeb0d9bc77 to your computer and use it in GitHub Desktop.
Renders a screen-aligned, distance-independent, resolution-independent, pixel-perfect quad in Unity. Use it with the built-in quad mesh. You don't have to rotate or scale the mesh renderer, the shader will take care of it.
Shader "FX/PixelDot"
{
Properties
{
[NoScaleOffset] _MainTex ("Texture", 2D) = "white" {}
_Color ("Color", Color) = (1, 1, 1, 1)
_Size ("Pixel Size", Range(1, 64)) = 1
}
SubShader
{
Tags { "RenderType"="Opaque" "Queue"="Geometry" }
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_instancing
#include "UnityCG.cginc"
struct v2f
{
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
float4 _Color;
float _Size;
v2f vert (appdata_full v)
{
UNITY_SETUP_INSTANCE_ID(v);
v2f o;
UNITY_INITIALIZE_OUTPUT(v2f, o);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Extract the world space position of the mesh renderer from the model matrix
float3 worldPos = float3(UNITY_MATRIX_M._m03, UNITY_MATRIX_M._m13, UNITY_MATRIX_M._m23);
// Transform to clip space
float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0f));
// Pixel snapping based on UnityPixelSnap from UnityCG.cginc
float2 hpc = _ScreenParams.xy * 0.5f;
float2 pixelPos = round((clipPos.xy / clipPos.w) * hpc);
// Expand from a point to a quad using the texture coordinates
pixelPos += (v.texcoord.xy-0.5) * _Size * float2(1, -1);
// Pixel position back to clip space
clipPos.xy = pixelPos / hpc * clipPos.w;
o.vertex = clipPos;
o.texcoord = v.texcoord;
return o;
}
float4 frag (v2f i) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(i);
return tex2D(_MainTex, i.texcoord) * _Color;
}
ENDCG
}
}
// This will enable basic depth buffer writes
Fallback "Diffuse"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment