#include "/lib/all_the_libs.glsl"
#include "/global/post/bloom.glsl"

varying vec2 texcoord;
varying vec2 PrevTilePos;



/* DRAWBUFFERS:1 */
vec3 getStarburst(sampler2D tex, vec2 uv, vec2 direction, float spreadDistance, vec2 texelSize) {
    vec3 resultColor = vec3(0.0);
    float totalWeight = 0.0;
    
    // 1. Doubled the samples to fix the blocky, jagged edges
    const int SAMPLES = 30; 
    
    for (int i = -SAMPLES; i <= SAMPLES; i++) {
        // 2. Exponential Falloff: This makes the streak fade into a sharp needle point
        // Tweak the 0.15: Higher = shorter/sharper fade. Lower = longer/thicker fade.
        float weight = exp(-abs(float(i)) * 0.005); 
        
        vec2 offset = direction * (float(i) / float(SAMPLES)) * spreadDistance * texelSize;
        vec3 sampleColor = texture2D(tex, uv + offset).rgb;
        
        // 3. Crush the core to make the source feel smaller
        vec3 sharpColor = pow(max(sampleColor, vec3(0.0)), vec3(3.0)); 
        
        // 4. CLAMP IT: This stops the giant sun from mathematically exploding
        // It caps the maximum brightness of the streak, keeping it contained.
        sharpColor = min(sharpColor, vec3(2.0));
        
        resultColor += sharpColor * weight;
        totalWeight += weight;
    }
    
    return resultColor / max(totalWeight, 0.0001);
}
void main() {
    vec3 softBloom = blur3x3(colortex1, PrevTilePos).xyz;
    vec2 texelSize = 1.0 / vec2(viewWidth, viewHeight);
    vec3 finalStarburst= vec3(0.0);
    #ifdef STAR_BURST_EFFECT

    
    
    vec2 dir1 = normalize(vec2(1.0, 1.0));
    vec3 streak1 = getStarburst(colortex1, PrevTilePos, dir1, STAR_BURST_SPREAD, texelSize);
    
    vec2 dir2 = normalize(vec2(1.0, -1.0));
    vec3 streak2 = getStarburst(colortex1, PrevTilePos, dir2, STAR_BURST_SPREAD, texelSize);
    
    finalStarburst = streak1 + streak2;
    #endif

    gl_FragData[0].xyz = softBloom + (finalStarburst * (nightStrength + 0.1) * STAR_BURST_STRENGHT);
}