// vert //

void main(void) {
	gl_Position = qgl_ftransform();
}


// frag //

uniform sampler2D fb_hover, fb_selection;
uniform vec4 hover_id, hover_color, selection_color;
uniform float hover_fill, selection_fill, has_hover, has_selection;
ivec2 tc;

vec4 diffVector(in sampler2D map, in vec4 id) {
	vec4 ds0 = abs(texelFetchOffset(map, tc, 0, ivec2(-1, 0)) - id);
	vec4 ds1 = abs(texelFetchOffset(map, tc, 0, ivec2( 1, 0)) - id);
	vec4 ds2 = abs(texelFetchOffset(map, tc, 0, ivec2(0, -1)) - id);
	vec4 ds3 = abs(texelFetchOffset(map, tc, 0, ivec2(0,  1)) - id);
	return vec4(dot(ds0, vec4(1)), dot(ds1, vec4(1)), dot(ds2, vec4(1)), dot(ds3, vec4(1)));
}
vec2 diffPair(in vec4 dv) {
	const float _c = 64;
	return vec2(step(1e-6, dot(dv, vec4(1))),
				step(1e-3, (dv.r * _c) * (dv.g * _c) * (dv.b * _c) * (dv.a * _c)));
}
float diffAlpha(in vec2 dp, in float fill) {
	return mix(dp.x - dp.y, dp.x - dp.y - dp.y + 1, fill);
}

void main(void) {
	tc = ivec2(gl_FragCoord.xy);
	float hh = clamp(dot(hover_id, vec4(1)), 0, 1);
	
	vec2 dp = diffPair(diffVector(fb_hover, hover_id));
	float v = diffAlpha(dp, hover_fill);
	qgl_FragData[0] = has_hover*hh*v*vec4(hover_color.rgb, hover_color.a);
	
	dp = diffPair(diffVector(fb_selection, vec4(1)));
	v = diffAlpha(dp, selection_fill);
	qgl_FragData[1] = has_selection*v*vec4(selection_color.rgb, selection_color.a);
}
