练手之RimLight
简单写写,练下手~
Shader "James/VP Shader/RimLight" { Properties { _MainTex("MainTex", 2D) = "white" {} _Color("Color", Color) = (1, 1, 1, 1) _RimColor("RimColor", Color) = (1, 1, 1, 1) _RimPower("RimPower", Range(0, 36)) = 0.1 _RimIntensity("RimIntensity", Range(0, 100)) = 3 } SubShader { Tags { "Queue" = "Transparent" } Pass { ZWrite Off Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float4 pos : SV_POSITION; float3 color : COLOR0; float2 uv : TEXCOORD0; float3 normal : TEXCOORD1; float3 objViewDir : TEXCOORD2; }; sampler2D _MainTex; float4 _MainTex_ST; float4 _Color; v2f vert(appdata_base v) { v2f o; o.pos = mul (UNITY_MATRIX_MVP, v.vertex); o.normal = v.normal; o.objViewDir = normalize(ObjSpaceViewDir(v.vertex)); o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); return o; } float4 _RimColor; float _RimPower; float _RimIntensity; half4 frag(v2f i) : COLOR { float rimSin = 1 - max(0, dot(i.normal, i.objViewDir)); float rimFactor = pow(rimSin, _RimPower) * _RimIntensity; float3 rimColor = rimFactor * _RimColor; float4 mainColor = tex2D(_MainTex, i.uv); float4 finalColor = mainColor * _Color; finalColor.rgb +=rimColor; return finalColor; } ENDCG } } FallBack "VertexLit" }
将上面的Shader改写一下,添加BumpTex,并使用一张RimTex来映射边缘光的强度:
Shader "James/VP Shader/BumpRimLight" { Properties { _MainTex("MainTex", 2D) = "white" {} _BumpTex("BumpTex", 2D) = "bump" {} _Color("Color", Color) = (1, 1, 1, 1) _RimColor("RimColor", Color) = (1, 1, 1, 1) _RimIntensity("RimIntensity", Range(0, 3)) = 0.1 _RimTex("RimTex", 2D) = "white" {} } SubShader { Tags { "Queue" = "Transparent" } Pass { Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float4 pos : SV_POSITION; float3 color : COLOR0; float2 uv : TEXCOORD0; float3 tangentSpackLightDir : TEXCOORD1; }; sampler2D _MainTex; sampler2D _BumpTex; sampler2D _RimTex; float4 _MainTex_ST; float4 _BumpTex_ST; float4 _RimTex_ST; float4 _Color; float4 _RimColor; float _RimIntensity; v2f vert(appdata_tan v) { v2f o; o.pos = mul (UNITY_MATRIX_MVP, v.vertex); float3 objViewDir = normalize(ObjSpaceViewDir(v.vertex)); o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); // 副法向量 float3 binormal = cross(normalize(v.vertex), normalize(v.tangent.xyz)); // 切空间矩阵 float3x3 rotation = float3x3(v.tangent.xyz, binormal, v.normal); // 切空间视线方向 o.tangentSpackLightDir = mul(rotation, objViewDir); return o; } half4 frag(v2f i) : COLOR { // 切空间法线,NormalMap默认带的是切空间的值 half3 tangentSpaceNormal = (tex2D(_BumpTex, i.uv).rgb * 2.0) - 1.0; float rimFactor = 1 - max(0, dot(tangentSpaceNormal, i.tangentSpackLightDir)); float rimIntensity = tex2D(_RimTex, rimFactor.xx).r; float3 rimColor = rimIntensity * _RimColor * _RimIntensity; float4 mainColor = tex2D(_MainTex, i.uv); float4 finalColor = mainColor * _Color; finalColor.rgb += rimColor; return finalColor; } ENDCG } } FallBack "VertexLit" }
注意上述代码是在切空间中计算rim的颜色强度。