Shader "FZDL_Shader/ASETemplate_CharacterAdvance"
{
	Properties
	{
		[Header(______________Debug______________)]
		[Toggle(_DEBUG_ON)]_DebugMode("Debug Mode",float) = 0
		[Toggle(_USE_MHY_CHANNEL_ON)]_use_Mhy_Channel("use Mhy Channel",float) = 0
		[Toggle(_VIEW_MAINTEX_ON)] _ViewMainTex("View MainTex",float) = 0
		[Toggle(_CLOSE_LIGHT_ON)] _Close_light_on("关闭环境颜色影响",float) = 0
		[Toggle(_USE_DEFAULT_VCOLOR)] _use_default_VertexColor("无顶点色",float) = 0


		[Header(__________________MainTex__________________)]
		_MainTex("MainTex", 2D) = "white" {}
		[HideInInspector][HDR]_MainTexAdjustColor("MainTex Adjust Color",color) = (0.5,0.5,0.5,1) 
		[Toggle]_UseBackFaceUV2 ("背面二套UV",float) = 0
		[Enum(None, 0, AlphaTest, 1, Emission, 2, FaceBlush, 3)] _MainTexAlphaUse ("Main Tex Alpha Use", Float) = 0


		[Header(__________________LightMapTex__________________)]
		[NoScaleOffset]_LightMapTex("LightMapTex",2D) = "gray" {}

		[Header(__________________Ramp__________________)]
		[NoScaleOffset]_RampTex("RampTex",2D) = "white" {}
		_LightArea("Ramp 起始亮度",float) = 1
		_ShadowRampWidth("Ramp 色带宽度",float) = 0.2

		[Header(__________________MetalPart__________________)]
		[NoScaleOffset]_MTMap("_MTMap",2D) = "gray" {}
		_MTMapTileScale("贴图拉伸",float) = 1  //Metal Map Scale
		[HideInInspector]_MTMapBrightness("强度",float) = 1 //Metal Map Intensity
		_MTMapLightColor("金属亮区颜色",color) = (1,1,1,1)
		_MTMapDarkColor("金属暗区颜色",color) = (1,1,1,1)
		_MTShadowMultiColor("处于阴影时颜色",color) = (1,1,1,1)
		[HideInInspector]_MTSpecularColor("Metal Specular Color",color) = (1,1,1,1)
		_MTShininess("金属高光系数",float) = 1
		_MTSpecularScale("金属高光强度",float) = 1
		_MTSpecularAttenInShadow("处于阴影时金属高光强度",float) = 1


		[Header(_________________ID 1___________________)]
		_TintColor ("TintColor",color) = (1,1,1,1)
		_SpecularColor ("高光颜色", Color) = (1,1,1,1)
		_Shininess("高光系数",float) = 1
		_SpecMulti("高光强度",float) = 1
		_OutlineColor ("Outline 颜色",color) = (1,1,1,1)

		[Header(__________________ID_2__________________)]
		_TintColor_1 ("TintColor",color) = (1,1,1,1)
		_Shininess_1 ("高光系数",float) = 1
		_SpecMulti_1 ("高光强度",float) = 1
		_OutlineColor_1 ("Outline 颜色 ",color) = (1,1,1,1)

		[Header(__________________ID_3__________________)]
		_TintColor_2 ("TintColor",color) = (1,1,1,1)
		_Shininess_2 ("高光系数",float) = 1
		_SpecMulti_2 ("高光强度",float) = 1
		_OutlineColor_2 ("Outline 颜色 ",color) = (1,1,1,1)
		
		[Header(__________________ID_4__________________)]
		_TintColor_3 ("TintColor",color) = (1,1,1,1)
		_Shininess_3 ("高光系数",float) = 1
		_SpecMulti_3 ("高光强度",float) = 1
		_OutlineColor_3 ("Outline 颜色 ",color) = (1,1,1,1)
		
		[Header(__________________ID_5__________________)]
		_TintColor_4 ("TintColor",color) = (1,1,1,1)
		_Shininess_4 ("高光系数",float) = 1
		_SpecMulti_4 ("高光强度",float) = 1
		_OutlineColor_4 ("Outline 颜色",color) = (1,1,1,1)

		[Header(__________________Outline__________________)]

		[HideInInspector]_OutlineWidthAdjustZs("法线外拓深度范围",vector) = (1,6,15,0)
		[HideInInspector]_OutlineWidthAdjustScales("法线外拓深度范围内Scale",vector) = (2,6,15,0)

        _OutlineWidth("Outline 宽度",float) = 1
        _MaxOutlineZOffset("深度偏移量",float) = 1



		[Header(__________________FaceMap__________________)]
		[Toggle(FACEMAP_ON)] _UseFaceMapNew ("Use Face Map", Int) = 0
		[NoScaleOffset]_FaceMapTex ("Face Map Tex (A Linear)", 2D) = "gray" {}
		[HideInInspector]_FaceMapRotateOffset ("Face Map Rotate Offset", Range(-1, 1)) = 0
		[HideInInspector]_FaceMapSoftness ("Face Map Softness", Range(0.000001, 1)) = 0.000001
		_FaceShadowColor("脸部阴影色",color) = (1,1,1,1)

		[Header(__________________Enviroment__________________)]	//环境变量相关
		[Toggle]_IsInShadowInScene ("环境中处于阴影区",float) = 0
		[HideInInspector]_OverrideLightDir ("设置补偿光照方向与强度",vector) = (1,0,0,1)
		[HideInInspector]_OverrideLightDirInShadow ("设置阴影区域补偿光照方向与强度",vector) = (1,0,0,1)

		_OverrideLightColor ("补偿光照颜色",color) = (0,0,0,0)
		[HideInInspector]_ES_CharacterMainLightColor("主光源颜色",color) = (1,1,1,1)

		_ES_CharacterMainLightBrightness("光照强度",float) = 2
		_ES_CharacterColorTone("Ramp 色调冷暖调节",range(0,1)) = 1
		_ES_CharacterAmbientBrightness("场景环境整体亮度",float) = 1
		_ES_CharacterAmbientLightColor("环境光颜色",color) = (1,1,1,1)
		[HideInInspector]_ES_CharacterMainLightRatio("主光源占比",range(0,1)) = 0.5
		[HideInInspector]_ES_CharacterAmbientLightRatio("环境光占比",Range(0,1)) = 0.3
	}

	SubShader
	{
		
		Tags
		{
			"RenderPipeline" = "UniversalPipeline"
		    "RenderType"="Opaque"
            "Queue"="Geometry+0" 
		}
	


		HLSLINCLUDE

		//--------- Inlucde Filelist -----------
		//--------------------------------------
	    #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

		//------- Shader KEYWORD Define --------
		//--------------------------------------





		
		//---------- Varials Define ------------
		//--------------------------------------




		//------------- Functions --------------
		//--------------------------------------


		//----------- alpha转换为chanelID ----------
		float FetchMaterialId(in half a)
		{
			float materialId = 0;

		#ifdef _USE_MHY_CHANNEL_ON
			if (a >= 0.8)
				materialId = 1;
			if ( a >= 0.4 && a < 0.6)
				materialId = 2;
			if ( a >= 0.2 && a < 0.4)
				materialId = 3;
			if (a >= 0.6 && a < 0.8)
				materialId = 4;
		#else
			if (a >= 0.8)
				materialId = 4;
			if ( a >= 0.4 && a < 0.6)
				materialId = 2;
			if ( a >= 0.2 && a < 0.4)
				materialId = 1;
			if (a >= 0.6 && a < 0.8)
				materialId = 3;
		#endif	
			return materialId;
		}

		ENDHLSL



		pass
		{
			Name "Character"
			Tags{"LightMode" = "UniversalForward"}

			Cull Off


			HLSLPROGRAM

			#pragma vertex character_vert
            #pragma fragment character_frag

			//--------- Inlucde Filelist -----------
			//--------------------------------------
		    #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

			//------- Shader KEYWORD Define --------
			//--------------------------------------

			#define BACK_FACE_ON
			#pragma shader_feature_local FACEMAP_ON 

			#pragma shader_feature_local _DEBUG_ON 
			#pragma shader_feature_local _USE_MHY_CHANNEL_ON 
			#pragma shader_feature_local _VIEW_MAINTEX_ON 
			#pragma shader_feature_local _CLOSE_LIGHT_ON 
			#pragma shader_feature_local _USE_DEFAULT_VCOLOR 



			
			//---------- Varials Define ------------
			//--------------------------------------

            TEXTURE2D(_MainTex);      		SAMPLER(sampler_MainTex);
            TEXTURE2D(_LightMapTex);     	SAMPLER(sampler_LightMapTex);
            TEXTURE2D(_MTMap);       		SAMPLER(sampler_MTMap);
            TEXTURE2D(_RampTex);       		SAMPLER(sampler_RampTex);
            TEXTURE2D(_FaceMapTex);       	SAMPLER(sampler_FaceMapTex);

			CBUFFER_START(UnityPerMaterial)
				
				//MainTex 相关
				float4 _MainTex_ST;
				float4 _MainTexAdjustColor;
				float _UseBackFaceUV2;
				float _MainTexAlphaUse;


				//Ramp 相关
				float _LightArea;
				float _ShadowRampWidth;

				//Metal 部分
				float _MTMapTileScale;
				float _MTMapBrightness;
				float4 _MTMapLightColor;
				float4 _MTMapDarkColor;
				float4 _MTShadowMultiColor;
				float4 _MTSpecularColor;
				float _MTShininess;
				float _MTSpecularScale;
				float _MTSpecularAttenInShadow;


				//Base Attribute
				float4 _TintColor;
				float3 _SpecularColor;
				float _Shininess;
				float _SpecMulti;

				//Channel 1 Attribute
				float4 _TintColor_1;
				float _Shininess_1;
				float _SpecMulti_1;

				//Channel 2 Attribute
				float4 _TintColor_2;
				float _Shininess_2;
				float _SpecMulti_2;
				
				//Channel 3 Attribute
				float4 _TintColor_3;
				float _Shininess_3;
				float _SpecMulti_3;
				
				//Channel 4 Attribute
				float4 _TintColor_4;
				float _Shininess_4;
				float _SpecMulti_4;


				//FaceMap
				float _FaceMapRotateOffset;
				float _FaceMapSoftness;
				float4 _FaceShadowColor;

				//环境变量相关
				float _IsInShadowInScene; 

			CBUFFER_END

			//覆盖光照
			float4 _OverrideLightDir;
			float4 _OverrideLightDirInShadow;
			float4 _OverrideLightColor;
			
			float4 _ES_CharacterMainLightColor;
			float _ES_CharacterMainLightBrightness;		
			float _ES_CharacterMainLightRatio;
			float _ES_CharacterColorTone;//Ramp 冷暖色调节

			float4 _ES_CharacterAmbientLightColor;
			float _ES_CharacterAmbientBrightness;
			float _ES_CharacterAmbientLightRatio;


			//---------- Appdata/v2f Struct --------
			//--------------------------------------
				
			struct character_appdata
			{
				float4 vertex : POSITION;
				float3 normal : NORMAL;
				float2 uv : TEXCOORD0;
				float2 uv2 :TEXCOORD1;
				float4 color : COLOR;
				/*ase_vdata:p=p;n=n;uv0=tc0.xy;c=c;t=t*/


			//#if defined(SUPPORT_INSTANCED_SKINNING)
			//	FZDL_BAKED_SKIN_INSTANCING_ATTRIBUTES
			//#endif    

			//	UNITY_VERTEX_INPUT_INSTANCE_ID
			};



			struct character_v2f
			{
				float4 position : SV_POSITION;
				half4 color : COLOR0;
				float4 texcoord : TEXCOORD0;
				float4 normalAndDiff : TEXCOORD1;
				float4 screen : TEXCOORD2;
				float3 worldPos : TEXCOORD3;

				#ifdef FACEMAP_ON
				half3 faceMapParams : TEXCOORD4;
				#endif


				//float4 isInShadow : TEXCOORD4;
				//float4 fogCoord : TEXCOORD5;

				/*ase_interp(5,7):sp=sp.xyzw;uv0=tc0.xyzw;uv1=tc1.xyzw;uv2=tc2.xyzw;c=c*/

				//UNITY_VERTEX_INPUT_INSTANCE_ID
			};

			//---------- Macro Consts --------------
			//--------------------------------------

			#define SHADOW_RAMP_COUNT 10
			#define PACKED_SHADOW_RAMP_V_STEP 0.1
			#define PACKED_SHADOW_RAMP_V_HALF_STEP 0.05
			#define PACKED_SHADOW_RAMP_COOL_V_START 0.5

			#define METAL_MAT_THRESHOLD 0.9 // lightmap.r > 0.9 to mark metal
			#define NON_EMISSION_MAX_COLOR_SCALE 1.1 // the max color scale allowed for non emission part
			#define RAD2DEG 57.29578



			//---------- Functions -----------------
			//--------------------------------------

			half diffuse_factor(half3 N, half3 L)
			{
				// multiply by 0.4975 instead of 0.5 for some precision reason
				return dot(N, L) * 0.4975f + 0.5f;
			}

			half specular_factor(half3 N, half3 H, half shininess)
			{
				return pow(max(dot(N, H), 0.001), shininess);
			}

			half rim_factor(half3 N, half3 V, half shininess)
			{
				return pow(1.0f - clamp(dot(N, V), 0.001, 0.999), shininess);
			}

			
			
			//-------------- Vert ------------------
			//--------------------------------------

			character_v2f character_vert(character_appdata v/*ase_vert_input*/)
			{
				character_v2f o = (character_v2f)0;
			 
				//--------- 设置isInShadow状态 --------
				//o.isInShadow.x = _IsInShadowInScene;

				float3 lightDir = _IsInShadowInScene?_OverrideLightDirInShadow.xyz:_OverrideLightDir.xyz;
				lightDir = normalize(lightDir);

				lightDir = _MainLightPosition.xyz;

				//-------- 计算常规顶点数据 -----------
				o.color = v.color;
				o.texcoord.xy = TRANSFORM_TEX(v.uv,_MainTex);
				o.texcoord.zw = TRANSFORM_TEX(v.uv2,_MainTex);

				o.worldPos = TransformObjectToWorld(v.vertex.xyz);
				o.position = TransformWorldToHClip(o.worldPos);
				o.screen = ComputeScreenPos(o.position);

				o.normalAndDiff.xyz = TransformObjectToWorldNormal(v.normal,true);
				
				//--------- N·L传递 ------------------
				o.normalAndDiff.w = diffuse_factor(o.normalAndDiff.xyz,lightDir.xyz); 


				//face
				#ifdef FACEMAP_ON

				//计算光照在面部object space 方向
				half3 lightLocalDir = TransformWorldToObjectNormal(lightDir,true);

				//计算以Z轴为起点，光照方向的角度
				half deltaAngle = atan2(lightLocalDir.x,lightLocalDir.z) * RAD2DEG;

				//不同测光照 会翻转UV 使得 光照侧一定是亮部
				bool flipUV = deltaAngle > 0 ;
				float2 faceUV = v.uv;
				if(flipUV)
				{
					faceUV.x = 1 - faceUV.x; 
				}

				//根据光照在脸部正方向角度 设置 过渡阈值
				float lightingThreshold = abs(deltaAngle / 180);
				lightingThreshold = smoothstep(max(_FaceMapRotateOffset,0),min(1 + _FaceMapRotateOffset,1),lightingThreshold);
				lightingThreshold = clamp(lightingThreshold, 0.0001, 0.9999);

				o.faceMapParams = half3(faceUV,lightingThreshold);

				#endif


				#if defined(_DEBUG_ON) && defined(_USE_DEFAULT_VCOLOR)
					o.color.r = 1; 
					o.color.g = 0.5; 
				#endif

				return o;	
			}


			//-------------- Frag ------------------
			//--------------------------------------

			half4 character_frag (character_v2f i
		#ifdef BACK_FACE_ON 
			,	float facing : VFACE 
		#endif 
			) : SV_Target
            {
				
				//------------ 基础赋值/定义/计算 ----------
				float3 N = i.normalAndDiff.xyz;
				float2 uv = i.texcoord.xy;
				float isInShadow = _IsInShadowInScene;

					//---------- 背面 ---------
				#ifdef BACK_FACE_ON					
					int isBack = facing < 0;
					// if(isBack & _UseBackFaceUV2)
					// {
					// 	uv = i.texcoord.zw;
					// }
					if(isBack)
					{
						N = -N;
						isInShadow = 1;
					}
				#endif

				float3 lightDir = _IsInShadowInScene?_OverrideLightDirInShadow.xyz:_OverrideLightDir.xyz;
				lightDir = normalize(lightDir);
				lightDir = _MainLightPosition.xyz;


				half3 V = normalize(GetCameraPositionWS() - i.worldPos);
                half3 H = normalize(lightDir + V);
				float N_dot_L = i.normalAndDiff.w;



				//----------- lightMap采样 ------------
				//		R: >0.9 ? isMetal:specular intensity
				//		G: AO
				//		B: isMetal?specular intensity:specular threshold
				//		A: fetch channel id
				half4 lightMapCol = SAMPLE_TEXTURE2D(_LightMapTex,sampler_LightMapTex,uv);



				//----------- 变量定义 ----------------
				float3 rampUV = 0;
				float4 tintColor = _TintColor;
				
				half shininess = _Shininess;
				half specMulti = _SpecMulti;

				//----------- 获取正确通道变量 --------
				if(1)
				{	
					float cnlID = FetchMaterialId(lightMapCol.a);

					//计算采用哪一条ramp
					rampUV.y = 1 - PACKED_SHADOW_RAMP_V_STEP * cnlID + PACKED_SHADOW_RAMP_V_HALF_STEP;
					rampUV.z = rampUV.y - PACKED_SHADOW_RAMP_COOL_V_START;

				
					if (cnlID == 1)
					{
						tintColor = _TintColor_1;		
						shininess = _Shininess_1;
						specMulti = _SpecMulti_1;
					}

					if (cnlID == 2)
					{
						tintColor = _TintColor_2;
						shininess = _Shininess_2;
						specMulti = _SpecMulti_2;
					}

					if (cnlID == 3)
					{
						tintColor = _TintColor_3;
						shininess = _Shininess_3;
						specMulti = _SpecMulti_3;
					}

					if (cnlID == 4)
					{
						tintColor = _TintColor_4;
						shininess = _Shininess_4;
						specMulti = _SpecMulti_4;					
					}	
				}
				 

				//------------ Base Color -------------
				half4 mainTexCol = SAMPLE_TEXTURE2D(_MainTex,sampler_MainTex,uv);


				// //特殊处理
				// 	// 2*A*B
				// 	half3 multColor = _MainTexAdjustColor.rgb * mainTexCol.rgb * 2;
				// 	// 1-2*(1-A)*(1-B)
				// 	half3 screenColor = (_MainTexAdjustColor.rgb + mainTexCol.rgb) * 2 - multColor - 1;
				// 	mainTexCol.rgb = lerp(multColor, screenColor, mainTexCol.rgb > 0.5);

				mainTexCol.rgb *= tintColor.rgb;





				//------------ 计算rampUV.x -------------
				
				float vertAO = i.color.r;	//顶点颜色R做AO值
				float lightMapAO = lightMapCol.g;

				float aoIntensity = vertAO * lightMapAO;

				//叠加AO因素获得光亮指数
				float threshhold_light = N_dot_L;
				if (aoIntensity < 0.05)
					threshhold_light = 0;
				else if (aoIntensity > 0.95)
					threshhold_light = 1;
				else
					threshhold_light = (threshhold_light + aoIntensity) * 0.5f;
				
				//Ramp过度范围确定,可以用_LightArea控制
				float shadowStrength = (_LightArea - threshhold_light) / _LightArea;

				float vertRampWidth = i.color.g;	//顶点颜色G做ramp宽度参数
				float rampWidth = _ShadowRampWidth * max(vertRampWidth*2,0.01);
				
				rampUV.x = 1 - min(shadowStrength/rampWidth, 1);

				if(isInShadow)
				{
					rampUV.x = 0;
				}
				float isShadowRampPart = step(rampUV.x,0.99);	//不为1都是处于ramp区域内



				//------------ 光照计算 ---------------	
				float isMetal = lightMapCol.r > METAL_MAT_THRESHOLD;

				#ifdef FACEMAP_ON
					isMetal = 0;
				#endif

				half3 diffColor;
				half3 specColor;


				if(isMetal)
				//-------------- 是金属的情况 -------------
				{
					half3 viewNormal = TransformWorldToViewDir(N);

					half2 metalMapUV = viewNormal.xy;
					metalMapUV.x *= _MTMapTileScale;
					metalMapUV = metalMapUV * 0.5 + 0.5;
					half metalMapValue = SAMPLE_TEXTURE2D(_MTMap,sampler_MTMap,metalMapUV).r;
					metalMapValue = saturate(metalMapValue * _MTMapBrightness);
					float3 inputMetalLightPartColor = lerp(_MTMapDarkColor.rgb, _MTMapLightColor.rgb, metalMapValue) * (mainTexCol.rgb);
					float3 inputMetalShadowMultiColor = _MTShadowMultiColor.rgb;

					half NoH = max(dot(N, H), 0.001); 
					half specular = pow(NoH, _MTShininess);
					specular = specular * _MTSpecularScale;
					specular = saturate(specular);
					float3 inputMetalSpecularColor = _MTSpecularColor.rgb * specular * lightMapCol.b;
					if (isInShadow)
					{
						inputMetalSpecularColor *= _MTSpecularAttenInShadow;
					}

					// diffColor = isShadowRampPart ? inputMetalLightPartColor * inputMetalShadowMultiColor : inputMetalLightPartColor * _ES_CharacterMainLightBrightness;
					// specColor = inputMetalSpecularColor * _ES_CharacterMainLightBrightness;

					diffColor = isShadowRampPart ? inputMetalLightPartColor * inputMetalShadowMultiColor : inputMetalLightPartColor * _ES_CharacterMainLightBrightness ;
					specColor = inputMetalSpecularColor * _ES_CharacterMainLightBrightness;
				}
				else
				//----------- 不是金属的情况 --------------
				{
					//采样Ramp图
					half3 warmColor = SAMPLE_TEXTURE2D(_RampTex,sampler_RampTex,rampUV.xy).rgb;
					half3 coolColor = SAMPLE_TEXTURE2D(_RampTex,sampler_RampTex,rampUV.xz).rgb;

					float3 rampColor = lerp(coolColor, warmColor, _ES_CharacterColorTone);
					

					//------------- 脸部情况 -------------
					#ifdef FACEMAP_ON

					half faceMapValue = SAMPLE_TEXTURE2D(_FaceMapTex,sampler_FaceMapTex, i.faceMapParams.xy).a;
					half faceMapSoftness = max(_FaceMapSoftness, 0.000001f); 

					half faceMapLum = smoothstep(clamp(i.faceMapParams.z - faceMapSoftness, 0.0001, 0.9999-0.001), min(i.faceMapParams.z + faceMapSoftness, 0.9999), faceMapValue);
 					
					if(isInShadow)
					{
						faceMapLum = 0;
					}

					isShadowRampPart = 1 > faceMapLum;

					// rampColor = lerp((half3)1, rampColor, 1-faceMapLum);
					rampColor = lerp((half3)1, _FaceShadowColor.rgb, 1-faceMapLum);


					//lightMapCol.b = 1;
					#endif

					// diffColor = isShadowRampPart ? mainTexCol.rgb * rampColor : mainTexCol.rgb * _ES_CharacterMainLightBrightness;
					diffColor = isShadowRampPart ? mainTexCol.rgb * rampColor : mainTexCol.rgb * _ES_CharacterMainLightBrightness ;

					half s = specular_factor(N, H, shininess);
					if (s > 1.0f - lightMapCol.b)
					{
						specColor = _SpecularColor * specMulti * lightMapCol.r;
					}
					else
					{
						specColor = 0;
					}
 
				}
				
 
				float3 outColor = diffColor + specColor;


				
				#if defined(_DEBUG_ON) && defined(_VIEW_MAINTEX_ON)
					return float4(mainTexCol.rgb,1);
				#endif

				#if defined(_DEBUG_ON) && defined(_CLOSE_LIGHT_ON)
					return float4(outColor.rgb,1);
				#endif

				//------------ Emission	---------------


				//------------ Apply Env Light --------

				// _ES_CharacterMainLightColor.rgb = _MainLightColor.rgb;

				// float3 ambientPartCol = outColor * _ES_CharacterAmbientBrightness;
				// float3 mainlightPartCol = saturate(_ES_CharacterMainLightColor.rgb) * (1 - _OverrideLightColor.a) + _OverrideLightColor.rgb;

				// outColor = ambientPartCol * lerp((half3)1,mainlightPartCol,_ES_CharacterMainLightRatio);
				// outColor += _ES_CharacterAmbientLightColor.rgb * _ES_CharacterAmbientLightRatio * saturate(outColor * 10);



				// _ES_CharacterMainLightColor.rgb = _MainLightColor.rgb + 0.1;
				// float mulnum = 1/min(_ES_CharacterMainLightColor.r,min(_ES_CharacterMainLightColor.g,_ES_CharacterMainLightColor.b));
				// _ES_CharacterMainLightColor.rgb *= min(mulnum,2);


				// float3 ambientPartCol = _ES_CharacterAmbientLightColor.rgb ;
				// float3 mainlightPartCol = _ES_CharacterMainLightColor.rgb * (1 - _OverrideLightColor.a) + _OverrideLightColor.rgb;
				// //mainlightPartCol *= _ES_CharacterMainLightBrightness;
				// // outColor *=   1 + ambientPartCol * _ES_CharacterAmbientLightRatio + (isShadowRampPart ? 0 : 0.5 + lerp(0.5, _ES_CharacterMainLightColor.rgb * 2 ,_ES_CharacterMainLightRatio));
				// //outColor += _ES_CharacterAmbientLightColor.rgb * _ES_CharacterAmbientLightRatio * saturate(outColor * 10);

				// //outColor *= ambientPartCol * _ES_CharacterAmbientLightRatio + (isShadowRampPart ? _ES_CharacterAmbientBrightness:0.6 + lerp( 0.4, mainlightPartCol * 0.6 ,_ES_CharacterMainLightRatio));


				// //return outColor.rgbb;

				// outColor *= isShadowRampPart ? 0.8 + ambientPartCol * _ES_CharacterAmbientBrightness : 0.2 + 0.5 * mainlightPartCol + 0.5 * ambientPartCol * _ES_CharacterAmbientBrightness;



				_ES_CharacterMainLightColor.rgb = _MainLightColor.rgb;

				float3 ambientPartCol = outColor * _ES_CharacterAmbientBrightness;
				float3 mainlightPartCol = saturate(_ES_CharacterMainLightColor.rgb) * (1 - _OverrideLightColor.a) + _OverrideLightColor.rgb;
				mainlightPartCol = lerp((half3)1,mainlightPartCol,_ES_CharacterMainLightRatio);

				outColor = ambientPartCol * mainlightPartCol * 1.1f;
				
				outColor += ambientPartCol * _ES_CharacterAmbientLightColor * _ES_CharacterAmbientLightRatio / _ES_CharacterAmbientBrightness;


				return float4(outColor,1);


			}



			ENDHLSL
		}
		
		


		Pass
		{

            Name "Outline"
            Tags{"LightMode" = "SRPDefaultUnlit"}

            Cull Front

            // Offset 1,-1

            HLSLPROGRAM

            #pragma vertex outline_vert
            #pragma fragment outline_frag


			//--------- Inlucde Filelist -----------
			//--------------------------------------
		    #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
	        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

			//------- Shader KEYWORD Define --------
			//--------------------------------------
            #pragma shader_feature_local _DEBUG_ON
            #pragma shader_feature_local _USE_DEFAULT_VCOLOR




			
			//---------- Varials Define ------------
			//--------------------------------------

            TEXTURE2D(_LightMapTex);     	SAMPLER(sampler_LightMapTex);

            CBUFFER_START(UnityPerMaterial)

            float4 _MainTex_ST;

            float4 _OutlineWidthAdjustZs;
            float4 _OutlineWidthAdjustScales;

            float _OutlineWidth;
            float _OutlineCorrectionWidth;
            float _OutlineWidthScale;
            float _MaxOutlineZOffset;

            float3 _OutlineColor;
            float3 _OutlineColor_1;
            float3 _OutlineColor_2;
            float3 _OutlineColor_3;
            float3 _OutlineColor_4;

            CBUFFER_END




			//---------- Appdata/v2f Struct --------
			//--------------------------------------

            struct outline_appdata
			{
				float4 vertex : POSITION;
				half4 color : COLOR0;
				float3 normal : NORMAL;
				float4 tangent : TANGENT;
				float2 texcoord : TEXCOORD0; 
				/*ase_vdata:p=p;n=n;t=t;c=c;uv0=tc0;*/

				//UNITY_VERTEX_INPUT_INSTANCE_ID
			};

			struct outline_v2f 
			{
				float4 position : SV_POSITION;
				half4 color : COLOR0;
				float2 texcoord : TEXCOORD0;
				// float3 normal : TEXCOORD1;
				// float4 screen : TEXCOORD2;
				/*ase_interp(3,15):sp=sp.xyzw;c=c;uv0=tc0.xy;wn=tc1.xyz*/

				//UNITY_VERTEX_INPUT_INSTANCE_ID
			};



			//------------- Functions --------------
			//--------------------------------------



            inline float lerpByZ(float startScale, float endScale, float startZ, float endZ, float z)
            {
                float t = (z - startZ) / max(endZ - startZ, 0.001);
                t = saturate(t);
                return lerp(startScale, endScale, t);
            }


			//-------------- Vert ------------------
			//--------------------------------------

			outline_v2f outline_vert(outline_appdata v)
			{
				outline_v2f o = (outline_v2f)0;

				#if defined(_DEBUG_ON) && defined(_USE_DEFAULT_VCOLOR)
					v.color.b = 1;
					v.color.a = 1;
				#endif



				//-------- 计算常规顶点数据 -----------
				o.texcoord = TRANSFORM_TEX(v.texcoord.xy, _MainTex);


				//消除误差提高精度后的o2w和w2v矩阵
                float4x4 worldMatZero = GetObjectToWorldMatrix();
                worldMatZero._14_24_34 -= GetCameraPositionWS();

                float4x4 viewMatZero = GetWorldToViewMatrix();
                viewMatZero._14_24_34 = 0;

                o.position = mul(viewMatZero,mul(worldMatZero,v.vertex));

          		float3 normal = v.tangent.xyz;
                half3 N = mul((float3x3)viewMatZero,mul((float3x3)worldMatZero,normal));
                // half3 N = mul(mul(normal,(float3x3)worldMatZero),(float3x3)viewMatZero);
                //在View Space 只需要 xy的方向
                N.z = 0.01f;
                N = normalize(N);

				//---------- 顶点偏移计算 -------------
                //外拓偏移计算
				half outOffset = 0;

                float fovScale = GetViewToHClipMatrix()._22;    //1/tan(FOV/2)
                // outwidth/(z * tan(FOV/2)) 是定值
                float z = -o.position.z * 2.414/fovScale;       //2.414 对应 fov 45

                float2 zRange,zScales;
                if (z < _OutlineWidthAdjustZs.y)
				{
					zRange = _OutlineWidthAdjustZs.xy;
					zScales = _OutlineWidthAdjustScales.xy;
				}
				else
				{
					zRange = _OutlineWidthAdjustZs.yz;
					zScales = _OutlineWidthAdjustScales.yz;
				}
				float scale = lerpByZ(zScales.x, zScales.y, zRange.x, zRange.y, z);

				float norOffset = _OutlineWidth * scale / 2.414;
				norOffset *= v.color.a;	//顶点色a通道影响法向偏移

				o.position.xyz += normalize(o.position.xyz) * _MaxOutlineZOffset  * (v.color.b-0.5f); //顶点色 b通道 指示视线方向上顶点偏移
				o.position.xy += N.xy * norOffset;
				o.position = TransformWViewToHClip(o.position.xyz);

				return o;
			}



			//-------------- frag ------------------
			//--------------------------------------
			half4 outline_frag (outline_v2f i) : SV_Target
			{
				float2 uv = i.texcoord.xy;
				half4 lightMapCol = SAMPLE_TEXTURE2D(_LightMapTex,sampler_LightMapTex,uv);


				//----------- 获取正确通道变量 --------
				float3 outlineColor = _OutlineColor;

				//----------- 获取正确通道变量 --------
				if(1)
				{	
					float cnlID = FetchMaterialId(lightMapCol.a);

				
					if (cnlID == 1)
					{
						outlineColor = _OutlineColor_1;		
					}

					if (cnlID == 2)
					{
						outlineColor = _OutlineColor_2;
					}

					if (cnlID == 3)
					{
						outlineColor = _OutlineColor_3;
					}

					if (cnlID == 4)
					{
						outlineColor = _OutlineColor_4;				
					}	
				}


				return half4(outlineColor,1);

			}

			ENDHLSL

		}
	
		Pass
		{

            Name "DepthOnly"
			Tags{"LightMode" = "DepthOnly"}

			ZWrite On
			ColorMask 0
			Cull[_Cull]

			HLSLPROGRAM

			#pragma vertex DepthOnly_vert
            #pragma fragment DepthOnly_frag

			//--------- Inlucde Filelist -----------
			//--------------------------------------
		    #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

			//------- Shader KEYWORD Define --------
			//--------------------------------------

			//---------- Varials Define ------------
			//--------------------------------------


			float4 _MainTex_ST;

			//---------- Appdata/v2f Struct --------
			//--------------------------------------
				
			struct DepthOnly_appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
				float2 uv2 :TEXCOORD1;
				/*ase_vdata:p=p;n=n;uv0=tc0.xy;c=c;t=t*/


			//#if defined(SUPPORT_INSTANCED_SKINNING)
			//	FZDL_BAKED_SKIN_INSTANCING_ATTRIBUTES
			//#endif    

			//	UNITY_VERTEX_INPUT_INSTANCE_ID
			};



			struct DepthOnly_v2f
			{
				float4 position : SV_POSITION;
				float4 texcoord : TEXCOORD0;

				//float4 isInShadow : TEXCOORD4;
				//float4 fogCoord : TEXCOORD5;

				/*ase_interp(5,7):sp=sp.xyzw;uv0=tc0.xyzw;uv1=tc1.xyzw;uv2=tc2.xyzw;c=c*/

				//UNITY_VERTEX_INPUT_INSTANCE_ID
			};


			//-------------- Vert ------------------
			//--------------------------------------

			DepthOnly_v2f DepthOnly_vert(DepthOnly_appdata v/*ase_vert_input*/)
			{
				DepthOnly_v2f o = (DepthOnly_v2f)0;
			 
				//-------- 计算常规顶点数据 -----------
				o.texcoord.xy = TRANSFORM_TEX(v.uv,_MainTex);
				o.texcoord.zw = TRANSFORM_TEX(v.uv2,_MainTex);

				o.position = TransformObjectToHClip(v.vertex.xyz);

				return o;
			}


			//-------------- Frag ------------------
			//--------------------------------------

			half4 DepthOnly_frag (DepthOnly_v2f i) : SV_Target
            {



            	return 0;           	
            }

			ENDHLSL
        }    



        Pass
		{

            Name "ShadowCaster"
			Tags{"LightMode" = "ShadowCaster"}

			ColorMask 0
			Cull Off

			HLSLPROGRAM

			#pragma vertex ShadowCaster_vert
            #pragma fragment ShadowCaster_frag

			//--------- Inlucde Filelist -----------
			//--------------------------------------
		    #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl"

			//------- Shader KEYWORD Define --------
			//--------------------------------------

			//---------- Varials Define ------------
			//--------------------------------------
			float3 _LightDirection;

			float4 _MainTex_ST;


			//---------- Appdata/v2f Struct --------
			//--------------------------------------
				
			struct ShadowCaster_appdata
			{
				float4 vertex : POSITION;
				float3 normal : NORMAL;
				float2 uv : TEXCOORD0;
				float2 uv2 :TEXCOORD1;
				/*ase_vdata:p=p;n=n;uv0=tc0.xy;c=c;t=t*/


			//#if defined(SUPPORT_INSTANCED_SKINNING)
			//	FZDL_BAKED_SKIN_INSTANCING_ATTRIBUTES
			//#endif    

			//	UNITY_VERTEX_INPUT_INSTANCE_ID
			};



			struct ShadowCaster_v2f
			{
				float4 position : SV_POSITION;
				float4 texcoord : TEXCOORD0;

				//float4 isInShadow : TEXCOORD4;
				//float4 fogCoord : TEXCOORD5;

				/*ase_interp(5,7):sp=sp.xyzw;uv0=tc0.xyzw;uv1=tc1.xyzw;uv2=tc2.xyzw;c=c*/

				//UNITY_VERTEX_INPUT_INSTANCE_ID
			};


			//-------------- Vert ------------------
			//--------------------------------------

			ShadowCaster_v2f ShadowCaster_vert(ShadowCaster_appdata v/*ase_vert_input*/)
			{
				ShadowCaster_v2f o = (ShadowCaster_v2f)0;
			 
				//-------- 计算常规顶点数据 -----------
				o.texcoord.xy = TRANSFORM_TEX(v.uv,_MainTex);
				o.texcoord.zw = TRANSFORM_TEX(v.uv2,_MainTex);

				//--------- 阴影计算 ----------------
				float3 positionWS =  TransformObjectToWorld(v.vertex.xyz);
				float3 normalWS = TransformObjectToWorldNormal(v.normal);
			    float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, _LightDirection));

			#if UNITY_REVERSED_Z
			    positionCS.z = min(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
			#else
			    positionCS.z = max(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
			#endif

			    o.position = positionCS;

				return o;
			}


			//-------------- Frag ------------------
			//--------------------------------------

			half4 ShadowCaster_frag (ShadowCaster_v2f i) : SV_Target
            {



            	return 0;           	
            }

			ENDHLSL
        }    



	}










}