从正常方向cg unity3d获得切线

时间:2015-08-07 01:24:00

标签: unity3d cg

我正在cg中写一个着色器,我在其中移动顶点。因为我移位了顶点,所以我重新计算法线,使它们指向远离表面并将该信息提供给片段函数。在着色器中我还实现了一个法线贴图,现在我想知道我是否也不应该重新计算切线?是否有计算切线的公式?我读到它与法线成90度角,我可以使用点积吗?

我想传递给VOUT.tangentWorld的右边切线。这是我的顶点函数:

VertexOutput vert (VertexInput i)
        {
            VertexOutput VOUT;

            // put the vert in world space
            float4 newVert = mul(_Object2World,i.vertex);

            // create fake vertexes
            float4 v1 = newVert + float4(0.05,0.0,0.0,0.0) ; // X
            float4 v2 = newVert + float4(0.0,0.0,0.05,0.0) ; // Z

            // assign the displacement map to uv coords 
            float4 disp = tex2Dlod(_Displacement, float4(newVert.x + (_Time.x * _Speed), newVert.z + (_Time.x * _Speed),0.0,0.0));
            float4 disp2 = tex2Dlod(_Displacement, float4(v1.x + (_Time.x * _Speed), newVert.z + (_Time.x * _Speed),0.0,0.0));
            float4 disp3 = tex2Dlod(_Displacement, float4(newVert.x + (_Time.x * _Speed), v2.z + (_Time.x * _Speed),0.0,0.0));

            // offset the main vert
            newVert.y += _Scale * disp.y; 

            // offset fake vertexes 
            v1 += _Scale * disp2.y; 
            v2 += _Scale * disp3.y; 

            // calculate the new normal direction
            float3 newNor = cross(v2 - newVert, v1 - newVert);

            // return world position of the vert for frag calculations
            VOUT.posWorld = newVert;

            // set the vert back in object space
            float4 vertObjectSpace = mul(newVert,_World2Object);

            // apply unity mvp matrix to the vert
            VOUT.pos = mul(UNITY_MATRIX_MVP,vertObjectSpace);

            //return the tex coords for frag calculations
            VOUT.tex = i.texcoord;

            // return normal, tangents, and binormal information for frag calculations
            VOUT.normalWorld = normalize( mul(float4(newNor,0.0),_World2Object).xyz);
            VOUT.tangentWorld = normalize( mul(_Object2World,i.tangent).xyz);
            VOUT.binormalWorld = normalize( cross(VOUT.normalWorld, VOUT.tangentWorld) * i.tangent.w);

            return VOUT;
        }

它不仅仅是向量v2 - newVertv1 - newVert因为表面上的点吗?我怎么知道它们中的哪一个呢?

1 个答案:

答案 0 :(得分:0)

I've used something like the below:

 Vector3 tangent = Vector3.Cross( normal, Vector3.forward );
 if( tangent.magnitude == 0 ) {
   tangent = Vector3.Cross( normal, Vector3.up );
 }

Source: http://answers.unity3d.com/questions/133680/how-do-you-find-the-tangent-from-a-given-normal.html