Unity3d shader the way to write shader before you must know the summary of the rendering pipeline

Source: Internet
Author: User
Tags unity 5

Version: Unity 5.4.1 Language: Unity Shader

Total from:

It took the last one months to put the Unity Shader Essentials "After reading, not how to write blog, because the writing is too good, see a bit sleepless, again strongly recommended.

today to write Shader before you must know the rendering pipeline to summarize, and then a simple combination of vertex \ Element shader shader, say that each code in the pipeline location, as well as the responsibility function.

Rendering Pipeline:

in writing Unity script, whether it is C # or JS, is to deal with the CPU, do arithmetic operations, call class members, control program flow. Instead of writing shader, he is dealing with the GPU.

Let's take a look at the script's invocation process: (Baidu has Chinese translation, my side directly on the official website)https://docs.unity3d.com/Manual/ExecutionOrder.html

from here, one of the first frames in the game is initialization, which is Awake, onenable, start the execution of these functions, and then the execution of physics, input, game logic, writing code in unity all the while working with these functions? Next we see scene Rendering, here is the most important part of the rendering: by the CPU issued instructions (that is, the usual drawcall), GPU response instructions to render, the execution is a rendering pipeline.

and Shader in which a rendering pipeline is controlled to tell Gpu,cpu how to render the object it passes over. Superficially speaking, shader is to the GPU, just as C # is to the CPU.

So what is the process of rendering a pipeline? The simple point is:" top of a few cutting screen, 33 pieces by screen ."

This is a simple way of remembering, and it feels pretty good to be useful.

The first line is the geometry stage: vertex shader, surface subdivision shader, geometry shader, crop-and-screen mapping. The main task is to transform each vertex of the model into a space in the screen coordinates to prepare for the actual rendering.

the second line is the rasterization phase: triangle traversal, triangle traverse, slice shader-per-slice operation, screen image. This stage is really a display of pixels on the screen.

a simple Shader:

This way, we can simply talk about the function of various parts of the pipeline through the example in the book.

Shader "Unity Shaders book/chapter 5/simple Shader" {//Displays properties on Unity Inspector, gives the user control//form: Property name ("Inspector displayed label", property type) = Initialize data Properties {//This is a color, initialized to (1,1,1,1), displays a color Tint on inspector, and _color is used in shader to invoke _color ("Color Tint", color ) = (1, 1, 1, 1)}//Shader's control code is in pass, a subshader may contain multiple pass//depending on the control code may call all passes, or may only call one//Now we only have one, Rendering will call this pass, for the time being no more than the other case Subshader {//tag, the label under Subshader is valid for all passes, while pass is only valid for itself//queue: Description of the queue in which the render is located, Geometry indicates that most opaque objects are rendered in this queue//Rendertype Opaque: Indicates that the object is opaque, and the difference between the queue is that it is only the rendering order, even if it is set to other, it is not a problem,//But you need this object is opaque         Rendertype must be set to Opaquetags {"Queue" = "Geometry" "rendertype" = "Opaque"} Pass {//Lightmode: Illumination mode            Tags {"Lightmode" = "forwardbase"}//settings, control shader Some default processing, depth test and deep write always on ZTest on Zwrite on            Cgprogram and ENDCG appear in pairs, the code inside the two lines is the control code written in CG language (variant of C language) Cgprogram//Vertex: Indicates that the function that controls the vertex shader is vert       Fragment: The function that indicates that the control element shader is Frag #pragma vertex vert     #pragma fragment Frag//Declare attributes in properties to invoke uniform fixed4 _color in vert and Frag functions;                The input struct A2V {//vertex must be provided by unity to the Vert function, POSITION indicates that he is the vertex coordinate of a model FLOAT4 vertex:position; Normal,normal indicates that the need is normal FLOAT3 normal:normal;//texcoord,texcoord0 indicates the need is the current model of UV coordinates FLOAT4 Texcoord:texcoord            0;                        };            The output of the vert function, the input//sv_ of the Frag function, is required and must be written, which is the data struct that must be obtained in the pipelined process v2f {                POS must, sv_position indicates the need to output a screen coordinate float4 pos:sv_position;                color, colors, other properties, used in the Frag function, but usually the identity after the colon is TEXCOORD0, TEXCOORD1, TEXCOORD2 ...//As long as it doesn't repeat, the other attributes indicate what doesn't matter            Fixed3 color:color0;                        };            The vertex shader controls the function v2f Vert (a2v v) {///Initialize the output structure first v2f o;           Unity_matrix_m: From model space to World space//UNITY_MATRIX_V: Viewing space from World space to camera Unity_matrix_p: From the observation space to the screen space//o.pos: Need to output a screen space coordinates, so very simple, UNITY_MATRIX_MVP is the model space to the screen space matrix, and then multiplied by V.vertex to get            O.pos = Mul (UNITY_MATRIX_MVP, V.vertex);            Calculates the color according to the normal O.color = v.normal * 0.5 + fixed3 (0.5, 0.5, 0.5);            Output return o;            }//The chip shader uses a control function that must be written on Sv_target, indicating that the output is a color on the screen fixed4 Frag (v2f i): sv_target {            Gets the vert processed color, and then multiplies _color.rgb by fixed3 C = I.color;            C *= _color.rgb;            Final output return Fixed4 (c, 1.0); } ENDCG}}//Declare the alternate shader if the above pass cannot be run Fallback "diffuse"}

The most important are the two functions vert and Frag specified by vertex and fragment. The pipeline locations where they are located are vertex shaders and slice shaders, respectively.

The vertex shader, which corresponds to the vert function, is necessary for the Sv_position variable as stated above, and the most important duty of the vertex shader is to output screen coordinates based on a model coordinate.

The surface subdivision shader and geometry shader should also be written, but they are not used when learning the book, so they are ignored for the time being.

cropping,the vert transforms the model coordinates to the screen coordinates, so that you can determine whether each vertex is in the screen, and the clipping is to crop out the vertices that are not in the screen.

screen mapping, which transforms the coordinates of each entity into screen coordinates, After the MVP matrix, the coordinates are in ( -1,-1) to (), and the screen map is to map it to the screen resolution. For example, the resolution is 1920*1080, you need to map ( -1,-1) to () to (0,0) to (1920,1080).

Triangle setting, triangle traversal. The vertices make up the triangular slices, and the triangular slices make up the mesh and make up the whole model. The two stages are calculated by the pixels covered by the triangles that make up the vertices.

The element shader, corresponding to the Frag function, processes the pixels from the last two stages, and ultimately needs to output the final color represented by a sv_target.

a chip-by-piece operation, a depth test, a template test, etc., can be configured by the pixel to be displayed on the screen. Corresponding to the above code ZTest on to open the depth test.

The screen image, which results in the final display.

Summarize:

top of a few cutting screen, 33 pieces per screen. Remember this at the same time, you need to know that the vert function is the vertex transform corresponding to the vertex shader stage, and the Frag function is to each pixel color processing, corresponding to the phase of the chip shader.

While the two phases of cropping and chip-by-slice operations cannot write code, they can be controlled.

today with their own language simple summary of the rendering pipeline, do not know whether you can pass this article on the rendering pipeline has a simple understanding. Write Shader, do not know the assembly line when you do not know why to write this way, so master this pipeline is very necessary.

will bring you more in the future Shader understanding and some interesting shader to use.


Unity3d shader the way to write shader before you must know the summary of the rendering pipeline

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.