Posterize function in Shader
// equal to what's done in c# to round numbers with x decimals float PosterizeF(float value, float steps) { // rounds value to the nearest integer not greater than value return floor(value * steps) / steps; } float PosterizeR(float value, float steps) { // rounds value to the nearest integer return round(value * steps) / steps; } float3 frag(v2f i) : SV_Target { float2 uv = i.uv0; float3 colorA = float3(1, 0, 0); float3 output = PosterizeF(uv.yyy, 8); return float3(output * colorA); }
Various exercises
Properties { // base texture _MainTex("Texture", 2D) = "white" {} // second texture to tween _SecondTex("Second Texture", 2D) = "white" {} // tint color _Tint("Tint", Color) = (1,1,1,1) // slider to tween the textures _Tween("Tween", Range(0,1)) = 0 } SubShader { // indicates that it gets rendered after all opaque objects Tags {"Queue"="Transparent"} Pass { // uses the alpha of the texture // This syntax is: Blend SrcFactor DstFactor // Blend is off by default // The color generated by frag is multiplied by SrcFactor (in this case the alpha) // if alpha is 0, generated col doesn't display (multiplied by 0) // the color that's already on screen gets multiplied by (1 - SrcAlpha) // if alpha is 0, DstCol alpha's 1 // then they get added together Blend SrcAlpha OneMinusSrcAlpha sampler2D _MainTex; sampler2D _SecondTex; float4 _MainTex_ST; float4 _Tint; float _Tween; float4 frag(v2f i) : SV_Target { // multiplies the uv, tiling the texture float2 tiledUv = i.uv * 2; // defines both textures to the uv float4 mainCol = tex2D(_MainTex, tiledUv); float4 secondCol = tex2D(_SecondTex, tiledUv); // tweens between those with a lerp, _Tween as t float4 tweenCol = lerp(mainCol, secondCol, _Tween); // tints a texture float4 tintedTexture = mainCol * _Tint; // tints the texture with the uv color float4 uvTintedTexture = float4(mainCol * tiledUv, 0, mainCol.a); // calculates the luminance value for each pixel of a texture float luminance = float((mainCol.r * 0.22) + (mainCol.g * 0.72) + (mainCol.b * 0.06)); // assigns the calculated pixel to each channel of the desaturated texture float4 desaturatedTexture = float4(luminance, luminance, luminance, mainCol.a); return desaturatedTexture; }
Post-process with Shader
// so when can debug the effect without playing [ExecuteInEditMode] public class Effects : MonoBehaviour { // material that's going to be used to assign effects // the RenderTexture of the camera will go to _MainTex [SerializeField] Material fxMat; // called after all rendering is complete // used for post-processing // takes the source texture (rendered image) // and a destination (where it's rendered, for example the screen) void OnRenderImage(RenderTexture source, RenderTexture destination) { // takes the source texture, and copies it to the destination // using a material to do some processing first Graphics.Blit(source, destination, fxMat); } }
Share this