創建卡通着色
這是有兩種不同的方式實現的:
但都是利用 自定義 光照模型來做的
第一種方式:通過一張 階梯圖 來約束 光照 能實現 三種階梯 效果
/// LightingToon 光照模型 /// 輸入的第一個參數 是 surf 的返回值 SurfaceOutput /// 第二個參數是 入射 光光線角度 /// 第三個參數爲 光線 衰減率 0-1 half4 LightingToon( SurfaceOutput s, half3 lightDir, half atten) { half NdotL = dot(s.Normal, lightDir); NdotL = tex2D(_RampTex, fixed2(NdotL,0.5)); fixed4 c; c.rgb = s.Albedo * _LightColor0.rgb * NdotL * atten; c.a = s.Alpha; return c; }
第二種方式: 通過代碼來實現的
/// LightingToon2 光照模型 /// 輸入的第一個參數 是 surf 的返回值 SurfaceOutput /// 第二個參數是 入射 光光線角度 /// 第三個參數爲 光線 衰減率 0-1 half4 LightingToon2(SurfaceOutput s, half3 lightDir, half atten) { half NdotL = dot(s.Normal, lightDir); half toon = (floor(NdotL * _ToonShadingLevels)) / (_ToonShadingLevels - 0.5); fixed4 c; c.rgb = s.Albedo * _LightColor0.rgb * toon * atten; c.a = s.Alpha; return c; }
Shader "Custom/chapter03/ToonShader"
{
Properties
{
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_RampTex("RampTex (RGB)", 2D) = "white" {}
_ToonShadingLevels("_ToonShadingLevels",Range(2,10)) = 10
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
//兩種 光照模型的 切換
#pragma surface surf Toon
//#pragma surface surf Toon2
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
sampler2D _MainTex;
sampler2D _RampTex;
float _ToonShadingLevels;
struct Input
{
float2 uv_MainTex;
};
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_BUFFER_END(Props)
void surf (Input IN, inout SurfaceOutput o)
{
fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
o.Albedo = c.rgb;
o.Alpha = c.a;
}
/// LightingToon 光照模型
/// 輸入的第一個參數 是 surf 的返回值 SurfaceOutput
/// 第二個參數是 入射 光光線角度
/// 第三個參數爲 光線 衰減率 0-1
half4 LightingToon( SurfaceOutput s, half3 lightDir, half atten)
{
half NdotL = dot(s.Normal, lightDir);
NdotL = tex2D(_RampTex, fixed2(NdotL,0.5));
fixed4 c;
c.rgb = s.Albedo * _LightColor0.rgb * NdotL * atten;
c.a = s.Alpha;
return c;
}
/// LightingToon2 光照模型
/// 輸入的第一個參數 是 surf 的返回值 SurfaceOutput
/// 第二個參數是 入射 光光線角度
/// 第三個參數爲 光線 衰減率 0-1
half4 LightingToon2(SurfaceOutput s, half3 lightDir, half atten)
{
half NdotL = dot(s.Normal, lightDir);
half toon = (floor(NdotL * _ToonShadingLevels)) / (_ToonShadingLevels - 0.5);
fixed4 c;
c.rgb = s.Albedo * _LightColor0.rgb * toon * atten;
c.a = s.Alpha;
return c;
}
ENDCG
}
FallBack "Diffuse"
}