• 【图形学】 22 基础纹理(三、凹凸映射切线空间的光照实现)


    来源:《UNITY SHADER入门精要》

    1、凹凸映射切线空间的光照实现

      我们要实现的是有深度效果的纹理贴图,我们是通过法线来实现的,主要通过法线贴图,然后把视线向量和光线向量转换到切线空间,在切线空间来进行计算

    Shader "Unity Shaders Book/Chapter 7/Normal Map In Tangent Space" {
    	Properties {
    		_Color ("Color Tint", Color) = (1, 1, 1, 1)
    		_MainTex ("Main Tex", 2D) = "white" {}
    		_BumpMap ("Normal Map", 2D) = "bump" {}
    		_BumpScale ("Bump Scale", Float) = 1.0
    		_Specular ("Specular", Color) = (1, 1, 1, 1)
    		_Gloss ("Gloss", Range(8.0, 256)) = 20
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

      老规矩,先给Shader命名,然后,定义它的 Properties语义块:_Color 基础的颜色,_MainTex 主要的纹理图,_BumpMap 法线纹理图,_BumpScale 法线的凹凸程度参数,_Specular 高光参数,_Gloss 光圈大小。这里不会有 _Diffues 属性了,因为之后的反射程度的参数会根据纹理和光线计算出来。

    	SubShader {
    		Pass { 
    			Tags { "LightMode"="ForwardBase" }
    		
    			CGPROGRAM
    			
    			#pragma vertex vert
    			#pragma fragment frag
    			
    			#include "Lighting.cginc"
    			
    			fixed4 _Color;
    			sampler2D _MainTex;
    			float4 _MainTex_ST;
    			sampler2D _BumpMap;
    			float4 _BumpMap_ST;
    			float _BumpScale;
    			fixed4 _Specular;
    			float _Gloss;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

      和 Properties语义块中的属性建立联系,同样,对于纹理的偏移系数,我们定义了 _MainTex_ST_BumpMap_ST 变量。

    			struct a2v {
    				float4 vertex : POSITION;
    				float3 normal : NORMAL;
    				float4 tangent : TANGENT;
    				float4 texcoord : TEXCOORD0;
    			};
    			
    			struct v2f {
    				float4 pos : SV_POSITION;
    				float4 uv : TEXCOORD0;
    				float3 lightDir: TEXCOORD1;
    				float3 viewDir : TEXCOORD2;
    			};
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

      我们定义用于输入输出的结构体。第 5 行的语义,TANGENT,也是Unity内置的语义,它和 法线 normal 不一样,它是 float4 类型的,因为我们需要 tangent.w 这个分量来决定切线空间中的第三个坐标轴——副切线的方向性。
      在顶点着色器的输出中,我们添加了两个变量来存储变换后的光照和视角方向。

    			float4x4 inverse(float4x4 input) {
    				#define minor(a,b,c) determinant(float3x3(input.a, input.b, input.c))
    				 //determinant(float3x3(input._22_23_23, input._32_33_34, input._42_43_44))
    				
    				float4x4 cofactors = float4x4(
    				     minor(_22_23_24, _32_33_34, _42_43_44), 
    				    -minor(_21_23_24, _31_33_34, _41_43_44),
    				     minor(_21_22_24, _31_32_34, _41_42_44),
    				    -minor(_21_22_23, _31_32_33, _41_42_43),
    				    
    				    -minor(_12_13_14, _32_33_34, _42_43_44),
    				     minor(_11_13_14, _31_33_34, _41_43_44),
    				    -minor(_11_12_14, _31_32_34, _41_42_44),
    				     minor(_11_12_13, _31_32_33, _41_42_43),
    				    
    				     minor(_12_13_14, _22_23_24, _42_43_44),
    				    -minor(_11_13_14, _21_23_24, _41_43_44),
    				     minor(_11_12_14, _21_22_24, _41_42_44),
    				    -minor(_11_12_13, _21_22_23, _41_42_43),
    				    
    				    -minor(_12_13_14, _22_23_24, _32_33_34),
    				     minor(_11_13_14, _21_23_24, _31_33_34),
    				    -minor(_11_12_14, _21_22_24, _31_32_34),
    				     minor(_11_12_13, _21_22_23, _31_32_33)
    				);
    				#undef minor
    				return transpose(cofactors) / determinant(input);
    			}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

      以上,我们只能自己写一个逆矩阵,因为unity它不再提供 inverse 的函数了。
      作者的参考: http://answers.unity3d.com/questions/218333/shader-inversefloat4x4-function.html。

    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;
    
    	// 构造从 切线空间 到 世界空间 的变换矩阵
    	fixed3 worldNormal = UnityObjectToWorldNormal(v.normal); 
    	fixed3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz);  
    	fixed3 worldBinormal = cross(worldNormal, worldTangent) * v.tangent.w; 
    
    			/*
    	float4x4 tangentToWorld = float4x4(worldTangent.x, worldBinormal.x, worldNormal.x, 0.0,
    								  worldTangent.y, worldBinormal.y, worldNormal.y, 0.0,
    								  worldTangent.z, worldBinormal.z, worldNormal.z, 0.0,
    							           0.0, 0.0, 0.0, 1.0);
    // 切线空间 到 世界空间 的矩阵,可以由列向量按列排列来构造,然后取逆得到 世界 到 切线的矩阵
    	float3x3 worldToTangent = inverse(tangentToWorld);
    			*/
    				
    //如果它只有平移和旋转,没有缩放,那就是正交矩阵,直接通过它的转置可以得到它的逆矩阵
    	float3x3 worldToTangent = float3x3(worldTangent, worldBinormal, worldNormal);
    
    // Transform the light and view dir from world space to tangent space
    	o.lightDir = mul(worldToTangent, WorldSpaceLightDir(v.vertex));
    	o.viewDir = mul(worldToTangent, WorldSpaceViewDir(v.vertex));
    	return o;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

      我们这里构造的是从 切线空间 到 世界空间 的变换矩阵。按照冯乐乐的代码注释,这样写可以处理统一缩放的矩阵和非统一缩放的矩阵。因为不能保证它是正交矩阵的时候,我们就只能自己计算它的逆。
      第 26、27 行,我们使用了 Unity 的内置函数 WorldSpaceLightDir()WorldSpaceViewDir() 来得到世界空间下的光照。然后它们乘以 rotation 变换到 切线空间。

    /// 以下重写的顶点着色器只适用于统一缩放的矩阵,不统一缩放的矩阵不行。
    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) ) * v.tangent.w;
    		// Construct a matrix which transform vectors from object space to tangent space
    	float3x3 rotation = float3x3(v.tangent.xyz, binormal, v.normal);
    		
    		// Or just use the built-in macro
    	//TANGENT_SPACE_ROTATION;
            
    		// Transform the light direction from object space to tangent space
    	o.lightDir = mul(rotation, normalize(ObjSpaceLightDir(v.vertex))).xyz;
    		
    		// Transform the view direction from object space to tangent space
    	o.viewDir = mul(rotation, normalize(ObjSpaceViewDir(v.vertex))).xyz;		
    	return o;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

      注意第 15 行,这里也可以使用内置定义宏,其实和我们写的一样,这里,我们查看了源码:

    // Declares 3x3 matrix 'rotation', filled with tangent space basis
    #define TANGENT_SPACE_ROTATION \
        float3 binormal = cross( normalize(v.normal), normalize(v.tangent.xyz) ) * v.tangent.w; \
        float3x3 rotation = float3x3( v.tangent.xyz, binormal, v.normal )
    
    • 1
    • 2
    • 3
    • 4

      其实和我们写的方式是一样的。看第 1 行,我们要使用这个宏,会提供矩阵 rotation。

    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);
    	fixed3 tangentNormal;
    	
    		//如果我们没有在选项中把它设置为 “Normal map”,就需要手动在代码中解决。
    	//tangentNormal.xy = (packedNormal.xy * 2 - 1) * _BumpScale;
    	//tangentNormal.z = sqrt(1.0 - saturate(dot(tangentNormal.xy, tangentNormal.xy)));
    				
    		// Or mark the texture as "Normal map", and use the built-in funciton
    	tangentNormal = UnpackNormal(packedNormal);
    				
    	fixed3 albedo = tex2D(_MainTex, i.uv).rgb * _Color.rgb;
    				
    	fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
    				
    	fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(tangentNormal, tangentLightDir));
    
    	fixed3 halfDir = normalize(tangentLightDir + tangentViewDir);
    	fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(tangentNormal, halfDir)), _Gloss);
    				
    	return fixed4(ambient + diffuse + specular, 1.0);
    			}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

      我们根据之前在顶点着色器中计算过的 切线空间的 光线向量 和 视线向量。所有计算都在切线空间中完成。
      第 6 行,我们使用 tex2D()函数 来采样 法线纹理 _BumpMap
      第 9-11 行,如果我们没有在选项中把 _BumpMap 设置为 “Normal map”,我们就需要在代码中转换。正如之前讲理论的时候所说,法线纹理中存储的是法线的xyz经过在 颜色空间 中映射之后,存储得到的像素值: p i x e l = n o r m a l + 1 2 pixel=\frac{normal+1}{2} pixel=2normal+1。因此,我们需要把存储的信息反映射回来: n o r m a l = 2 × p i x e l − 1 normal = 2\times pixel - 1 normal=2×pixel1 。然后我们需要乘以 _BumpScale(用以控制凹凸程度)来得到 tangentNormal
      当然,我们应当把纹理类型标识成 Normal map,Unity 会根据平台来选择不同的压缩方法。这时,这时,我们就不能用自己的方法反映射出法线信息了。因为此时 _BumpMap 的RGB分量并不再是法线方向的XYZ值了。所以我们应该使用 Unity 的内置函数 UnpackNormal 来得到正确的法线方向。

      我们在第 14 行用到了这个内置函数,我们在UnityCG.cginc中能找到:

    inline fixed3 UnpackNormal(fixed4 packednormal)
    {
    #if defined(UNITY_NO_DXT5nm)
        return packednormal.xyz * 2 - 1;
    #elif defined(UNITY_ASTC_NORMALMAP_ENCODING)
        return UnpackNormalDXT5nm(packednormal);
    #else
        return UnpackNormalmapRGorAG(packednormal);
    #endif
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

      只有当我们把法线纹理的纹理类型标识成 Normal map 时,可以使用 Unity 内置函数 UnpackNormal 来得到正确的法线方向。按照不同的压缩方式,会有不同的解压方法。

    			ENDCG
    		}
    	} 
    	FallBack "Specular"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    springboot基础(50):linux安装kafka
    商业化广告--体系学习-- 6 -- 行业蓝图篇 -- 那些产品适合采用广告模式变现
    Java-Day19 Java集合(集合框架、Collection接口、List接口及List接口实现类)
    第5章相似矩阵及二次型(4)
    如何将安防视频监控系统/视频云存储EasyCVR平台推流到公网直播间?
    Mybatis复杂查询及动态SQL
    基于改进全卷积一阶检测器的桥梁裂缝定位算法
    Python实现视频字幕时间轴格式转换
    深度解读财团参与Twitter私有化的投资逻辑
    Vue 搭配 Spring MVC 创建一个 web 项目
  • 原文地址:https://blog.csdn.net/qq_40891541/article/details/126518563