//$c3 AWK 06/28/11 added height chacking during smart blurring
//$c2 AWK 06/07/11 change how we blur the ssao shadow
//$c1 AWK 05/12/11 created

// this line is needed to get the associated xml files
#define SW_PARAMETER_FILES "global.xml, ssaoblur.xml"
#define SW_INCLUDE "utils.glsl"

const int MAX_SAMPLES = 21;
uniform vec2 ssaoBlurSampleOffsets[21];
uniform float ssaoBlurSampleWeight[21];



// screen position
varying vec2 v_texcoord;


#ifdef _VERTEX_PROGRAM
void main()
{
	gl_Position=vec4(gl_Vertex.xy,0.5,1.0);
	v_texcoord=gl_MultiTexCoord0.xy;
}
#endif //_VERTEX_PROGRAM




#ifdef _FRAGMENT_PROGRAM
void main()
{
	vec4 vSample = vec4(0.0,0.0,0.0,0.0);

	float weights[42];
	float colors[42];
	float weightsSum = 0.0;
	vec2 uv = v_texcoord + ssaoBlurTextureScale*ssaoBlurSampleOffsets[0];
	vec4 vnorm = texture2D(ssaoBlurNormal, uv);
	if(vnorm.a > 0.0)
	{
		weights[0] = ssaoBlurSampleWeight[0];
		weightsSum += weights[0];
		vec3 norm =  normalize((vnorm.xyz*2.0) - vec3(1.0));
		vec4 pos;
		if(ssaoBlurHeightCheck > 0.0)
			pos = texture2D(ssaoBlurPosition, uv);
		colors[0] = texture2D(ssaoBlurResult, uv).r;
//		pos.z += 0.01;
		vec2 scale = ssaoBlurTextureScale;
		int woffset = 0;
		for(int j=0; j<2; ++j)
		{
			bool stopSampling = false;
			for (int i = 1; i < ssaoBlurSamples; ++i)
			{
				weights[i+woffset] = 0.0;
				colors[i+woffset] = 0.0;
				if(!stopSampling)
				{
					vec2 suv = v_texcoord + scale*ssaoBlurSampleOffsets[i];
					vec4 sn = texture2D(ssaoBlurNormal, suv);
					colors[i+woffset] = texture2D(ssaoBlurResult, suv).r;
					if(sn.a > 0.0)
					{
						if(ssaoBlurHeightCheck > 0.0)
						{
							vec4 sPos = texture2D(ssaoBlurPosition, suv);
							float ht = abs(dot(norm, (sPos-pos).xyz));
							if(ht < ssaoBlurHeightCheck)
							{
								vec3 tNormal =  normalize((sn.xyz*2.0) - vec3(1.0));
								weights[i+woffset] = dot(norm,tNormal)*ssaoBlurSampleWeight[i];
								weightsSum += weights[i+woffset];
							}
							else
							stopSampling = true;
						}
						else
						{
							vec3 tNormal =  normalize((sn.xyz*2.0) - vec3(1.0));
							weights[i+woffset] = dot(norm,tNormal)*ssaoBlurSampleWeight[i];
							weightsSum += weights[i+woffset];
						}
					}
					else
						stopSampling = true;
				}
			}
			scale = -ssaoBlurTextureScale;
			woffset = ssaoBlurSamples-1;
		}
		int samples = ssaoBlurSamples*2-1;
		for(int i=0; i<samples; i++)
		{
			vSample += (weights[i]/weightsSum)*colors[i];
		}
	}
//	gl_FragColor = vec4(weightsSum, weightsSum, weightsSum, 1.0);//vSample;
	gl_FragColor = vSample;
}
#endif //_FRAGMENT_PROGRAM
