#ifndef INCLUDE_ENDER_STARS
#define INCLUDE_ENDER_STARS

/*
Ender stars ported from Fantasy Shaders, adapted to BSL.
Injected in gbuffers_skytextured.glsl (the End sky pass) and tinted by endCol
(from dimensionColor.glsl). Requires gbufferModelViewInverse.

Only actual star points light up (the threshold zeroes everything else), so
there is no full-sky glow. Base brightness is tuned for BSL's endCol and the
final tonemap; fine-tune in-game with END_STAR_I.
*/

float GetEnderStarNoise(vec2 pos) {
    return fract(sin(dot(pos, vec2(12.9898, 4.1414))) * 43758.54953);
}

vec3 GetEnderStars(vec3 viewPos, float VdotU) {
    vec3 wpos = normalize((gbufferModelViewInverse * vec4(viewPos * 1000.0, 1.0)).xyz);

    vec3 starCoord  = 0.55 * wpos / (abs(wpos.y) + length(wpos.xz));
    vec2 starCoord2 = starCoord.xz * 0.6;
    if (VdotU < 0.0) starCoord2 += 120.0;
    float starFactor = 1536.0;
    starCoord2 = floor(starCoord2 * starFactor) / starFactor;

    float star = 1.0;
    star *= GetEnderStarNoise(starCoord2.xy);
    star *= GetEnderStarNoise(starCoord2.xy + 0.1);
    star *= GetEnderStarNoise(starCoord2.xy + 0.23);
    star = max(star - 0.6, 0.0);
    star *= star;

    vec3 enderStars = star * endCol.rgb * 80.0;

    float VdotUM1 = abs(VdotU);
    float VdotUM2 = (1.0 - VdotUM1) * (1.0 - VdotUM1);
    enderStars *= VdotUM1 * VdotUM1 * (VdotUM2 + 0.015) + 0.015;

    return enderStars;
}

#endif //INCLUDE_ENDER_STARS
