/* Shader for conversion of RGB textures into Grayscale textures.
 * Uses standard formula for conversion:
 * (w)2006 by Mario Kleiner. Licensed under MIT license.
*/

#extension GL_ARB_texture_rectangle : enable

const mat3 rgb2ycbcrMatrix = mat3(0.299, -0.168736, 0.5, 0.587, -0.331264, -0.418688, 0.114, 0.5, -0.081312);
const vec3 rgb2y = vec3(0.299, 0.587, 0.114);
const vec3 rgb2cb = vec3(-0.168736, -0.331264, 0.5);
const vec3 rgb2cr = vec3(0.5, -0.418688, -0.081312);
uniform sampler2DRect Image;
uniform vec4 Roi;
uniform vec4 ColorRoi;
uniform float GrayThreshold;

void main()
{
    float accept = 0.0;
    vec3 ycbcr;    
    vec4 incolor = texture2DRect(Image, gl_TexCoord[0].st);
    ycbcr.r = dot(rgb2y, incolor.rgb);
    ycbcr.g = dot(rgb2cb, incolor.rgb);
    ycbcr.b = dot(rgb2cr, incolor.rgb);
    ycbcr+= vec3(0.0, 0.5, 0.5);
    accept = step(0.00, ycbcr.r) * step(ycbcr.r, GrayThreshold); 
    accept = accept * step(ColorRoi.x, ycbcr.g) * step(ycbcr.g, ColorRoi.y); 
    accept = accept * step(ColorRoi.z, ycbcr.b) * step(ycbcr.b, ColorRoi.w); 

    gl_FragColor.a = accept;
    gl_FragColor.rgb = incolor.rgb * (0.5 + accept);
}
