Unityshader Example 11: Screen effect mosaic (Mosaic) material

Source: Internet
Author: User

Mosaic (Mosaic) material



Overview


Mosaic (Mosaic), it is estimated that everyone is usually the most annoying image processing means, hey, yes, I said is "playing code." All right, seriously, Mosaic refers to the current widely used image (video) processing means, this means the image of specific areas of the color scale details deterioration and cause the effect of color block disruption, because the blur appears to have a small lattice composition, the image is called this picture mosaic. The goal is usually to make the image large-scale to reduce the image () video resolution, and let the image (video) Some details hidden, make it illegible, generally used to protect privacy, or hide some unhealthy images.
principle

To achieve the effect of the mosaic, the picture needs to be a fairly large square area with the color of the same point, the equivalent of the continuous color discretization, so we can think of the method of rounding out the discrete color, but in our image texture coordinate sampling in the 0 to 1 continuous range, So we need to convert the texture coordinates to the actual size of the integer coordinates, next to the image this coordinate quantization discrete, for example, for a picture resolution of 256x256 pixels, the size of the mosaic block is 8x8 pixels, we must first multiply the texture coordinates (256,256) to map to 0 to 256 of the range , equivalent to an integer representing a pixel, then rounding the texture coordinates by 8, and then multiplying the coordinates by 8, divided by 256. Remap the range back to 0 to 1, but the texture coordinates are already discrete, not contiguous.

Shader Code Implementation


To the code implementation part, if the above principle is about the dizzy students or directly look at the code it (forgive me, science students, composition has never been done). First, you have to declare a mosaic-sized parameter in the attribute.


Properties {_maintex ("Base (RGB)", 2D) = "White" {}_mosaicsize ("mosaicsize", int) =5}


then declare a built-in four-dollar variable _maintex_texelsize, which literally means the _maintex pixel size of the main map, is a four-dollar number with a value of Vector4 (1/width, 1/height, Width, height); This is the unity of the Black magic, do not know where the definition of the official documents do not explain, there are known users can tell me in the reply.
Half4 _maintex_texelsize;



because the mosaic is for pixel operation, the key code is also implemented in the Frag function:


Float2 UV = (I.TEXCOORD*_MAINTEX_TEXELSIZE.ZW);//map texture coordinates to the size of the resolution UV = Floor (uv/_mosaicsize) *_mosaicsize;// Rounding I.texcoord =uv*_maintex_texelsize.xy;//the coordinates back to 0,1 within the range of the mosaic block size fixed4 col = tex2d (_maintex, I.texcoord);


Shader Complete Code

