precision highp float;

out vec4 FragColor;

in vec3 v_ViewPos;
in vec3 v_Normal;
in vec2 v_TexCoord;

uniform sampler2D u_BaseColorSampler;
uniform sampler2D u_MetallicRoughnessSampler;
//uniform sampler2D u_NormalSampler;
uniform sampler2D u_OcclusionSampler;
//uniform sampler2D u_EmissiveSampler;
uniform vec4 u_BaseColorFactor;
uniform float u_MetallicFactor;
uniform float u_RoughnessFactor;
//uniform vec3 u_EmissiveFactor;
//uniform int u_DoubleSided;
//uniform int u_Unlit;

uniform r_Light {
    vec3 color;
    vec3 direction;
} dlight;

#define PI 3.14159265
#define EPSILON 0.001

#include "brdf.glsl"

void main() {
    vec3 l = -normalize(dlight.direction);

    // Light received by the surface
    vec3 irradiance = max(dot(l, v_Normal), 0.) * dlight.color;

    // Sample PBR parameters
    vec4 baseColor = texture2D(u_BaseColorSampler, v_TexCoord) * u_BaseColorFactor;
    //baseColor = clamp(baseColor, 0., 1.);
    vec2 metallicRoughness = texture2D(u_MetallicRoughnessSampler, v_TexCoord).rg * vec2(u_MetallicFactor, u_RoughnessFactor);
    //metallicRoughness = vec2(0., 1.);
    //metallicRoughness = vec2(0.);
    metallicRoughness = clamp(metallicRoughness, 0., 1.);
    float occlusion = texture2D(u_OcclusionSampler, v_TexCoord).r;
    occlusion = clamp(occlusion, 0., 1.);

    // Compute BRDF
    vec3 brd = brdf(l, -normalize(v_ViewPos), v_Normal, metallicRoughness.x, metallicRoughness.y, baseColor.rgb, 0.5);
    FragColor = vec4(irradiance * brd * occlusion, baseColor.a);
}
