Advertisement
Gary_Keen27

Greyscale Filter

Nov 2nd, 2016
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ////////////////////////////////////////////////
  2. ////////////////////CPU SIDE////////////////////
  3. ////////////////////////////////////////////////
  4. using UnityEngine;
  5. using System.Collections;
  6.  
  7. [ExecuteInEditMode]
  8. public class Greyscale : MonoBehaviour
  9. {
  10.  
  11.     public float intensity;
  12.     private Material material;
  13.  
  14.     void Awake()
  15.     {
  16.         material = new Material(Shader.Find("My Shaders/Greyscale")); //Use the shader.
  17.     }
  18.  
  19.     void OnRenderImage(RenderTexture source, RenderTexture destination) //Before the buffer is sent to the camera, modify it with above shader.
  20.     {
  21.         if (intensity == 0)
  22.         {
  23.             Graphics.Blit(source, destination); //Intensity is 0. Blit the image straight to the screen.
  24.             return;
  25.         }
  26.  
  27.         material.SetFloat("_Scale", intensity); //Uniform the value to the shader.
  28.         Graphics.Blit(source, destination, material); //Blit the modified image to the screen.
  29.     }
  30. }
  31.  
  32. ////////////////////////////////////////////////
  33. ////////////////////GPU SIDE////////////////////
  34. ////////////////////////////////////////////////
  35. Shader "My Shaders/Greyscale"
  36. {
  37.     Properties
  38.     {
  39.         _MainTex ("Buffer", 2D) = "white" {}
  40.         _Scale ("Intensity", Range (0, 1)) = 0
  41.     }
  42.     SubShader
  43.     {
  44.         Pass
  45.         {
  46.             CGPROGRAM
  47.             #pragma vertex vert_img //Standard vertex shader as we don't need to make a custom one.
  48.             #pragma fragment frag
  49.  
  50.             #include "UnityCG.cginc"
  51.  
  52.             uniform sampler2D _MainTex;
  53.             uniform float _Scale;
  54.  
  55.             float4 frag(v2f_img input) : COLOR
  56.             {
  57.                 float4 textureMap = tex2D(_MainTex, input.uv);
  58.                
  59.                 float lum = textureMap.r * 0.2126 + textureMap.g * 0.7152 + textureMap.b * 0.0722; //Standard values for HDTV greyscale calibration. It is important that each channel is modified by a seperate amount due to luminosity.
  60.                 float3 greyscale = float3(lum, lum, lum); //A vec3 result of the above.
  61.                
  62.                 float4 result = textureMap;
  63.                 result.rgb = lerp(textureMap.rgb, greyscale, _Scale); //Mix between the original buffer and the greyscale modification based off the weight of _Scale.
  64.                 return result;
  65.             }
  66.             ENDCG
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement