当前位置:网站首页>Getting started with unityshader - Surface Shader
Getting started with unityshader - Surface Shader
2022-06-25 02:33:00 【Jelly Xizhilang】
Of surface shaders CG The code is direct and must be written in SubShader In block ,Unity Will generate multiple for us behind the scenes Pass. Of course , Can be in SubShader Use at the beginning Tags To set the label used by this surface shader . We can also use LOD Command to set the... Of the surface shader LOD value . then , We use CGPROGRAM and ENDCG Defines the specific code of the surface shader .
Shader "Custom/test"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 3.0
sampler2D _MainTex;
struct Input
{
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
fixed4 _Color;
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_BUFFER_END(Props)
void surf (Input IN, inout SurfaceOutputStandard o)
{
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
1 Compile instructions
The most important function of the compilation instruction is to indicate the surface function and lighting function used by the surface shader , And set some optional parameters . Of surface shaders CG The first sentence of code in a block is often its compilation instruction . The general format of the compilation instruction is as follows :
#pragma surface surfaceFunction lightModel [optionalparams ]
among ,#pragmasurface Used to indicate that the compilation instruction is used to define the surface shader , After it, you need to specify the surface function used (surfaceFunction) And illumination model (lightModel), meanwhile , You can also use a " Some optional parameters to control the behavior of the surface shader .
Surface function :
surfaceFunction It is used to define these surface properties .surfaceFunction Usually called surf Function of ( The function name can be arbitrary ), Its function format is fixed :
void surf (Input IN,inout SurfaceOutput o)
void surf (Input IN, inout SurfaceOutputStandard o)
void surf (Input IN, inout SurfaceOutputStandardSpecular o)
In surface functions , Will use the input structure InputIN To set various surface properties , And store these attributes in the output structure SurfaceOutput、SurfaceOutputStandard or SurfaceOutputStandardSpecular in , And then to the light
Function to calculate the lighting result .
Light function :
The lighting function uses the various surface properties set in the surface function , To apply certain lighting models , And then simulate the lighting effect of the object surface .Unity Built in physics based lighting model functions Standard and StandardSpecular (UnityPBSLighting.cginc Defined in file ), And a simple non - Physical illumination model function Lambert and BlinnPhong ( stay Lighting.cginc Defined in file ).
Customize functions for forward rendering :
// For perspective independent lighting models , For example, diffuse reflection
half4 Lighting<Name> (SurfaceOutput s,half3 lightDir, half atten) ;
// For view dependent lighting models , For example, specular reflection
half4 Lighting<Name> (SurfaceOutput s, half3 lightDir, half3 viewDir, half atten) ;
Custom lighting model https://docs.unity3d.com/Manual/SL-SurfaceShaderLightingExamples.html Optional parameters :
Optional parameters https://docs.unity3d.com/Manual/SL-SurfaceShaders.html
- Custom modification function
Vertex modification function (vertex:VertexFunction): Allows us to customize some vertex attributes , for example , Pass vertex color to surface function , Or change the vertex position , Realize some vertex animation, etc .
The last color modification function (finalcolor:ColorFunction): Before the color is drawn to the screen , Change the color value for the last time , For example, to achieve custom fog effect .
- shadow
addshadow Parameter generates a shadow cast for the surface shader Pass.
fullforwardshadows Parameter can support shadows of all light source types in the forward rendering path .
noshadow Parameter to disable shadows .
- Transparency blending and transparency testing
adopt alpha and alphatest Command to control transparency blending and transparency testing . for example ,alphatest:VariableName The instruction will use the name VariableName To eliminate the slice elements that do not meet the conditions . here , We may also need to use the above mentioned addshadow Parameter to generate the correct shadow cast Pass.
- light
noambient The parameters will tell Unity Do not apply any ambient light or light probe (light probe).
novertexlights Parameters tell Unity Do not apply any per vertex lighting .
noforwardadd All extra... In forward rendering will be removed Pass. in other words , This Shader Only one pixel by pixel directional light is supported , Other light sources will follow a vertex by vertex or SH To calculate the effect of light . This parameter is usually used in the mobile platform version of the surface shader .
nolightmap Control light baking .
nofog Fog effect simulation .
- Control code generation
By default ,Unity A corresponding forward render path is generated for a surface shader 、 Delay the use of the rendering path Pass, This leads to the generation of Shader File size . If we determine that the surface shader will only be used in some render paths , Can exclude_ path:deferred、exclude_path:forward and exclude_path:prepass To tell Unity There is no need to generate code for certain render paths .
2 Two structures
Input Structure :
Input The structure contains many data sources of surface properties , therefore , It will be used as the input structure of the surface function ( If you have customized the vertex modification function , It will also be the output structure of the vertex modification function ).
Input The structure contains the sampling coordinates of the main texture and the normal texture uv_ MainTex and uv_ BumpMap. These sampling coordinates must be in “uv” The prefix ( In fact, it can also be used “uv2” The prefix , Indicates the use of a set of secondary texture coordinates ), Followed by the texture name . With the main texture _MainTex For example , If you need to use its sampling coordinates , It needs to be in Input The structure states float2 uv_ MainTex To correspond to its sampling coordinates . surface 17.1 Lists Input Other variables built into the structure .
When using, strictly declare variables according to the above name . One exception is , We have customized the vertex modification function , And need to transfer some customized data to the surface function . for example , To customize the fog effect , We may need to calculate the fog effect mixing coefficient in the vertex modification function according to the vertex position information in the view space , So that we can Input A structure named half fog The variable of , Store the calculation result in the variable and output it .
SurfaceOutput Structure :
Output as a surface function , Then, various lighting calculations will be performed as the input of the lighting function . Compared with the Input The freedom of the structure , The variables in this structure are declared in advance , Neither increase nor decrease ( If you do not assign values to certain variables , The default value will be used ).SurfaceOutput Your statement can be in Lighting.cginc Found in file :
struct SurfaceOutput {
fixed3 Albedo; // Reflectance to light source
fixed3 Normal; // Surface normal direction
fixed3. Emission; // Spontaneous light
half Specular; // The exponential part of the specular reflection
fixed Gloss; // Intensity coefficient in specular reflection
fixed Alpha; // Transparent channel
};
and SurfaceOutputStandard and SurfaceOutputStandardSpecular The declaration of can UnityPBSLighting.cginc Find :
struct Sur faceOutputStandard
{
fixed3 Albedo; // base (diffuse or specular) color
fixed3 Normal; // tangent space normal, if written
half3 Emission;
half Metallic; // 0=non-metal, 1=metal
half Smoothness; // 0=rough, 1=smooth
half Occlusion; // occlusion (default 1)
fixed Alpha; // alpha for transparencies
};
struct SurfaceOutputStandardSpecular
{
fixed3 Albedo; // diffuse color
fixed3 Specular; // specular color
fixed3 Normal; // tangent space normal, if written
half3 Emission;
half Smoothness; // 0=rough, 1=smooth
half Occlusion; // occlusion (default 1)
fixed Alpha; // alpha for transparencies
};
In a surface shader , Just select one of the above three , It depends on the lighting model we choose to use .Unity There are two built-in lighting models , One is Unity5 Previous 、 ordinary 、 Non physical based lighting model , It includes Lambert and BlinnPhong; The other is Unity 5 Added 、 Physics based lighting model , Include Standard and StandardSpecular, This model will be more in line with the laws of Physics , But the calculation will be much more complicated .
If a non physical based lighting model is used , We usually use them SurfaceOutput Structure , If you use a physics based lighting model Standard or StandardSpecular, We will use... Separately SurfaceOutputStandard or SurfaceOutputStandardSpecular Structure . among ,SurfaceOutputStandard The structure is used for the default metal workflow (Metallic Workflow), Corresponding Standard Light function ; and SurfaceOutputStandardSpecular Structure is used for highlight workflow (Specular Workflow), Corresponding StandardSpecular Light function .
The surface shader essentially contains a lot of Pass The summit of / Chip shader .
3 Unity What did you do behind your back
We talked about that before ,Unity In the back, a surface shader will be generated, which contains a lot of Pass The summit of / Chip shader . these Pass Some are for different rendering paths , for example , By default Unity Generates... For forward render paths LightMode by ForwardBase and ForwardAdd Of Pass, by Unity 5 The previous delay render path generation LightMode by PrePassBase and PrePassFinal Of Pass, by Unity 5 Later, the delayed rendering path is generated LightMode by Deferred Of Pass. Some more Pass Is used to generate additional information , for example , To extract surface information for illumination mapping and dynamic global illumination ,Unity Will generate a LightMode by Meta Of Pass. Some surface shaders modify vertex positions , therefore , We can use adddshadow The compile instruction generates the corresponding LightMode by ShadowCaster Shadow casting Pass. these Pass The generation of is based on our compilation instructions and custom functions in the surface shader , There are rules to follow .
Click on shader On the front panel Show generated code Button to view the vertices generated by the surface shader / Chip shader .
With Unity Generated LightMode by ForwardBase Of Pass ( For forward rendering ) For example ,Unity The automatic generation process of is as follows :
(1) Directly into the surface shader CGPROGRAM and ENDCG Copy the code between , This code includes our understanding of Input Structure 、 Surface function 、 Light function ( If you make up your mind ) Definition of equal variables and functions . These functions and variables will be called as normal structures and functions in the subsequent processing .
(2) Unity Will analyze the above code , And generate the output of the item point shader ——v2f_ surf Structure , Used for data transfer between vertex shaders and slice shaders .
(3) next , Generate vertex shaders .
① If we customize the vertex modification function ,Unity First, the vertex modification function will be called to modify the vertex data , Or fill in custom Input Variables in the structure . then ,Unity Analyze the modified data in the vertex modification function , Pass when needed Input The structure stores the modification results in v2f_surf In the corresponding variable .
② Calculation v2f_surf Other generated variable values in . This mainly includes the vertex position 、 Texture coordinates 、 Normal direction 、 Light up by the top 、 Lighting texture sampling coordinates, etc . Of course , We can control whether some variables need to be calculated by compiling instructions .
③ Last , take v2f_surf Passed to the next slice shader .
(4) Generate a slice shader .
① Use v2f_ surf Fill in the corresponding variable in Input Structure , for example , Texture coordinates 、 Angle of view, direction, etc .
② Call our custom surface function to fill SurfaceOutput Structure .
③ Call the lighting function to get the initial color value . If you use a built-in Lambert or BlinnPhong Light function ,Unity Dynamic global illumination is also calculated , And added to the calculation of the lighting model .
④ Do other color overlays . for example , If you don't use light baking , It also adds the influence of per vertex lighting .
⑤ Last , If you have customized the last color modification function ,Unity It will be called to make the final color modification .
4 Surface Shader The shortcomings of
Lost control of various optimizations and special effects , Have a certain impact on Performance .
Surface shaders have not been able to complete some custom rendering effects
- If you need to deal with various light sources , Especially if you want to use Unity Global illumination in , You may prefer to use surface shaders , But always be careful about its performance
- If you need to deal with a very small number of light sources , For example, there is only one directional light , So use vertices / Slice shaders are a better choice
- If you have a lot of custom rendering effects , Then please select the vertex / Chip shader .
Shader "Unity Shaders Book/Chapter 17/Normal Extrusion" {
Properties {
_ColorTint ("Color Tint", Color) = (1,1,1,1)
_MainTex ("Base (RGB)", 2D) = "white" {}
_BumpMap ("Normalmap", 2D) = "bump" {}
_Amount ("Extrusion Amount", Range(-0.5, 0.5)) = 0.1
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 300
CGPROGRAM
// surf - which surface function.
// CustomLambert - which lighting model to use.
// vertex:myvert - use custom vertex modification function.
// finalcolor:mycolor - use custom final color modification function.
// addshadow - generate a shadow caster pass. Because we modify the vertex position, the shder needs special shadows handling.
// exclude_path:deferred/exclude_path:prepas - do not generate passes for deferred/legacy deferred rendering path.
// nometa - do not generate a “meta” pass (that’s used by lightmapping & dynamic global illumination to extract surface information).
#pragma surface surf CustomLambert vertex:myvert finalcolor:mycolor addshadow exclude_path:deferred exclude_path:prepass nometa
#pragma target 3.0
fixed4 _ColorTint;
sampler2D _MainTex;
sampler2D _BumpMap;
half _Amount;
struct Input {
float2 uv_MainTex;
float2 uv_BumpMap;
};
// Vertex modification function
void myvert (inout appdata_full v) {
v.vertex.xyz += v.normal * _Amount;
}
// Surface function
void surf (Input IN, inout SurfaceOutput o) {
fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
o.Albedo = tex.rgb;
o.Alpha = tex.a;
o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_BumpMap));
}
// Light function
half4 LightingCustomLambert (SurfaceOutput s, half3 lightDir, half atten) {
half NdotL = dot(s.Normal, lightDir);
half4 c;
c.rgb = s.Albedo * _LightColor0.rgb * (NdotL * atten);
c.a = s.Alpha;
return c;
}
// The last color modification function
void mycolor (Input IN, SurfaceOutput o, inout fixed4 color) {
color *= _ColorTint;
}
ENDCG
}
FallBack "Legacy Shaders/Diffuse"
}
边栏推荐
- 保险APP适老化服务评测分析2022第06期
- [i.mx6ul] u-boot migration (VI) network driver modification lan8720a
- Summary of knowledge points of computer level III (database) test preparation topics
- Charles 抓包工具
- Application of TSDB in civil aircraft industry
- PyTorch学习笔记(七)------------------ Vision Transformer
- JS regular matching numbers, upper and lower case letters, underscores, midlines and dots [easy to understand]
- 【Proteus仿真】Arduino UNO+数码管显示4x4键盘矩阵按键
- Computing service network: a systematic revolution of multi integration
- QT package the EXE file to solve the problem that "the program input point \u zdapvj cannot be located in the dynamic link library qt5cored.dll"
猜你喜欢
How to monitor the log through the easycvr interface to observe the platform streaming?
Please run IDA with elevated permissons for local debugging.
进入阿里做测试员遥不可及?这里或许有你想要的答案
Sumati gamefi ecological overview, element design in the magical world
AI服装生成,帮你完成服装设计的最后一步
jwt
Experience of epidemic prevention and control, home office and online teaching | community essay solicitation
Intranet learning notes (5)
leecode学习笔记-机器人走到终点的最短路径
3年测试经验,连简历上真正需要什么都没搞明白,张口就要20k?
随机推荐
Qt中使用QDomDocument操作XML文件
Android Internet of things application development (smart Park) - set sensor threshold dialog interface
【Proteus仿真】Arduino UNO+继电器控制照明设备
Is the compass reliable? Is it safe to open a securities account?
高速缓存Cache详解(西电考研向)
It is said that Yijia will soon update the product line of TWS earplugs, smart watches and bracelets
|遇到bug怎么分析,专业总结分析来了
Lizuofan, co-founder of nonconvex: Taking quantification as his lifelong career
yarn : 无法加载文件 C:\Users\xxx\AppData\Roaming\npm\yarn.ps1,因为在此系统上禁止运行脚本
PSQL column to row
Migrate Oracle database from windows system to Linux Oracle RAC cluster environment (2) -- convert database to cluster mode
[day 26] given the ascending array nums of n elements, find a function to find the subscript of target in nums | learn binary search
How to quickly familiarize yourself with the code when you join a new company?
Viewing MySQL password on Linux_ MySQL forgets password "suggestions collection" under Linux
调用系统函数安全方案
记一次beego通过go get命令后找不到bee.exe的坑
Network planning | [four network layers] knowledge points and examples
Charles 抓包工具
Can automate - 10k, can automate - 20K, do you understand automated testing?
MCN机构遍地开花:博主和作者要谨慎签约、行业水很深