#define _RangeCorrection	1.8
varying vec4 vert1, vert2, vert3, vert4;
varying vec4 tc12, tc34;

uniform float GridSizeX, GridSizeY;
uniform float Base, StepSize;
uniform vec3 n00, n01, n11, n10, f00, f01, f11, f10;

vec4 MixVert(in vec4 v)
{		
	vec3 n = mix(mix(n00, n01, v.y), mix(n10, n11, v.y), v.x);
	vec3 f = mix(mix(f00, f01, v.y), mix(f10, f11, v.y), v.x);	
	vec3 dir = n.xyz - f.xyz;
	vec4 ret; 
	ret.xyz = ((-(n.z - Base)/dir.z) * dir) + n.xyz;
	ret.w = 1.0;
	return ret;
}

void main()
{
	vert1 = gl_Vertex;
	vert1.x -= GridSizeX;
	vert1.x = max(vert1.x, 0.0);
	vert1 = MixVert(vert1);

	vert2 = gl_Vertex;
	vert2.x += GridSizeX;
	vert2.x = min(vert2.x, 1.0);
	vert2 = MixVert(vert2);

	vert3 = gl_Vertex;
	vert3.y -= GridSizeY;
	vert3.y = max(vert3.y, 0.0);
	vert3 = MixVert(vert3);

	vert4 = gl_Vertex;
	vert4.y += GridSizeY;
	vert4.y = min(vert4.y, 1.0);
	vert4 = MixVert(vert4);

	vec4 texc1 = (gl_ModelViewProjectionMatrix * vert1);
	vec4 p1 = texc1;
	texc1.w *= _RangeCorrection;
	vec4 texc2 = (gl_ModelViewProjectionMatrix * vert2);
	vec4 p2 = texc2;
	texc2.w *= _RangeCorrection;
	vec4 texc34 = (gl_ModelViewProjectionMatrix * vert3);
	texc34.w *= _RangeCorrection;
	tc12.xy = ((texc1.xy / texc1.w) + 1.0) * 0.5;
	tc12.zw = ((texc2.xy / texc2.w) + 1.0) * 0.5;
	tc34.xy = ((texc34.xy / texc34.w) + 1.0) * 0.5;
	texc34 = (gl_ModelViewProjectionMatrix * vert4);
	texc34.w *= _RangeCorrection;
	tc34.zw = ((texc34.xy / texc34.w) + 1.0) * 0.5;
	
#ifndef _LINEAR_FILTER_ENABLED	
	float tmp;

	float KURVY = abs(tc12.x - tc12.z);
	float KURVY2 = abs(tc34.y - tc34.w);
	float PICE = StepSize * 2.0;
	if (KURVY < PICE)
 	{
		tmp = mix(tc12.x, tc12.z, 0.5);
		tc12.x = tmp - StepSize;
		tc12.z = tmp + StepSize;
		vec4 d = ((vert2 - vert1) / (KURVY/PICE)) * 0.5;
		vec4 t = mix(vert1, vert2, 0.5);
		vert1 = t - d;
		vert2 = t + d;
	};
	
	if (KURVY2 < PICE)
 	{
		tmp = mix(tc34.y, tc34.w, 0.5);
		tc34.y = tmp + StepSize;
		tc34.w = tmp - StepSize;
		
		vec4 d = ((vert4 - vert3) / (KURVY2/PICE)) * 0.5;
		vec4 t = mix(vert3, vert4, 0.5);
		vert3 = t - d;
		vert4 = t + d;
	};
#endif

	gl_Position = mix(p1, p2, 0.5);
	gl_Position.w *= _RangeCorrection;
}
