1. 程式人生 > >從一個shader剖析unity混合光照和pbr

從一個shader剖析unity混合光照和pbr

從unity5.6自帶的程式碼來看。

standard shader綜論

下面是standard.shader的面板
這裡寫圖片描述
shader結構圖:

這裡寫圖片描述

兩個subShader

subShader的區別,先看兩個pass的區別:
這裡寫圖片描述
這裡寫圖片描述
然後我們先看第一個forward pass,“UnityStandardCoreForward.cginc”裡檢視,vertBase和fragBase又根據是否定義simple而執行不同的分支:
這裡寫圖片描述

simple版

vs分析

定義了simple的分支,資料結構和函式,我們去“UnityStandardCoreForwardSimple.cginc”檔案裡檢視,vert函式的輸入結構定義:
這裡寫圖片描述


vert函式輸出結構定義
這裡寫圖片描述
vert函式定義
這裡寫圖片描述
裡面涉及的函式,獲取切線空間光照和view方向的函式
這裡寫圖片描述
獲取lightmap或環境光的uv的函式:
這裡寫圖片描述
grazing引數的獲取:
這裡寫圖片描述
我們總結一下,定義了UNITY_STANDARDD_SIMPLE巨集的vs,如下:
這裡寫圖片描述

simple版fs分析

再看fragment函式fragForwardBaseSimpleInternal,在UnityStandardCoreForwardSimple.cginc檔案中:
這裡寫圖片描述
裡面第一句又從輸入的結構得到FragmentCommonData,函式如下:
這裡寫圖片描述
fragmentCommonData結構如下:
這裡寫圖片描述


與前面的結構比較:
這裡寫圖片描述
轉換函式FragmentSetupSimple也在SimpleForward這個檔案裡
這裡寫圖片描述
其中的UNITY_SETUP_BRDF_INPUT函式(UnityStandardCore.cginc中)定義如下,這個函式裡獲取FragmentCommonData的difColor,SpecColor,oneMinusReflectivity和smoothness。
這裡寫圖片描述
其中a通過Alpha函式(UnityStandardInput.cginc)得到,如果定義了_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A則通過_color.a得到,否則:
這裡寫圖片描述
。該巨集的定義通過editor得到,在builtin_shaders-5.6\Editor\StandardShaderGUI.cs檔案中:
這裡寫圖片描述
介面上感覺就是這裡:
這裡寫圖片描述

specularSetup

再看,specularSetup裡面,smoothness通過SpecularGloss函式得到(在UnityStandardInput.cginc中定義),如果有speculargloss貼圖,則對貼圖取樣,如果用主貼圖的a通道儲存gloss值,則sg的a通道通過取樣主貼圖得到,如果a通道在specularGLoss貼圖,則通過取樣specGLoss貼圖得到。如果沒有定義高光貼圖,則高光顏色通過_SpecColor得到,如果gloss在主貼圖的a通道,則取樣主貼圖獲取gloss,否則,gloss通過_Glossiness得到:
這裡寫圖片描述
diffColor,SpecColor,oneMinusReflectivity又通過EnergyConservationBetweenDiffuseAndSpecular得到:
這裡寫圖片描述
diffColor用preMultiplyAlpha函式,裡面將blend模式加入:
這裡寫圖片描述

metalSetup

如圖所示:
這裡寫圖片描述
輸出FragmentCommanData。主要獲取metallicGlossMap中的金屬度和粗糙度值。

看完FragmentCommonData後,我們再繼續看fragForwardBaseSimpleInternal函式,mainLight包含顏色和方向,nDotL,然後是shadowMask衰減,實時陰影衰減並將兩個衰減混合。從遮擋貼圖取樣得到遮擋因子。rl好像是反射光線和主光源方向的點乘,然後是FragmentGI求出GI。FragmentGI函式如下:
這裡寫圖片描述
這裡寫圖片描述
fragmentGI函式裡首先構建了一個UnityGIInput資料結構,然後呼叫UnityGlobalIllumination求出gi,有Unity_GlossyEnvironmentData的話,GI裡會加入該引數。
這裡寫圖片描述
主要包含UnityGIbase和UnityGI_IndirectSpecular,前者計算了陰影的衰減(烘焙陰影和實時陰影混合),SH光照,烘焙的lightmap,平行光與非平行光lightmap,動態lightmap。最終返回UnityGI結構,該結構包含light,color,indirect.diffuse引數。
UnityGI_IndirectSpecular(UnityGLobalIllumination.cginc)計算間接高光,用probe相關的屬性計算。
這裡寫圖片描述
這裡寫圖片描述
用求得的GI,計算衰減的光顏色。
然後就是BRDF計算間接光照和直接光照了
這裡寫圖片描述

