从一个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
            }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值