#include "core.fsh"
#include "pbr.fsh"
#include "commonInput.fsh"

in highp vec3 P_f;

uniform sampler2D texEmi;
uniform sampler2D texEmiMask;
uniform vec2 emiUVOff[PBR_EMI_LIGHT_NUM];

flat in int emiIdx_f;

vec3 LinearToSRGBWrapper(vec3 col)
{
#ifdef PBR_DISABLE_SRGB
    return col;
#else
    return LinearToSRGB(col);
#endif
}

layout(location = 0) out vec4 fragColor;

void main()
{
    PBRInfo info;
    info.albedo = getBaseCol();
    vec2 metaRough = getMetaRough();
    info.metallic  = metaRough.x;
    info.roughness = metaRough.y;
    vec4 emi = texture(texEmi, uv_f);
    float emiMask = texture(texEmiMask, uv1_f + emiUVOff[emiIdx_f]).r;
    emi *= emiMask;
    info.emissive  = emi.rgb;

    info.dirN = getNormal();
    info.dirV = normalize(_WorldEye - P_f);
    vec3 dirR = reflect(-info.dirV, info.dirN);
    
    info.iSpec = IBL_Reflect(dirR, metaRough.y);
    info.iDiff = IBL_Irradiance(info.dirN);
    float alpha;
    vec3 color = BRDF_PBS(info, alpha);
    color = LinearToSRGBWrapper(color);
    alpha = min(alpha + emi.a, 1.0);
    fragColor = vec4(color * alpha, alpha);
}