VF Version Code
Shader "PENGLU/UNLIT/MOSAICVF" {Properties {_maintex ("Base (RGB)", 2D) = "White" {}_mosaicsize ("mosaicsize", int) =5} Subshader {Tags {"rendertype" = "Opaque"}lod 100Pass {cgprogram#pragma vertex vert#pragma fragment  frag#include "Uni Tycg.cginc "struct appdata_t {float4 vertex:position;float2 texcoord:texcoord0;}; struct V2F {float4 vertex:sv_position;half2 texcoord:texcoord0;}; sampler2d _maintex;float4 _maintex_st;half4 _maintex_texelsize;int _mosaicsize;v2f vert (appdata_t v) {v2f O;o.vertex = Mul (UNITY_MATRIX_MVP, V.vertex); O.texcoord = Transform_tex (V.texcoord, _maintex); return o;} Fixed4 Frag (v2f i): sv_target{float2 UV = (I.TEXCOORD*_MAINTEX_TEXELSIZE.ZW); UV = Floor (uv/_mosaicsize) *_mosaicsize;i. Texcoord =uv*_maintex_texelsize.xy;fixed4 col = tex2d (_maintex, I.texcoord); Unity_opaque_alpha (COL.A); return col;} ENDCG}}}

VF Version Code 01 effect:



C # script code
to make screen effects, but also need to script the match, here do not explain too much, the important part of the script has comments, need to pay attention to a few functions, the specific use of the official documents ( here and here )

Onrenderimage (rendertexture sourcetexture, Rendertexture desttexture)

Graphics.blit (Sourcetexture, desttexture,material)

Graphics.blit (Sourcetexture, desttexture);


The complete C # script is as follows:


Using unityengine;using system.collections;using System; [Executeineditmode] [Addcomponentmenu ("Penglu/imageeffect/mosaic")]public class Imageeffect_mosaic:monobehaviour {#region Variablespublic Shader mosaicshader = null;private Material mosaicmaterial = null;public int mosaicsize = 8; #endregion//Create Material and shadermaterial material{get{if (mosaicmaterial = = null) {mosaicmaterial = new material (mosaicshader); Mosaicmaterial.hideflags = Hideflags.hideanddontsave;} return mosaicmaterial;}} Use the This for Initializationvoid Start () {Mosaicshader = Shader.find ("PENGLU/UNLIT/MOSAICVF");//Disable If we don t su Pport Image Effectsif (!            systeminfo.supportsimageeffects) {enabled = false;        Return }//Disable The image effect if the shader can ' t//run on the Users graphics card if (! Mosaicshader | | !            mosaicshader.issupported) enabled = FALSE; return;} void Onrenderimage (Rendertexture sourcetexture, rendertexture desttexture) {if (mosaicsize > 0 && mosaicshader! = null) {material. Setint ("_mosaicsize", mosaicsize);//Pass the mosaic size to shader Graphics.blit (Sourcetexture, desttexture,material); The captured image is passed to the GPU and processed by shader, which is transmitted back to}else{graphics.blit (Sourcetexture, desttexture);}} Update is called once per framevoid Update () {#if Unity_editorif (application.isplaying!=true) {Mosaicshader = Shader.f IND ("PENGLU/UNLIT/MOSAICVF");}    #endif} public void Ondisable () {if (mosaicmaterial) destroyimmediate (mosaicmaterial); }}



Mosaic effect Variants

in the process of online data search, but also see some very interesting mosaic algorithm variants, here I only put their key code and implementation of the results, we can understand their own production.

round mosaic
Key code:

Float2 Intuv = (I.TEXCOORD*_MAINTEX_TEXELSIZE.ZW); Float2 XYUV = Floor (intuv/_mosaicsize) *_mosaicsize+0.5*_mosaicsize ; Float dissample = Length (XYUV-INTUV); Float2 MOSAICUV = xyuv*_maintex_texelsize.xy;fixed4 col = tex2d (_maintex, I.texcoord); if (dissample<0.5*_mosaicsize) col = tex2d (_MAINTEX,MOSAICUV);


Code Effects:




positive hexagon (honeycomb) Mosaicalgorithm principle Reference here and here , I did a little simplification, reduced some of the mathematical operations to support Tanget 2.0, the algorithm is not difficult to understand, but it is still very difficult to think out, so I admire the original author, This shows that mathematics in the shader programming is still quite important;

Key code:

const float TR = 0.866025f;//tr=√3float2 Xyuv = (I.TEXCOORD*_MAINTEX_TEXELSIZE.ZW); int wx = int (xyuv.x/1.5f/_mosaicsize) ; int wy = int (xyuv.y/tr/_mosaicsize); Float2 v1,v2;float2 wxy =float2 (Wx,wy); if (WX/2*2==WX) {if (Wy/2*2==wy) {v1 = Wxy;v2 = wxy+1;} ELSE{V1 = WXY+FLOAT2 (0,1); v2 = Wxy+float2 (1,0);}} Else{if (wy/2*2 = = WY) {v1 = WXY+FLOAT2 (0,1); v2 = Wxy+float2 (1,0);} ELSE{V1 = Wxy;v2 = wxy+1;}} V1 *= float2 (_MOSAICSIZE*1.5F,_MOSAICSIZE*TR); v2 *= float2 (_mosaicsize*1.5f,_mosaicsize*tr); float S1 = Length ( V1.XY-XYUV.XY); float s2 = length (v2.xy-xyuv.xy); Fixed4 col = tex2d (_maintex,v2*_maintex_texelsize.xy); if (S1 < S2)  col = tex2d (_maintex,v1*_maintex_texelsize.xy);  



Code effects:


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Unityshader Example 11: Screen effect mosaic (Mosaic) material

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.