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入门精要》

### Unity Shader法线贴图采样出现马赛克的原因及解决方案 #### 原因分析 在 Unity Shader 中,当法线贴图采样时出现马赛克现象,通常是由以下几个原因引起的: 1. **纹理过滤模式 (Filter Mode)** 如果纹理的 `Filter Mode` 设置为 `Point`,则不会对纹理进行任何滤波操作。这种情况下,纹理会被简单地按最近邻算法采样,导致放大时会出现明显的马赛克效果[^2]。 2. **Mipmap 的使用不当** Mipmap 是一种优化技术,通过预先生成不同分辨率的纹理层次结构来减少渲染开销并提高性能。然而,如果未正确配置 Mipmap 或者禁用了它,则可能导致纹理缩放时不平滑,从而引发马赛克问题[^4]。 3. **UV 映射不均匀** UV 映射决定了模型表面如何映射到二维纹理上。如果 UV 贴图存在拉伸或者扭曲的情况,可能会使得某些区域内的像素密度较低,进而造成视觉上的马赛克效应。 4. **纹理尺寸不足或压缩格式不合适** 使用低分辨率的纹理文件或不适合当前场景需求的压缩格式也可能引起细节丢失和锯齿状边缘,表现为马赛克形式[^1]。 --- #### 解决方案 针对上述可能的原因,以下是几种有效的解决方法: 1. **调整 Filter Mode** 将纹理的 `Filter Mode` 改为 `Bilinear` 或 `Trilinear`。其中: - `Bilinear`: 对每个纹素周围的四个相邻点执行一次双线性插值。 - `Trilinear`: 不仅进行了两次双线性插值,还考虑了 LOD 层次间的过渡,因此能够显著改善大范围缩放下的图像质量[^3]。 修改方式如下所示: ```csharp TextureImporter textureImporter = AssetImporter.GetAtPath(texturePath) as TextureImporter; if (textureImporter != null) { textureImporter.filterMode = FilterMode.Trilinear; // 更改为 Trilinear 模式 } ``` 2. **启用 Mipmaps 并合理设置其参数** 确保启用了 Mipmaps 功能,并适当调节各层级之间的权重分布以及偏移量 (`Bias`) 来获得更自然的结果。此外还可以尝试开启 Anisotropic Filtering(各项异性过滤),进一步提升倾斜视角下的清晰度。 3. **优化 UV Mapping** 检查模型的 UV 展开情况,确保没有重叠、翻转或其他异常状况发生;必要时重新手动编辑 UV 图形以达到理想状态。 4. **选用高质量纹理资源** 提高原始素材的质量,比如增大图片尺寸至更高 DPI 数值,或是采用无损压缩算法保存数据等措施均有助于缓解此类问题的发生几率。 5. **自定义采样逻辑** 若默认行为仍无法满足特定项目的需求,则可以通过编写 HLSL/CG 片段来自定义采样过程。例如利用 `tex2Dlod()` 函数显式指定所需 miplevel 实现精确控制: ```hlsl half4 color = tex2Dlod(_MainTex, float4(i.uv.xy * _TilingFactor, 0, 0)); ``` --- ### 总结 综上所述,Unity Shader法线贴图采样的马赛克问题是多种因素共同作用所致,需从多个角度出发综合考量才能彻底消除该缺陷。具体实施过程中可根据实际应用场景灵活运用以上提到的各种手段加以改进。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值