
#include "/lib/ssr/ssr_common.glsl"

vec3 RT_SIMPLE(vec3 dir, vec3 position, float roughness, float dither, float quality)
{
    vec3 rtPos = vec3(1.1);

    vec3 farthestClipPos = toClipSpace3DH(position + dir * 512);

    if (all(greaterThan(farthestClipPos.xy, vec2(0.0))) && all(lessThan(farthestClipPos.xy, vec2(1.0))))
    {
        float sampledDepth = texture(dhDepthTex0, farthestClipPos.xy).r;
        float currentDepth = (farthestClipPos.z * dhRenderDistance);

        if (sampledDepth < 1.0 && currentDepth <= (sampledDepth * dhRenderDistance) + 0.1)
        {
            rtPos = farthestClipPos;
        }
    }
    // return rtPos;

    vec3 clipPosition = toClipSpace3DH(position);
    vec3 direction = normalize(toClipSpace3DH(position + dir) - clipPosition);
    vec3 maxLengths = (step(0.0, direction) - clipPosition) / direction;

    float mult = min(maxLengths.x, min(maxLengths.y, maxLengths.z));

    vec3 stepv = direction * mult / quality;
    vec3 spos = clipPosition + stepv * dither;

    for (int i = 0; i <= quality; ++i)
    {

        float depthSample = texelFetch2D(dhDepthTex0, ivec2(spos.xy / texelSize), 0).r;

        if (depthSample < spos.z)
        {
            float dist = abs(depthSample - spos.z) / spos.z;
            if (dist <= 0.03)

                rtPos = vec3(spos.xy, depthSample);
            break;
        }
        spos += stepv;
    }

    return rtPos;
}

vec3 RT5LQ(vec3 dir, vec3 position, float dither, float steps)
{

    float quality = steps;
#ifdef DH

    vec3 clipPosition = toClipSpace3DH(position);
    vec3 direction = normalize(toClipSpace3DH(position + dir) - clipPosition);
#else
    vec3 clipPosition = toClipSpace3(position);
    vec3 direction = normalize(toClipSpace3(position + dir) - clipPosition);

#endif
    vec3 maxLengths = (step(0.0, direction) - clipPosition) / direction;
    float minLength = min(min(maxLengths.x, maxLengths.y), maxLengths.z);

    vec3 stepv = (direction * minLength) / quality;

    float tolerance = max(abs(stepv.z) * 4.0, 0.75 / (position.z * position.z));

    for (int i = 0; i <= int(quality); ++i)
    {

        vec3 spos = clipPosition + stepv * (i + dither);

#ifdef DH
        float depthSample = texelFetch2D(dhDepthTex1, ivec2(spos.xy / texelSize), 0).r;
#else
        float depthSample = texelFetch2D(depthtex1, ivec2(spos.xy / texelSize), 0).r;
#endif

        if (depthSample < spos.z && abs(spos.z - depthSample) < tolerance)
        {
            return vec3(spos.xy, depthSample);
        }
    }

    return vec3(1.1); // Indicates no intersection found
}
vec3 RT5XLQ(vec3 dir, vec3 position, float dither, float steps)
{
#ifdef DH
    vec3 clipPosition = toClipSpace3DH(position);
    vec3 direction = normalize(toClipSpace3DH(position + dir) - clipPosition);
#else
    vec3 clipPosition = toClipSpace3(position);
    vec3 direction = normalize(toClipSpace3(position + dir) - clipPosition);
#endif

    // Calculate step size in clip space
    vec3 maxLengths = (step(0.0, direction) - clipPosition) / direction;
    float minLength = min(min(maxLengths.x, maxLengths.y), maxLengths.z);
    vec3 stepv = direction * (minLength / steps);

    float tolerance = abs(stepv.z) * 4.0;

    // Precompute texel size scaling
    vec2 texCoordScale = 1.0 / texelSize;

    float scaledDither0 = mix(0.1, 1.0, dither);
    float scaledDither1 = mix(0.9, 1.0, dither);
    float scaledDither = mix(scaledDither1, scaledDither0, float(steps >= 4));
    for (int i = 0; i < steps; ++i)
    {
        vec3 samplePosition = clipPosition + stepv * (float(i) + scaledDither);

        // Use integer coordinates for sampling directly
        ivec2 texCoords = ivec2(samplePosition.xy * texCoordScale);
#ifdef DH
        float depthSample = texelFetch2D(dhDepthTex1, texCoords, 0).r;

#else
        float depthSample = texelFetch2D(depthtex1, texCoords, 0).r;
#endif
        if (depthSample < samplePosition.z && abs(samplePosition.z - depthSample) < tolerance)
        {
            return vec3(samplePosition.xy, depthSample);
        }
    }

    return vec3(1.1); // No valid depth found
}

