天天看點

U3D着色器源碼分析

最近在看u3d 5.3.3着色器的源碼,這裡先簡單的分析下UnityShaderVariables.cginc 中 UnityLighting的_WorldSpaceLightPos0的值是怎麼擷取的。

CBUFFER_START(UnityLighting) //光照的參數

	//_WorldSpaceLightPos0.w可以表明該光源的類型,如果為0表示是平行光,為1表示是點光源或者聚光燈光源。
	#ifdef USING_DIRECTIONAL_LIGHT
	uniform half4 _WorldSpaceLightPos0; //位置  lightdir = nor(lightpos)  光源的向量
	#else
	uniform float4 _WorldSpaceLightPos0;
	#endif

	uniform float4 _LightPositionRange; // xyz = pos, w = 1/range 點光源才有效 陰影的時候才會有值
。。。。。。
           

通過幀調試視窗,可以看到這個值是。

U3D着色器源碼分析
U3D着色器源碼分析

圖一中的是近視值,右鍵copy會得到真實的值,通過比較發現和我自己計算出來的是一樣的。直接上代碼

void TestLigth()
    {
        //ForwardBase的光源應該是平行光
        //ForwardAdd的類型不限制

        Vector4 lightInfo;
        if (mLight.type != LightType.Directional)
        {
            Vector3 worldPos = mLight.transform.position;
            lightInfo = worldPos;
            lightInfo.w = 1.0f;
        }//The light is a directional light.
        else
        {
            Vector3 worldDir = mLight.transform.TransformDirection(new Vector3(0, 0, -1));
          //  worldDir1 = MyTransform.TransformDirection(mLight.transform, new Vector3(0, 0, -1));

            lightInfo = worldDir;
            lightInfo.w = 0.0f;
        }
        _WorldSpaceLightPos0 = lightInfo;
        //_LightMatrix0  == world2Light
        _LightMatrix0 = mLight.transform.worldToLocalMatrix;
        //UnityLightingCommon.cginc  fixed4 _LightColor0;
        //kShaderVecLightColor0 
        _LightColor0 = mLight.color * mLight.intensity;

        //MeshRenderer


    }