#ifdef msaa
uniform sampler2DMS   tex0;   // screen
#else
uniform sampler2DRect tex0;   // screen
#endif
uniform sampler2D     tex4; // noise texture
uniform vec4        aratio; // alpha,screen_nx/screen_ny
uniform vec3        sun_colors[4];


vec3 to_srgb(vec3 L)
{
 L=clamp(L,0.0001,0.9999);
 vec3  f=step(0.0031308,L);
 vec3 L1=L*12.92;
 vec3 L2=1.055*pow( L,vec3(1./2.4))- 0.055;
 return mix(L1,L2,f);
}

float noise(float t)
{
 return texture2D(tex4,vec2(t,.0)).x;
}

float pent(in vec2 p)
{
 float q = abs(p.x);
 return max(max(q*1.176-p.y*0.385, q*0.727+p.y), -p.y*1.237)*1.;
}

// p - pixel coord. aspect*[-0.5;0.5],[-0.5;0.5]
// sunpos  - sunpos
float flare(vec2 p, vec2 sunpos)
{
 vec2 q   = p-sunpos;
 vec2 pds = p*(length(p))*0.75;
 float a = atan(q.x,q.y);
 float rz = .55*(pow(abs(fract(a*.8+.12)-0.5),3.)*(noise(a/16.)*0.9+.1)*exp2((-dot(q,q)*4.))); //Spokes
 rz += max(1.0/(1.0+32.0*pent(pds+0.8*sunpos)),.0)*0.2; //Projected ghost (main lens)
 vec2 p2 = mix(p,pds,-.5); //Reverse distort
 rz += max(0.01-pow(pent( (p2 + 0.4*sunpos)),2.2),.0)*3.0;
 rz += max(0.01-pow(pent( (p2 + 0.2*sunpos)),5.5),.0)*3.0;
 rz += max(0.01-pow(pent( (p2 - 0.1*sunpos)),1.6),.0)*4.0;
 rz += max(0.01-pow(pent(-(p2 + 1.0*sunpos)),2.5),.0)*5.0;
 rz += max(0.01-pow(pent(-(p2 - 0.5*sunpos)),2.0),.0)*4.0;
 rz += max(0.01-pow(pent(-(p2 + 0.7*sunpos)),5.0),.0)*3.0;
 return clamp(rz,0.,1.);
}

vec3 sun_color(float cs,float ipower)
{
 vec3 col = sun_colors[0]*exp2(cs*650.*ipower)*.8;
 col +=     sun_colors[1]*exp2(cs*100.*ipower)*.3;
 col +=     sun_colors[2]*exp2(cs*50. *ipower)*.5;
 col +=     sun_colors[3]*exp2(cs*10. *ipower)*.4;
 return col;
}


in vec2 p; // [-0.5;0,5]*ratio, [-0.5;0,5]
in vec2 tc;
in vec2 sunpos;
in vec3 power;
out vec4 fragColor;
void main()
{
 vec3 rd      = normalize( vec3(p.xy,1.0) );
 vec3 sun_pos = normalize( vec3(sunpos.xy,1.) );
 float rdl    = clamp(dot(rd, sun_pos),0.,1.);
 vec3 col     = sun_color(rdl-1.0,power.z);
 col         += power.x*sun_colors[0]*max(flare(p,sun_pos.xy/sun_pos.z),0.);
 col          = clamp(col*power.y, 0., 1.);
 col          = col*0.5 + 0.5*col*col*(3.0-2.0*col); //saturation
 ivec2 ti     = ivec2(tc.xy);
#ifdef msaa
 col         += (texelFetch(tex0,ti,0)+texelFetch(tex0,ti,1)+texelFetch(tex0,ti,2)+texelFetch(tex0,ti,3)).rgb*0.25;
#else
 col         += texelFetch(tex0,ti).rgb;
#endif
 col          = to_srgb(col);
 fragColor    = vec4( col, aratio.x );
}