simple版好像brdf不多,下面看看複雜版
這裡寫圖片描述
輸入結構:
這裡寫圖片描述

複雜的比simple版多了些東西,但原理是一樣的。
後面我發現BRDF有3個版本。上面的是brdf3.
根據馮樂樂的數,第18章,在disney使用的brdf2中,它的漫反射項為:
這裡寫圖片描述

float attenuation = 1;
  float3 attenColor = attenuation * _LightColor0.xyz;

float Pi = 3.141592654;
 float InvPi = 0.31830988618;
float gloss = _Gloss;
half fd90 = 0.5 + 2 * LdotH * LdotH * (1-gloss);
 float3 directDiffuse = ((1 +(fd90 - 1)*pow((1.00001-NdotL), 5)) * (1 + (fd90 - 1)*pow((1.00001-NdotV), 5)) * NdotL) * attenColor;

pbs高光項:
這裡寫圖片描述
函式實現:
這裡寫圖片描述
程式碼例項,摘自Enviro外掛:
這裡寫圖片描述
整個fragment shader程式碼(包含了GI部分,呼叫unity內建函式實現):

 float4 frag(VertexOutput i) : COLOR {
                i.normalDir = normalize(i.normalDir);
                // UNITY_SAMPLE_DEPTH對深度貼圖進行取樣  
                // _ProjectionParams的x為1,如果投影翻轉則x為-1,y是攝像機近裁剪平面,z是攝像機遠裁剪平面,w是1/z.
                float sceneZ = max(0,LinearEyeDepth (UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(i.projPos)))) - _ProjectionParams.g); //減去近裁剪平面
                float partZ = max(0,i.projPos.z - _ProjectionParams.g); //物體之深度
                float3x3 tangentTransform = float3x3( i.tangentDir, i.bitangentDir, i.normalDir); // 轉移矩陣
                float3 viewDirection = normalize(_WorldSpaceCameraPos.xyz - i.posWorld.xyz);      
                float3 _WetNormal_var = UnpackNormal(tex2D(_WetNormal,TRANSFORM_TEX(i.uv0, _WetNormal)));
                float3 _Ripple_var = UnpackNormal(tex2D(_Ripple,TRANSFORM_TEX(i.uv0, _Ripple)));
                //float3 node_4532_nrm_base = _WetNormal_var.rgb + float3(0,0,1);   
                //float3 node_4532_nrm_detail = _Ripple_var.rgb * float3(-1,-1,1);   //wet和下雨混合
                //float3 node_4532_nrm_combined = node_4532_nrm_base*dot(node_4532_nrm_base, node_4532_nrm_detail)/node_4532_nrm_base.z - node_4532_nrm_detail;
                float3 node_4532_nrm_combined = _WetNormal_var.rgb +  _Ripple_var.rgb;
                float3 node_4532 = node_4532_nrm_combined;
                float3 normalLocal = node_4532;
                float3 normalDirection = normalize(mul( normalLocal, tangentTransform ));
                float3 viewReflectDirection = reflect( -viewDirection, normalDirection );
                float3 lightDirection = normalize(_WorldSpaceLightPos0.xyz);
                float3 lightColor = _LightColor0.rgb;
                float3 halfDirection = normalize(viewDirection+lightDirection);
                float attenuation = 1;
                float3 attenColor = attenuation * _LightColor0.xyz;
                float Pi = 3.141592654;
                float InvPi = 0.31830988618;
                float gloss = _Gloss;
                float specPow = exp2( gloss * 10.0+1.0);

                UnityLight light;
                #ifdef LIGHTMAP_OFF
                    light.color = lightColor;
                    light.dir = lightDirection;
                    light.ndotl = LambertTerm (normalDirection, light.dir);
                #else
                    light.color = half3(0.f, 0.f, 0.f);
                    light.ndotl = 0.0f;
                    light.dir = half3(0.f, 0.f, 0.f);
                #endif
                UnityGIInput d;
                d.light = light;
                d.worldPos = i.posWorld.xyz;
                d.worldViewDir = viewDirection;
                d.atten = attenuation;
                #if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
                    d.ambient = 0;
                    d.lightmapUV = i.ambientOrLightmapUV;
                #else
                    d.ambient = i.ambientOrLightmapUV;
                #endif
                d.boxMax[0] = unity_SpecCube0_BoxMax;
                d.boxMin[0] = unity_SpecCube0_BoxMin;
                d.probePosition[0] = unity_SpecCube0_ProbePosition;
                d.probeHDR[0] = unity_SpecCube0_HDR;
                d.boxMax[1] = unity_SpecCube1_BoxMax;
                d.boxMin[1] = unity_SpecCube1_BoxMin;
                d.probePosition[1] = unity_SpecCube1_ProbePosition;
                d.probeHDR[1] = unity_SpecCube1_HDR;
                Unity_GlossyEnvironmentData ugls_en_data;
                ugls_en_data.roughness = 1.0 - gloss;
                ugls_en_data.reflUVW = viewReflectDirection;
                UnityGI gi = UnityGlobalIllumination(d, 1, normalDirection, ugls_en_data );
                lightDirection = gi.light.dir;
                lightColor = gi.light.color;
                float NdotL = max(0, dot( normalDirection, lightDirection ));
                float LdotH = max(0.0,dot(lightDirection, halfDirection));
                float3 specularColor = _Specular.rgb;
                float specularMonochrome = max( max(specularColor.r, specularColor.g), specularColor.b);
                float NdotV = max(0.0,dot( normalDirection, viewDirection ));
                float NdotH = max(0.0,dot( normalDirection, halfDirection ));
                float VdotH = max(0.0,dot( viewDirection, halfDirection ));
                float visTerm = SmithBeckmannVisibilityTerm( NdotL, NdotV, 1.0-gloss );
                float normTerm = max(0.0, NDFBlinnPhongNormalizedTerm(NdotH, RoughnessToSpecPower(1.0-gloss)));
                float specularPBL = max(0, (NdotL*visTerm*normTerm) * UNITY_PI / 4.0 );
                float3 directSpecular = 1 * pow(max(0,dot(halfDirection,normalDirection)),specPow)*specularPBL*lightColor*FresnelTerm(specularColor, LdotH);
                half grazingTerm = saturate( gloss + specularMonochrome );
                float3 indirectSpecular = (gi.indirect.specular);
                indirectSpecular *= FresnelLerp (specularColor, grazingTerm, NdotV);
                float3 specular = (directSpecular + indirectSpecular);
                NdotL = max(0.0,dot( normalDirection, lightDirection ));
                half fd90 = 0.5 + 2 * LdotH * LdotH * (1-gloss);
                float3 directDiffuse = ((1 +(fd90 - 1)*pow((1.00001-NdotL), 5)) * (1 + (fd90 - 1)*pow((1.00001-NdotV), 5)) * NdotL) * attenColor;
                float3 indirectDiffuse = float3(0,0,0);
                indirectDiffuse += gi.indirect.diffuse;
                float3 diffuseColor = _LightColor0.rgb;
                diffuseColor *= 1-specularMonochrome;
                float3 diffuse = (directDiffuse + indirectDiffuse) * diffuseColor;

                float3 finalColor = diffuse + specular;
                fixed4 finalRGBA = fixed4(finalColor,(saturate((sceneZ-partZ)/_Depth)*_Alpha));
                UNITY_APPLY_FOG(i.fogCoord, finalRGBA);
                return finalRGBA;
            }