// GGX distribution function G1
float g(float NdotL, float roughness)
{
    float k = (roughness * roughness) / 2.0;
    return NdotL / (NdotL * (1.0 - k) + k);
}
float g2(float NdotL)
{
    return NdotL / (NdotL * 0.9999 + 0.0001);
}

vec2 R2_samples(int n)
{
    vec2 alpha = vec2(0.75487765, 0.56984026);
    return fract(alpha * n);
}

#include "/lib/specular.glsl"
vec3 rotateAroundXAxis(vec3 v)
{

    float c = 0.999962; // cos(0.5 degrees)
    float s = 0.0087;   // sin(0.5 degrees)

    return vec3(
        v.x,
        c * v.y - s * v.z,
        s * v.y + c * v.z);
}
vec4 calculateSpecularLightingHQ(
    vec3 normal,
    vec3 np3,
    vec3 albedo,
    float shading,
    float skylight,
    float roughness,
    float porosity,
    vec3 fragpos,
    vec4 scene,
    float alpha0)
{
    bool inWater = (isEyeInWater == 1);
    vec3 reflectionColorScene = scene.rgb;
    bool waterMask = (iswater > 0.99);
    const float f0 = 0.02;

    // Determine the incident and transmitted refractive indices based on the environment
    float etaI = inWater ? 1.33 : 1.0;

    vec3 specTerm = shading * GGX2(normal, -np3, lightPos, roughness, vec3(f0));

    // Indirect specular calculation
    vec3 indirectSpecular = vec3(0.0);
    float fresnelDiffuse = 0.0;
    float noise = mix(noise_standard(gl_FragCoord.xy), 0.5, 0.0);

    vec3 L = reflect(np3, normal);

    vec3 L2 = L;

    float cosThetaI = dot(np3, normal);
    float clampedCosThetaI = clamp(1.0 + cosThetaI, 0.0, 1.0);
    float F = f0 + (1.0 - f0) * pow(clampedCosThetaI, 5.0);

    float etaISq = etaI * etaI;
    float sinThetaTSq = etaISq * (1.0 - cosThetaI * cosThetaI);
    if (sinThetaTSq > 1.0)
    {
        L2.y = -L2.y;
        F = 1.0;
    }
    // Geometry term
    float NoL = clamp(dot(normal, L), 0.0, 1.0);
    float G1 = g(NoL, roughness);

    float rayContrib = F * G1;

    vec4 sky = skyFromTex2(L2, colortex6);
    sky.rgb += sky.a * sunLight;

    vec3 reflectionColor = mix(reflectionColorScene, sky.rgb, pow(skylight, 3.0));

    vec3 rtPos = RT_SIMPLE(mat3(gbufferModelView) * L, fragpos, roughness, noise, 12);

    if (rtPos.z < 1.0)

    {
        vec3 previousPosition =
            reprojectDH(mat3(gbufferModelViewInverse) * toScreenSpaceDH(rtPos) + gbufferModelViewInverse[3].xyz, false);
        if (previousPosition.x > 0.0 && previousPosition.y > 0.0 && previousPosition.x < 1.0 && previousPosition.y < 1.0)
        {
            reflectionColor = texture(colortex4, previousPosition.xy).rgb;
        }
    }

    indirectSpecular += reflectionColor * rayContrib;
    fresnelDiffuse += rayContrib;

    // Average indirect specular and fresnel diffuse terms
    vec3 a = (indirectSpecular) + (specTerm * sunLight);
    vec3 b = (vec3(1.0) - fresnelDiffuse);

    //////////////////

    float fresnel = fresnelDiffuse;
    float effectiveAlpha = scene.a * (1.0 - fresnel) + fresnel;

    a *= (inWater ? scene.a : 1.0);

    vec3 baseColorCorrected = scene.rgb * alpha0 * (1.0 - fresnel);

    vec3 outcolor = (a + b * baseColorCorrected.rgb);
    float outalpha = effectiveAlpha;

    return vec4(outcolor, outalpha);
}

vec4 reflections(float skyLight, vec3 normal, vec3 fragpos, vec4 materialProps, vec4 outcolor, float shading, vec3 albedo, float alpha0)
{

    vec3 p3 = mat3(gbufferModelViewInverse) * fragpos;
    vec3 f0 = vec3(materialProps.z);

    float porosity = 0;

    vec4 reflection = calculateSpecularLightingHQ(normal, normalize(p3), albedo, shading, skyLight, pow(1.0 - materialProps.w, 2.0), porosity, fragpos, outcolor, alpha0);

    return reflection;
}
