
uniform sampler2D cvTexture;
uniform sampler2D cvTexture2;
uniform sampler2D cvTexture3;
uniform sampler2D cvTexture_RESULT;
uniform sampler2D cvTexture_RESULT_2;
uniform sampler2D cvTexture_First;
uniform sampler2D cvOrigin;
uniform sampler1D colorTable;
uniform int SHADER_STATE;
uniform float noise;
uniform float gen;

#define mask 3
int m_value = ( (mask - 1) / 2 );
float mask_f = 3.0;

vec4 origin;
vec4 color;
vec4 color2;
vec4 color3;
vec2 IMG_SIZE = vec2( 320,  335 );

//取三張足壓的最大值, 再用原始影像相減後回傳
float GetGreyValueWithoutGrey( float pos_x, float pos_y, float origin_g/*, float grey_g*/ )
{
	float pixel;

	float C;
	float F;

	color = texture2D( cvTexture, vec2( pos_x, pos_y ) );
	color3 = texture2D( cvTexture3, vec2( pos_x, pos_y ) );
	color2 = texture2D( cvTexture2, vec2( pos_x, pos_y ) );

	
	pixel = color.g;
	if( pixel > color2.g )
		pixel = color2.g;
	if( pixel > color3.g )
		pixel = color3.g;


	F = ( origin_g - pixel );

	pixel = F;

	return pixel;
}

float RemoveNoise( float value )
{
	value = value - ( noise / 255.0 );
	return value;
}

void main()
{	
	vec2 pos = gl_TexCoord[0].st;

	float x = pos.s;
	float y = pos.t;
	vec4 color_result;

	origin = texture2D( cvOrigin, vec2( x, y ) );

	if( SHADER_STATE == 0 )	//FINAL
	{
		color_result = texture2D( cvTexture_RESULT_2, vec2( x, y ) );
		//color_result.g = RemoveNoise ( color_result.g );
		color_result.g = color_result.g * gen;
		color = texture1D( colorTable, color_result.g );

		//改成灰階輸出
		//color.r = color.g = color.b = color_result.g;

	}
	else if( SHADER_STATE == 2 || SHADER_STATE == 4 )	//cvTexture_RESULT_2		p.s. SHADER_STATE == 4 為擷取原始灰階影像用
	{
		color_result = texture2D( cvTexture_RESULT, vec2( x, y ) );

		if( true )
		{
			float sum = 0.0;
			float tmp_x;
			float tmp_y;
			float result;

			for( float i=-m_value; i<=m_value; i++ )
			{
				for( float j=-m_value; j<=m_value; j++ )
				{
					//tmp_x = x + i/588.0;
					//tmp_y = y + j/504.0;
					tmp_x = x + i / IMG_SIZE.x;
					tmp_y = y + j / IMG_SIZE.y;

					if( tmp_x < 0.0 || tmp_x > 1.0 || tmp_y < 0.0 || tmp_y > 1.0 )
						continue;
							
					sum +=  texture2D( cvTexture_RESULT, vec2( tmp_x, tmp_y ) ).g ;
				}
			}
			color_result.g = sum / (pow( mask_f, 2.0 ));
	
		}

		//if( SHADER_STATE == 2 )
			//color_result.g = RemoveNoise ( color_result.g );

		color.r = color.b = color.g = color_result.g;
	}
	else if( SHADER_STATE == 1 )	//cvTexture_RESULT
	{		
		color.g = GetGreyValueWithoutGrey( x, y, origin.g );

		color.g = RemoveNoise ( color.g );
		color.r = color.b = color.g;

    }

	else if( SHADER_STATE == 3 )	//640*480的原始影像材質
	{
		if( x > 1.0 || x < 0.0 || y > 1.0 || y < 0.0 )
			color.r = color.g = color.b = 1.0;
		else
			color = texture2D( cvTexture_First, vec2( x, y ) );
	}
	

	gl_FragColor = color;
}
