<jittershader name="chromakey">
	<description>
	Chromatic distance based keying using hsv
	</description>
	<param name="tol" type="float" default="0.3">
		<description>Tolerance</description>
	</param>
	<param name="fade" type="float" default="0.">
		<description>Fade amount</description>
	</param>	
	<param name="color" type="vec4" default="0.0 0.0 0.0 0.0">
		<description>Color target (RGB)</description>
	</param>

	<param name="tex0" type="int" default="0" />
	<param name="tex1" type="int" default="1" />	
	<language name="glsl" version="1.0">
		<bind param="color" program="fp" />
		<bind param="tol" program="fp" />
		<bind param="fade" program="fp" />
		<bind param="tex0" program="fp" />
		<bind param="tex1" program="fp" />	
		<program name="vp" type="vertex" source="sh.passthru.xform.vp.glsl" />
		<program name="fp" type="fragment">
<![CDATA[

// texcoords
varying vec2 texcoord0;
varying vec2 texcoord1;

// samplers
uniform sampler2DRect tex0;
uniform sampler2DRect tex1;

// blend amount
uniform vec4 color;
uniform float tol;
uniform float fade;

vec3 rgb2hsv(vec3 rgb)
{
	float Cmax = max(rgb.r, max(rgb.g, rgb.b));
	float Cmin = min(rgb.r, min(rgb.g, rgb.b));
	float delta = Cmax - Cmin;
    
	vec3 hsv = vec3(0., 0., Cmax);

	if (Cmax > Cmin) {
		hsv.y = delta / Cmax;
		if (rgb.r == Cmax) {
			hsv.x = (rgb.g - rgb.b) / delta;
		}
		else {
			if (rgb.g == Cmax) {
				hsv.x = 2. + (rgb.b - rgb.r) / delta;
			}
			else {
				hsv.x = 4. + (rgb.r - rgb.g) / delta;
			}
		}
		hsv.x = fract(hsv.x / 6.);
	}
    return hsv;
}

void main()
{   
	vec4 a = texture2DRect(tex0, texcoord0);
	vec4 b = texture2DRect(tex1, texcoord1);
    float len = length(vec3(4., 1., 2.) * (rgb2hsv(color.rgb) - rgb2hsv(a.rgb)));
	float scale = smoothstep(abs(tol),abs(tol)+abs(fade),len);
	gl_FragColor = mix(b, a, scale);
}

]]>
		</program>
	</language>
</jittershader>
