varying vec2 		texcoord;
uniform sampler2D 	lightTex;
uniform sampler2D 	lensRamp;
uniform vec3 		lensColor;
/*vec4 				color=vec4(0,0,0,0),
					color1=vec4(0,0,0,0),
					color2=vec4(0,0,0,0),
					color3=vec4(0,0,0,0),
					color4=vec4(0,0,0,0),
					color5=vec4(0,0,0,0),
					color6=vec4(0,0,0,0),
					color7=vec4(0,0,0,0);*/
					
uniform int NSAMPLES;//=12;
uniform float FLARE_DISPERSAL;//=0.2;
uniform float FLARE_HALO_WIDTH;//=0.45;
uniform vec3 FLARE_CHROMA_DISTORTION;//=vec3(0.1,0.05,0.15);


vec3 textureDistorted(in sampler2D tex, in vec2 sample_center, in vec2 sample_vector, in vec3 distortion) 
{
	return vec3(
		texture2D(tex, sample_center + sample_vector * distortion.r).r,
		texture2D(tex, sample_center + sample_vector * distortion.g).g,
		texture2D(tex, sample_center + sample_vector * distortion.b).b
	);
}

void main()
{
	vec2 image_center = vec2(0.5);
	vec2 sample_vector = (image_center - texcoord) * FLARE_DISPERSAL;
	vec2 halo_vector = normalize(sample_vector) * FLARE_HALO_WIDTH;
	vec2 offset;
	float offsetLen=1.0/length(vec2(0.5));

	float weight = length(vec2(0.5) - fract(texcoord + halo_vector)) * offsetLen;
	weight = pow(1.0 - weight, 5.0);
	vec3 result = textureDistorted(lightTex, texcoord + halo_vector, halo_vector, FLARE_CHROMA_DISTORTION).rgb*vec3(weight);//*vec2(weight);
		
	for (int i = 0; i < NSAMPLES; ++i) 
	{
		offset =  fract(texcoord + sample_vector * float(i));
		
		weight = length(vec2(0.5) - offset) * offsetLen;
		weight = /*pow(*/1.0 - weight/*, 2.0)*/;
	  
		result += texture2D(lightTex, offset).rgb * vec3(weight);
		result = min(result,vec3(1.0));
	}
	
	//vec3 ramp=pow(texture2D(lensRamp, vec2(length(vec2(0.5) - texcoord) / length(vec2(0.5))) ).rgb,vec3(2.2));
	result = (result-vec3(0.1,0.1,0.1))*1.5;
	//result *= ramp;
	
	// BRIGHTNESS & CONTRAST
	gl_FragColor.xyz = result*lensColor.xyz;
}
