Unity shader法线纹理应用

注:tangent : TANGENT; 类型为float4,  w可以用来翻转副法线

1.Unity切线空间问题和推理思考

有部分切线空间推导

https://www.jianshu.com/p/af800402f5db

2.Unity文档对Mesh.tangents说明:

https://docs.unity3d.com/ScriptReference/Mesh-tangents.html

Description

The tangents of the Mesh.

Tangents are mostly used in bump-mapped Shaders. A tangent is a unit-length vector that follows Mesh surface along horizontal (U) texture direction. Tangents in Unity are represented as Vector4, with x,y,z components defining the vector, and w used to flip the binormal if needed.

Unity calculates the other surface vector (binormal) by taking a cross product between the normal and the tangent, and multiplying the result by tangent.w. Therefore, w should always be 1 or -1.

You should calculate tangents yourself if you plan to use bump-mapped shaders on the Mesh. Assign tangents after assigning normals or using RecalculateNormals.

3.为什么要有切线空间(Tangent Space),它的作用是什么?

https://www.zhihu.com/question/23706933/answer/161968056

切线空间下计算:


//法线纹理,将法线信息存储在纹理当中(纹理颜色),通过映射变化得出法线方向
//切线空间下计算
Shader "MyShader/NormalMapTangentSpace"
{

    Properties
    {
		_Color("Color Tint", color) = (1,1,1,1)//控制整体色调
        _MainTex ("Main Texture", 2D) = "white" {}
		_BumpMap( "Normal Map", 2D) = "bump" {}
		_BumpScale( "Bump Scale", float) = 1.0//控制凹凸程度
		_Gloss("Gloss", Range(8,20) ) = 20
		_SpecularColor("Specular Color", color ) = (1,1,1,1)
		_DiffuseColor( "Diffuse Color", color ) = (1,1,1,1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
			Tags{ "LightMode" = "ForwardBase"}
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"
			#include "Lighting.cginc"

            struct a2v
            {
                float4 vertex : POSITION;//世界空间下顶点坐标
                float2 texcoord : TEXCOORD0;
				float3 normal : NORMAL;
				float4 tangent : TANGENT;//把顶点的切线方向填充到tangent变量中, w可以用来翻转副法线
            };

            struct v2f
            {
                float4 uv : TEXCOORD0;
                float4 pos : SV_POSITION;
				float3 lightDir : TEXCOORD1;
				float3 viewDir : TEXCOORD2;
            };

			fixed4 _Color;
            sampler2D _MainTex;
            float4 _MainTex_ST;
			sampler2D _BumpMap;
			float4 _BumpMap_ST;
			float _BumpScale;
			
			fixed4 _DiffuseColor;
			fixed4 _SpecularColor;
			float _Gloss;

            v2f vert (a2v v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);

				o.uv.xy = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;//获取主纹理的某一位置的最终纹理坐标
				o.uv.zw = v.texcoord.xy * _BumpMap_ST.xy + _BumpMap_ST.zw;//获取法线纹理的某一位置的最终纹理坐标

				//Compute the binormal计算副切线
				float3 binormal = cross(normalize(v.normal), normalize(v.tangent.xyz));

				//将模型空间下的切线方向, 副法线方向, 法线方向按照行排列 得出 模型空间到切线空间的变换矩阵
				float3x3 rotation = float3x3(v.tangent.xyz, binormal, v.normal);

				//也可以使用内部函数直接获取到 模型空间到切线空间的变换矩阵
				//TANGENT_SPACE_ROTATION;

				//Transform the light direction from object space to tangent space 将模型空间下顶点到光源的方向转换 为 切线空间下的方向
				o.lightDir = mul(rotation, ObjSpaceLightDir(v.vertex)).xyz;
				//Transform the view direction from object space to tangent space 将模型空间下顶点到视点的方向转换为 切线空间下的方向
				o.viewDir = mul(rotation, ObjSpaceViewDir(v.vertex)).xyz;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
				fixed3 tangentLightDir = normalize(i.lightDir);
				fixed3 tangentViewDir = normalize(i.viewDir);
				

				//Get the texel in the normal map 法线贴图采样
				fixed4 packedNormal = tex2D(_BumpMap, i.uv.zw);
				
				//Get the tangent normal 获取切线空间的法向量
				fixed3 tangentNormal;
				tangentNormal.xy = (2 * packedNormal - 1)*_BumpScale;
				tangentNormal.z = sqrt(1.0 - saturate(dot(tangentNormal.xy, tangentNormal.xy)));

				fixed3 albedo = tex2D(_MainTex, i.uv).rgb*_Color.rgb;

				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT * albedo;

				fixed3 diffuse = _LightColor0.rgb*albedo*saturate(dot(tangentNormal, tangentLightDir));

				fixed3 halfDir = normalize(tangentLightDir + tangentViewDir);
				fixed3 specular = _LightColor0.rgb * _SpecularColor.rgb*pow( saturate( dot( tangentNormal, halfDir ) ), _Gloss );

				return fixed4(ambient + diffuse + specular, 1.0);
            }
            ENDCG
        }
    }
}

 2.世界空间下计算:

// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'

Shader "MyShader/NormalMapWorldSpaceMat"
{
    Properties
    {
		_Color( "Color", color ) = (1,1,1,1)
        _MainTex ("Main Tex", 2D) = "white" {}
		_BumpMap("Bump Map", 2D) = "bump" {}
		_BumpScale( "Bump Scale", float) = 1.0
		_SpecularColor( "Specular Color", color ) = ( 1,1,1,1 )
		_Gloss( "Gloss", Range( 8, 256 ) ) = 20
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
			Tags{ "LightMode" = "ForwardBase"}
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"
			#include "Lighting.cginc"
            struct a2v
            {
                float4 pos : POSITION;
                float2 uv : TEXCOORD0;
				float4 tangent : TANGENT;
				float3 normal : NORMAL;
            };

            struct v2f
            {
                float4 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
				float4 TtoW0 : TEXCOORD1;//切线空间到世界空间变换矩阵的第一行
				float4 TtoW1 : TEXCOORD2;//切线空间到世界空间变换矩阵的第二行
				float4 TtoW2 : TEXCOORD3;//切线空间到世界空间变换矩阵的第三行
            };


			fixed4 _Color;
            sampler2D _MainTex;
            float4 _MainTex_ST;
			sampler2D _BumpMap;
			float4 _BumpMap_ST;
			float _BumpScale;
			fixed4 _SpecularColor;
			float _Gloss;

            v2f vert (a2v v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.pos);
                o.uv.xy = v.uv.xy*_MainTex_ST.xy + _MainTex_ST.zw;
				o.uv.zw = v.uv.xy*_BumpMap_ST.xy + _BumpMap_ST.zw;

				float3 worldPos = mul(unity_ObjectToWorld, v.pos).xyz;
				float3 worldNormal = UnityObjectToWorldNormal(v.normal);
				float3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz);
				float3 worldBinormal = cross(worldNormal, worldTangent)*v.tangent.w;

				o.TtoW0 = float4(worldTangent.x, worldBinormal.x, worldNormal.x, worldPos.x);
				o.TtoW1 = float4(worldTangent.y, worldBinormal.y, worldNormal.y, worldPos.y);
				o.TtoW2 = float4(worldTangent.z, worldBinormal.z, worldNormal.z, worldPos.z);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {

				fixed3 bump;
				bump.xy = UnpackNormal(tex2D(_BumpMap, i.uv.xy)).xy * _BumpScale;
				bump.z = saturate( sqrt(1 - dot(bump.xy, bump.xy)) );
				bump = normalize( half3(dot(i.TtoW0.xyz, bump), dot(i.TtoW1.xyz, bump), dot(i.TtoW2, bump)) );
				
				float3 worldPos = float3(i.TtoW0.w, i.TtoW1.w, i.TtoW2.w);
				fixed3 worldLightDir = normalize( UnityWorldSpaceLightDir(worldPos) );

				fixed3 albedo = tex2D(_MainTex, i.uv.xy).rgb*_Color.rgb;

				fixed3 diffuse = _LightColor0.rgb * albedo * saturate(dot(bump, worldLightDir));

				fixed3 worldViewDir = normalize(UnityWorldSpaceViewDir(worldPos));
				fixed3 halfDir = normalize(worldViewDir + worldLightDir);

				fixed3 specular = _LightColor0.rgb * _SpecularColor.rgb*pow(saturate(dot(bump, halfDir)), _Gloss);

				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT * albedo;
               
                return fixed4( ambient+diffuse+specular, 1.0 );
            }
            ENDCG
        }
    }
}

 

参考:《Unity Shader入门精要》

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值