Advertisement
lunoland

Unity/HLSL Pixel Shader Dithering

Feb 26th, 2017
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. // @lunoland's modification of code provided by Shadertoy users hornet and TomF (see shadertoy.com/view/4t2SDh)
  2.  
  3. // Generate a uniformly distributed random coordinate between (0, 0) and (1, 1); you can use UVs as input.
  4. float2 random_coord(float2 input) {
  5. return frac(sin(dot(input + frac(_Time.y) * 0.07, float2(12.9898, 78.233))) * 43758.5453);
  6. }
  7.  
  8. // Take the resulting color you get from randomly sampling a pre-calculated blue noise texture and remap it to a
  9. // triangle-shaped distribution in the range of [-0.5, 1.5].
  10. half4 tri_dist(half4 input) {
  11. input = input * 2 - 1;
  12. half4 result = original * rsqrt(abs(input));
  13. result = max(-1, result); // Handle the NaN that results from 0 * rsqrt(0)
  14. return result - sign(input) + 0.5;
  15. }
  16.  
  17. // In your fragment shader, you can add some noise to the final color like so:
  18. sampler2D _NoiseTex; // Add this texture in the properties block and assign it a pre-calculated blue noise texture (16x16 works fine) from http://momentsingraphics.de/Media/BlueNoise/FreeBlueNoiseTextures.zip
  19. half4 frag (v2f input) : SV_Target {
  20.  
  21. // ...whatever operations you do to get your final color go here
  22.  
  23. // Sample the pre-calculated blue noise texture at random, and then remap the resulting color to the triangular distribution
  24. half4 noise = tri_dist( tex2D(_NoiseTex, rand(input.uv)) ) / 255; // add 2 bits of triangularly distributed noise (1 / 255 = 1 bit, 1.5 - -0.5 = 2)
  25. return color + noise;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement