冯乐乐的《Unity Shader入门精要》附带项目,其中部分shader已经修改测试
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

78 lines
3.0 KiB

Shader "Unlit/MineBumpTestShader2"
{
Properties {
_BumpMap("Normal Map", 2D) = "bump" {}
}
SubShader
{
Pass
{
Tags{"LightMode"="ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
#include "UnityCG.cginc"
sampler2D _BumpMap;
struct a2v{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float2 uv : TEXCOORD0;
};
struct v2f {
float3 worldPos : TEXCOORD0;
float2 uv : TEXCOORD1;
float4 pos : SV_POSITION;
half3 wNormal : TEXCOORD2;
half3 wTangent : TEXCOORD3;
half3 wBitangent : TEXCOORD4;
};
// vertex shader now also needs a per-vertex tangent vector.
// 顶点着色器现在也需要一个逐顶点的切线向量。
// in Unity tangents are 4D vectors, with the .w component used to
// 在Unity中,切线是一个四维的向量,w分向量用于
// indicate direction of the bitangent vector.
// 表现二次切线向量的方向
// we also need the texture coordinate.
// 我们仍然需要贴图来配合
v2f vert (a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.uv = v.uv;
o.wTangent = UnityObjectToWorldDir(v.tangent.xyz);
o.wNormal = UnityObjectToWorldNormal(v.normal);
// compute bitangent from cross product of normal and tangent
// 通过计算法线与切线的叉积,得到二次切线bitangent,叉积*切线方向
// half tangentSign = v.tangent.w * unity_WorldTransformParams.w;
// output the tangent space matrix
half tangentSign = v.tangent.w;
o.wBitangent = cross(o.wNormal, o.wTangent) * tangentSign;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
half3 tnormal = UnpackNormal(tex2D(_BumpMap, i.uv));
// transform normal from tangent to world space
// 将法线方向从切线空间转换到世界空间中。
float3x3 TBNMatrix = float3x3(i.wTangent,i.wBitangent,i.wNormal);
half3 worldNormal = mul(tnormal,TBNMatrix);
half3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);
fixed3 ambient = ShadeSH9(fixed4(worldNormal,1));
fixed3 diffuse = _LightColor0.rgb * saturate(dot(worldNormal, worldLightDir));
fixed4 c = fixed4(ambient+diffuse,1);
return c;
//return fixed4(tnormal,1);
}
ENDCG
}
}
}