
uniform float time;


float gett(vec3 dir, float A, float B, float C, float D, float E, float F, float G, float H, float I, float J) {
	float a = dir.x*(A*dir.x + 2.0*B*dir.y + 2.0*C*dir.z) + dir.y*(E*dir.y + 2.0*F*dir.z) + dir.z*(H*dir.z);
	float b = D*dir.x + G*dir.y + I*dir.z;
	float c = J;
	float d = b*b-a*c;

	d = b*b-a*c;
//	if (d<0) return -1;
	d = sqrt(abs(d));
	if (a<0) { d = -d; b = -b; }
	if (-d-b>0) return (-d-b)/a;
	return (d-b)/a;

/*
	b /= -a;
	float ds = d<0.0 ? 0.0 : sqrt(d)/abs(a);
	return d<0.0 ? -1.0 : b>ds ? b-ds : b+ds;*/
}

vec3 getnorm(vec3 pos, float A, float B, float C, float D, float E, float F, float G, float H, float I, float J) {
	return normalize(vec3(dot(pos, vec3(A, B, C))+D, dot(pos, vec3(B, E, F))+G, dot(pos, vec3(C, F, H))+I));
}

// dir is interpolated (screen coords times modelview or somesuch), A..J are constants representing the quadric
vec3 shadepixels(vec3 dir, float A, float B, float C, float D, float E, float F, float G, float H, float I, float J) {
	float t = gett(dir, A, B, C, D, E, F, G, H, I, J);
	vec3 pos = dir*t;
	vec3 n = getnorm(pos, A, B, C, D, E, F, G, H, I, J);

	return t>0.0 ? dot(-n, normalize(dir)) : vec3(0.0);
//	return t>0.0 ? vec3(1.0) : vec3(0.0);
}


void main() {
	vec3 eye = normalize(vec3(-1.0+2.0*gl_TexCoord[0].xy, 0.0725/*+time*0.1*/));

//	gl_FragColor = vec4(0.5+0.5*sin(t), 0.0, 0.0, 1.0);
//	gl_FragColor = vec4(eye, 1.0);

	float xp = sin(time*4.0)*50.0;
	float yp = cos(time*4.0)*50.0;
	float zp = 10.0;

	float r = 1.0;

/*	float A = 1.0;
	float B = 0.0;
	float C = 0.0;
	float D = -xp;
	float E = 1.0;
	float F = 0.0;
	float G = -yp;
	float H = 1.0;
	float I = -zp;
	float J = -r*r;*/

	time += 0.5*(sin(gl_TexCoord[0].x*2.548904+time+sin((gl_TexCoord[0].x+gl_TexCoord[0].y)*2.4589497+time*1.24))+cos(gl_TexCoord[0].y*1.45897+time*0.85));

	vec3 col0, col1, col2;
	for (int i = 0; i < 3; i++) {
		float a=0.0, b=0.0, c=10.0;
		float d,e,f;
		if (i == 0) d=sin(time+0.0), e=sin(time*2.0)+1.0, f=cos(time+0.0);
		else if (i == 1) d=sin(time+0.0), e=1.0, f=cos(time+0.0);
		else if (i == 2) d=0.5, e=sin(time), f=(time+0.0);

		float A = 1-d*d                         ;
		float E = 1-e*e                         ;
		float H = 1-f*f                         ;
		float B = -d*e                          ;
		float C = -d*f                          ;
		float F = -e*f                          ;
		float D  =  d*(d*a+e*b+f*c)-a           ;
		float G  =  e*(e*b+f*c+d*a)-b           ;
		float I  =  f*(f*c+d*a+e*b)-c           ;
		float J = -(a*d+b*e+c*f)*(a*d+b*e+c*f)  ;

		if (i == 0) col0 = shadepixels(eye, A, B, C, D, E, F, G, H, I, J);
		if (i == 1) col1 = shadepixels(eye, A, B, C, D, E, F, G, H, I, J);
		if (i == 2) col2 = shadepixels(eye, A, B, C, D, E, F, G, H, I, J);
	}

	vec3 col = max(min(max(col0,col1), col2), min(col0,col1));

	gl_FragColor = vec4(abs(col), 1.0);
}
