Interpretation of Series 3 Written by CG in Unity, interpretation of unitycgshader

Source: Internet
Author: User

Interpretation of Series 3 Written by CG in Unity, interpretation of unitycgshader

In the previous example, we obtained that the information transmitted by the mesh component was converted to a suitable color range and colored to the object in the form of color. In this article, we will study the discarding fragments and front clipping and front face culling to achieve transparency.

When the information of a mesh component is transmitted, we can use the code to determine which parts are rendered (render) and which parts are not. This process is like removing the unwanted parts, we don't see him. Although his mesh information is still there, our GPU won't process it, and it will definitely be less performance consumption than the GPU before removal.

This process is like our mesh component is a transparent film. We assume that we cannot see this adhesive paper at all, and the fragment coloring tool is selectively colored like a brush during coloring, the final effect is that we may see that a part of the film is visible, but the film still exists, but we didn't color it for him. We neither looked at them, they do not need to draw valuable ink (GPU parallel processing capability)


So we can transform the longitude green pseudo-color sphere in the previous example and erase the part of the longitude> 0.5, then the code should be changed:

Pass {Cull Off // disable the cropping mode. CGPROGRAM # pragma vertex vert # pragma fragment frag # include "UnityCG. cginc "struct vertexOutput {float4 pos: SV_POSITION; // The texture coordinates in the mesh information are output by the vertex shader. The coordinates are the float4 posInObjectCoords: TEXCOORD0;} of the object coordinate system ;}; vertexOutput vert (appdata_full input) {vertexOutput output; output. pos = mul (UNITY_MATRIX_MVP, input. vertex); // pass texcoord directly to the clip coloring tool output. posInObjectCoords = input. texcoord; return output;} float4 frag (vertexOutput input): COLOR {// when the y value of the coordinate is greater than 0.5, the part if (input. posInObjectCoords. y> 0.5) {discard;} // The rest still generates the longitude green ball return float4 (0.0, input. posInObjectCoords. y, 0.0, 1.0);} ENDCG}



Then give the shader to material, and then give a sphere to see that the green fake colored ball we saw last time is left with only the southern hemisphere:


Looks solid from the front.


A little skewed, From the above we can see that the sphere is hollow, so I use a film and a brush to compare this render process.



Let's Replace the sphere with a cube to see what it looks like:



It can be found that this is a strange cube. The six sides of the cube are only drawn in half, and they are both in the lower half.

Why is the difference between the cube and the sphere so big?

Because the cube is a Cartesian coordinate system, and the sphere is a polar coordinate system ............ Slap in the face ~~~ Are you back to the instructor?


In the same way, we can change> 0.5 to <0.5 to get the northern hemisphere of the sphere.


This is the simplest form of surface removal (cuteaway)


A better way to remove a surface is to convert the position of a clip from the object coordinate system to the world coordinate system, then, based on the basic matrix transformation, we can calculate which fragments are located inside the other sphere (the original radius is 0.5), and then remove the surfaces inside the other sphere, in this case, if the two balls overlap one part, even if the two balls rotate around one another, no overlapping part will be drawn, and the overlapping part will not be drawn, we can't see it anyway, saving performance. Even if the sphere is rotated, the coordinates of the object are converted to the world coordinates through the built-in matrix of unity, and the world coordinates of the overlapping parts are fixed. Therefore, after the overlapping parts of the two sphere are cropped, after rotating a ball, you can see the cropped hole. (Because the previous method is based on the object Coordinate System)


Front and back Clipping

We have seen Cull Off in the code just now. This line of code is located before the CGPROGRAM mark, so it is not in the CG category. It is the ShaderLab instruction in Unity, so it does not need a semicolon to end.

Cull Off is to turn Off triangle pruning (why is a triangle suddenly popped up, and the brain fills up, our three-dimensional images are pieced together by triangles in the computer, because of this, our 3D images produce sawtooth images, which are the credit of triangles)

Cull Front is tailored to the Front (external)

Cull Back is tailored to the backend (internal), which is the default mode of all our Shader. That is to say, if the Shader is not written by yourself, it is very likely that when we rotate our hemisphere, you only see the surface in front, not the hemisphere surface. If you don't believe it, you can drag a model to see it.


As for why the default side is the back crop, because in most cases, our rendering is performed on the surface of the entire 3D body, since the surface is completely rendered, you can't see the part that is facing your back, so the default backend tailoring will save a lot of physical performance!

However, since we have erased the surface, we can see the inner surface on the back through the erased part. So we should modify this cropping mode, just like a house with a roof, we can't see the floor in the house from the top, so the floor should belong to the category of tailoring. However, it would be a bit scary if we had to wipe the roof (open the roof) and couldn't see the floor, so we had to switch the cropping mode.


To better understand the two modes, we modify the above Code to Pass internally/externally tailored, and the final coloring of each Pass is different (red and green)


To be clear, only one SubShader is executed for the Shader in Unity, but all the Pass


Modified code:


Pass {Cull front // external cropping, this channel can be understood as coloring CGPROGRAM # pragma vertex vert # pragma fragment frag # include "UnityCG. cginc "struct vertexOutput {float4 pos: SV_POSITION; // The texture coordinates in the mesh information are output by the vertex shader. The coordinates are the float4 posInObjectCoords: TEXCOORD0;} of the object coordinate system ;}; vertexOutput vert (appdata_full input) {vertexOutput output; output. pos = mul (UNITY_MATRIX_MVP, input. vertex); // pass texcoord directly to the clip coloring tool output. posInObjectCoords = input. texcoord; return output;} float4 frag (vertexOutput input): COLOR {// when the y value of the coordinate is greater than 0.5, the part if (input. posInObjectCoords. y> 0.5) {discard;} // The rest still generates the longitude green ball return float4 (0.0, input. posInObjectCoords. y, 0.0, 1.0);} ENDCG} Pass {Cull back // internal cropping, this channel can be understood as coloring CGPROGRAM # pragma vertex vert # pragma fragment frag # include "UnityCG. cginc "struct vertexOutput {float4 pos: SV_POSITION; // The texture coordinates in the mesh information are output by the vertex shader. The coordinates are the float4 posInObjectCoords: TEXCOORD0;} of the object coordinate system ;}; vertexOutput vert (appdata_full input) {vertexOutput output; output. pos = mul (UNITY_MATRIX_MVP, input. vertex); // pass texcoord directly to the clip coloring tool output. posInObjectCoords = input. texcoord; return output;} float4 frag (vertexOutput input): COLOR {// when the y value of the coordinate is greater than 0.5, the part if (input. posInObjectCoords. y> 0.5) {discard;} // The remaining part still generates the longitude red ball return float4 (input. posInObjectCoords. y, 0.0, 0.0, 1.0);} ENDCG}

We have finished a Shader with two passes. Now let's see what the sphere looks like:


Looking down from the top, we don't know whether the concave part of the sphere is convex due to its full vertical aspect. It seems that the green longitude ball in the previous example is still shown,

Let's look at the bottom online:



We still don't know whether the red and black parts are concave or convex. After all, this is a hemisphere, and the vertical hemisphere is invisible.

Let's look at it from the front:


It can be seen that the green black part is the concave inner surface, and the red black part is the convex outer surface ~



At this point, we can control what is visible or invisible on our surface as we like!

Next, CG has something more amazing waiting for us to discover ~


How to Learn shader

Learning Methods

(1) From Simplicity to complexity: Write the Shader by yourself, start from the simplest writing, pass the simple test, and add it to the Shader a little bit.
(2) Multi-Debug: for example, there is a float variable x. If the range of x is [], the color of float4 (x, 1) is output in the frag fragment function, and the value of x is observed in red; if the range of x is [], the float4 (x/, 0,) color can be output in the frag fragment function. The method is as simple as needed.
(3) view UnityCG. cginc and other files, and the built-in Shader of unity, that is, Build-in Shader.
Build-in Shader
(4) reading books: It is recommended that you read more books while reading this tutorial. Recommended English The CG Tutorial, that is, The Chinese version of The Cg Tutorial _ programmable real-time graphics authoritative guide
Links to related teaching materials

Tips
(1) view UnityCG. cginc and other files
When the CG of Vertex and Fragment is used, # include "UnityCG. cginc" is used to define many functions, such as TRANSFORM_TEX and UNITY_TRANSFER_DEPTH. How can we view these definitions?

Windows path: Unity \ Editor \ Data \ CGIncludes
Mac path: Right-click unity icon-> show contents-> Data-> CGIncludes
This folder contains the Unity Shader library, such as UnityCG. cginc, UnityCG. glslinc, and Lighting. cginc. Open
UnityCG. cginc (single Dev, etc.), and then you can view the definition of related functions.

(2) e-book learning skills
Chinese e-books are easy to learn and understand, but most of them are photocopies.
An English e-book can be used to search for knowledge points with keywords.

(3) Use # prama only_renderers d3d9 to limit the compilation platform. (3) (4) Better use results

(4) Open the compiled Shader and view the corresponding assembly code or OpenGL ES code.
Method: left-click the single-host shader file and click Open Compiled Shader in the Inspector panel.

A Brief Introduction to the ShaderLab For Unity3D syntax

It's also a newbie who just got in touch with Shader. It means it's a bit confusing to learn it at the beginning. Here are some of my own understandings and I don't know if it can help you.
1. the SV_POSITION here is called the output semantics. Semantics is a concept proposed in GPU programming. This definition may be long. I am afraid I cannot tell you clearly or mislead you, you can bind the input/output of cg to the semantics in Baidu's next article.
2. # pragma vertex vert is a preprocessing command that indicates the vertex program of a function named by vert, which is fixed, for details, refer to the vertex and fragment coloring tool section in the Unity holy code component reference manual.
3. cg programs are followed by CGPROGRAM, and mul functions are cg standard library functions.
P.s. It is recommended that you take a look at the cg language a little before shader, and there will be fewer steps around

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.