
// completely unoptimized and has some bugs

struct fragment {
	float4 position  : POSITION;
//	float4 color0    : COLOR0;
	float2 texcoord0 : TEXCOORD0;
//	float4 envcoord  : TEXCOORD1;
//	float4 normal    : COLOR1;
};

struct pixel {
	float4 color0 : COLOR0;
};


float3 RGBtoHSV(float3 rgb) {
	float h,s,v;
	float mini,maxi,delta;

	mini = min(rgb.r, min(rgb.g, rgb.b));
	maxi = max(rgb.r, max(rgb.g, rgb.b));
	v = maxi;

	delta = maxi-mini;//+0.01;

	if (maxi != 0) {
		s = delta/maxi;

		if (rgb.r == maxi)
			h = (rgb.g-rgb.b)/delta;
		else if (rgb.g == maxi)
			h = 2+(rgb.b-rgb.r)/delta;
		else
			h = 4+(rgb.r-rgb.g)/delta;

		h *= 60;
		if (h < 0) {
			h += 360;
		}
	} else {
/*		v = 1.0;
		s = 0.0;
		h = 0.0;*/
		s = 0;
		h = -1;
	}

	return float3(h, s, v);
}

float4 HSVtoRGB(float3 hsv) {
	int i;
	float f, p, q, t, r, g, b;
	float a = 0;
	r = 1.0; g = 1.0; b = 1.0;
	if (hsv.g != 0) {
		a = 1.0;
		hsv.r /= 60;
		i = floor(hsv.r);
		f = hsv.r-i;
		p = hsv.b*(1-hsv.g);
		q = hsv.b*(1-hsv.g*f);
		t = hsv.b*(1-hsv.g*(1-f));

		if (i == 0) {
			r = hsv.b; g = t; b = p;
		} else if (i == 1) {
			r = q; g = hsv.b; b = p;
		} else if (i == 2) {
			r = p; g = hsv.b; b = t;
		} else if (i == 3) {
			r = p; g = q; b = hsv.b;
		} else if (i == 4) {
			r = t; g = p; b = hsv.b;
		} else {
			r = hsv.b; g = p; b = q;
		}
/*	} else {
		r = 0;
		g = 0;
		b = 0;*/
	}

	return float4(r, g, b, a);
}


pixel main(fragment IN, uniform sampler2D texture, uniform float hue, uniform float useDepth) {
	pixel OUT;

	float4 col = tex2D(texture, IN.texcoord0);
	float3 hsv;

	hsv = RGBtoHSV(col.rgb);

	hsv.r += hue*360.0;

/*	if (useDepth == 1) {
	}*/

	if (hsv.r >= 360.0) hsv.r -= 360.0;
	if (hsv.r < 0) hsv.r += 360.0;

	col.rgba = HSVtoRGB(hsv);

	OUT.color0 = col;

	return OUT;
}
