﻿Shader "Nextech/VideoModuleHologram"
{
	Properties
	{
		_MainTex("Texture", 2D) = "Black" {}
		_Alpha("Alpha", Range(0, 1)) = 1
		_Android("Android", Float) = 1

		[Space]
		_Threshold("Threshold", Range(0.0, 1)) = 0.006
		_Tint1("Tint1", Range(0.0, 1)) = 0.006
		_Tint2("Tint2", Range(0.0, 1)) = 0.006

		[Space]
		_UseColorMask("UseMask", Range(0, 1)) = 0
		_MaskColor("Mask Color", Color) = (1,1,1,1)

		[Space]
		_UseBlend("UseBlend", Range(0, 1)) = 0
		_BlendColor("Blend Color", Color) = (1,1,1,1)
	}

	SubShader
	{
		Tags
		{
			"Queue" = "Transparent"
			"PreviewType" = "Plane"
		}
		Pass
		{
			Blend SrcAlpha OneMinusSrcAlpha

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
			};

			float _Android;

			struct v2f
			{
				float4 vertex : SV_POSITION;
				float2 uv : TEXCOORD0;
			};

			v2f vert(appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = v.uv;

				// flip Y for iOS
				if(_Android == 0)
				{
					o.uv.y = 1-o.uv.y;
				}

				return o;
			}

			sampler2D _MainTex;
			float _Alpha;
			float _Threshold;
			float _Tint1;
			float _Tint2;

			float _UseColorMask;
			float4 _MaskColor;

			float _UseBlend;
			float4 	_BlendColor;

			const float PI = 3.14159;

			float4 frag(v2f input) : SV_Target
			{
				// Get the color infomation from the main tex.
				float4 color = tex2D(_MainTex, input.uv);
				float colorDistance = 0;

				float4 mask = tex2D(_MainTex, 0);

				if (_UseColorMask > 0.5)
				{
					mask = _MaskColor;
				}
				
				// Calculate the distance between the two color points.
				colorDistance = abs(distance(mask.rgb, color.rgb));
								

				float color1 = color.g;
				float color2 = color.r;
				float color3 = color.b;

				float diff1 = color1 - color2;
				float diff2 = color1 - color3;

				bool shouldMask = false;

				if (color1 > color2)
				{
					if (color1 > color3)
					{
						if (diff1 > _Threshold || diff2 > _Threshold)
						{
							shouldMask = true;
						}
					}

					if (abs(color1 - color3) < _Tint1)
					{
						color.g = (color.r + color.b) / 2;
					}
				}
				
				// Apply blended color
				color.rgb = lerp(color.rgb, _BlendColor, _UseBlend);
								
				// Apply Alpha based on the distance and threshold
				if (shouldMask)
				{
					color.a = 0 * _Alpha;
				}
				else
				{
					color.a = color.a * _Alpha;
				}

				// Apply fix for washed out android
				if(_Android == 1)
				{
					color = pow(color, 2.2);
				}


				
				return color;
			}
			ENDCG
		}
	}
}