下面是博主自己根據unity 5.6.5自帶的standard shader,內建檔案改成一個半透明的standard shader,主要把那些include檔案裡呼叫的函式都寫到一個檔案裡面:

Shader "Capstone/simpleStandard"
{
    Properties
    {
        _MainTex("Main Texture", 2D) = "white" {}
        _OcclusionMap("Occlusion Texture", 2D) = "white" {}

        _Color("Color", Color) = (1,1,1,1)
        _Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
        [Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
    }

    SubShader
    {
        Tags{ "RenderType" = "Transparent" }
        LOD 100

        Pass
        {
            Blend One OneMinusSrcAlpha
            ZWrite Off

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"
            #include "UnityStandardUtils.cginc"
            #include "UnityLightingCommon.cginc"
            #include "UnityImageBasedLighting.cginc" 
            #include "UnityGlobalIllumination.cginc"
            #include "UnityStandardBRDF.cginc"


#define IN_WORLDPOS(i) half3(0,0,0)
            struct appdata
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
                float2 uv  : TEXCOORD0;
                float2 uv1 : TEXCOORD1;
            };

            struct v2f
            {
                float4 pos          : SV_POSITION;
                float2 uv           : TEXCOORD0;
                half4 eyeVec        : TEXCOORD1;   //w for grazing term
                half4 normalWorld   : TEXCOORD2;   // W: fresnel term
                float3 reflectVec   : TEXCOORD3;
                half4 ambientOrLightmapUV : TEXCOORD4;
                //float3 
            };

            struct FragmentDataInput
            {
                half3 diffColor, specColor;
                // Note: smoothness & oneMinusReflectivity for optimization purposes, mostly for DX9 SM2.0 level.
                // Most of the math is being done on these (1-x) values, and that saves a few precious ALU slots.
                half oneMinusReflectivity, smoothness;
                float3 normalWorld;
                float3 eyeVec;
                half alpha;
                float3 posWorld;
                half3 reflUVW;

            };

            sampler2D    _MainTex;
            float4       _MainTex_ST;
            float4       _Color;
            float        _Glossiness;
            float        _Metallic;

            sampler2D   _OcclusionMap;
            half        _OcclusionStrength;

            inline UnityGI FragmentGINew(FragmentDataInput s, half occlusion, half4 i_ambientOrLightmapUV
                , half atten, UnityLight light, bool reflections)
            {
                UnityGIInput d;
                d.light = light;
                d.worldPos = s.posWorld;
                d.worldViewDir = -s.eyeVec;
                d.atten = atten;
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
                d.ambient = 0;
                d.lightmapUV = i_ambientOrLightmapUV;
#else
                d.ambient = i_ambientOrLightmapUV.rgb;
                d.lightmapUV = 0;
#endif

                d.probeHDR[0] = unity_SpecCube0_HDR;
                d.probeHDR[1] = unity_SpecCube1_HDR;
#if defined(UNITY_SPECCUBE_BLENDING) || defined(UNITY_SPECCUBE_BOX_PROJECTION)
                d.boxMin[0] = unity_SpecCube0_BoxMin; // .w holds lerp value for blending
#endif
#ifdef UNITY_SPECCUBE_BOX_PROJECTION
                d.boxMax[0] = unity_SpecCube0_BoxMax;
                d.probePosition[0] = unity_SpecCube0_ProbePosition;
                d.boxMax[1] = unity_SpecCube1_BoxMax;
                d.boxMin[1] = unity_SpecCube1_BoxMin;
                d.probePosition[1] = unity_SpecCube1_ProbePosition;
#endif

                if (reflections)
                {
                    Unity_GlossyEnvironmentData g = UnityGlossyEnvironmentSetup(s.smoothness, -s.eyeVec, s.normalWorld, s.specColor);
                    // Replace the reflUVW if it has been compute in Vertex shader. Note: the compiler will optimize the calcul in UnityGlossyEnvironmentSetup itself
#if UNITY_STANDARD_SIMPLE
                    g.reflUVW = s.reflUVW;
#endif

                    return UnityGlobalIllumination(d, occlusion, s.normalWorld, g);
                }
                else
                {
                    return UnityGlobalIllumination(d, occlusion, s.normalWorld);
                }
            }

            inline half4 VertexGIForwardNew(float2 uv1, float3 posWorld, half3 normalWorld)
            {
                half4 ambientOrLightmapUV = 0;
                // Static lightmaps
#ifdef LIGHTMAP_ON
                ambientOrLightmapUV.xy = uv1 * unity_LightmapST.xy + unity_LightmapST.zw;
                ambientOrLightmapUV.zw = 0;
                // Sample light probe for Dynamic objects only (no static or dynamic lightmaps)
#elif UNITY_SHOULD_SAMPLE_SH
#ifdef VERTEXLIGHT_ON
                // Approximated illumination from non-important point lights
                ambientOrLightmapUV.rgb = Shade4PointLights(
                unity_4LightPosX0, unity_4LightPosY0, unity_4LightPosZ0,
                unity_LightColor[0].rgb, unity_LightColor[1].rgb, unity_LightColor[2].rgb, unity_LightColor[3].rgb,
                unity_4LightAtten0, posWorld, normalWorld);
#endif

                ambientOrLightmapUV.rgb = ShadeSHPerVertex(normalWorld, ambientOrLightmapUV.rgb);
#endif

//#ifdef DYNAMICLIGHTMAP_ON
//              ambientOrLightmapUV.zw = v.uv2.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
//#endif

                return ambientOrLightmapUV;
            }

            v2f vert(appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                float4 posWorld = mul(unity_ObjectToWorld, v.vertex);

                half3 eyeVec = normalize(posWorld.xyz - _WorldSpaceCameraPos);
                half3 normalWorld = UnityObjectToWorldNormal(v.normal);

                o.normalWorld.xyz = normalWorld;
                o.eyeVec.xyz = eyeVec;

                o.normalWorld.w = Pow4(1 - saturate(dot(normalWorld, -eyeVec))); // fresnel term
                o.eyeVec.w = saturate(_Glossiness + 1.0h - OneMinusReflectivityFromMetallic(_Metallic)); // grazing term
                o.reflectVec = reflect(eyeVec, normalWorld);
                o.ambientOrLightmapUV = VertexGIForwardNew(v.uv1, posWorld.xyz, normalWorld);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                //fragmentSetupSimple
                half alpha = 1.0;
                half3 specColor;
                half3 albedo = tex2D(_MainTex, i.uv).rgb * _Color.rgb;
                half oneMinusReflectivity;
                half3 diffColor = DiffuseAndSpecularFromMetallic(albedo, _Metallic, /*out*/ specColor, /*out*/ oneMinusReflectivity);

                FragmentDataInput o = (FragmentDataInput)0;
                o.diffColor = diffColor;
                o.specColor = specColor;
                o.oneMinusReflectivity = oneMinusReflectivity;
                o.smoothness = _Glossiness;

                o.diffColor = PreMultiplyAlpha(o.diffColor, alpha, o.oneMinusReflectivity, /*out*/ o.alpha);
                o.normalWorld = i.normalWorld.xyz;
                o.eyeVec = i.eyeVec.xyz;
                o.posWorld = half3(0, 0, 0);  //UnityStandardCore裡面,這裡應該是half3(0,0,0)
                o.reflUVW = i.reflectVec;

                UnityLight light;
                light.color = _LightColor0.rgb;
                light.dir = _WorldSpaceLightPos0.xyz;

                half ndotl = saturate(dot(o.normalWorld, light.dir));

                half occlusion = tex2D(_OcclusionMap, i.uv).g;
                occlusion = LerpOneTo(occlusion, _OcclusionStrength);

                half rl = dot(o.reflUVW, light.dir);

                half atten = 1.0;
                UnityGI gi = FragmentGINew(o, occlusion, i.ambientOrLightmapUV, atten, light, true);

                half3 attenuatedLightColor = gi.light.color * ndotl;

                //half3 c = BRDF3_Indirect(o.diffColor, o.specColor, gi.indirect, PerVertexGrazingTerm(i, o), i.normalWorld.w);
                half3 c = BRDF3_Indirect(o.diffColor, o.specColor, gi.indirect, i.eyeVec.w, i.normalWorld.w);
                //c += BRDF3DirectSimple(o.diffColor, o.specColor, o.smoothness, rl) * attenuatedLightColor;
                c += BRDF3_Direct(o.diffColor, o.specColor, Pow4(rl), o.smoothness)* attenuatedLightColor;

                //UNITY_APPLY_FOG(i.fogCoord, c);
                half4 outputCol = half4(c, o.alpha);
                return outputCol;
                // sample the texture
                /*fixed4 col = tex2D(_MainTex, i.uv);
                return col;*/
            }
                ENDCG
            }
    }
}