#version 460

layout(location = 0) in VertexData {
    vec3 positionViewSpace;
    vec3 normalViewSpace;
    vec2 uv;
    vec3 tangentViewSpace;
    float tangentSign;
} frag_in;

layout(location = 0) out vec4 outPosition;
layout(location = 1) out vec4 outNormal;
layout(location = 2) out vec4 outAlbedo;
layout(location = 3) out vec4 outMaterial;

layout(set = 0, binding = 0) uniform sampler2D uTexture;

layout(set = 0, binding = 1) uniform sampler2D uNormalMap;

layout(push_constant) uniform PushConstant {
    mat4 model;
    vec4 color;
    vec4 materialProperties;
    int  showFresnel;
    int  useTexture;
} pc;

void main()
{
    vec3 albedo = (pc.useTexture == 1) ? texture(uTexture, frag_in.uv).rgb : pc.color.rgb;

    vec3 N = normalize(frag_in.normalViewSpace);
    vec3 T = normalize(frag_in.tangentViewSpace);
    T = normalize(T - dot(T, N) * N);

    vec3 B = normalize(cross(N, T) * frag_in.tangentSign);

    vec3 normalTex = texture(uNormalMap, frag_in.uv).rgb;
    normalTex = normalTex * 2.0 - 1.0;

    mat3 TBN = mat3(T, B, N);
    vec3 mappedNormalViewSpace = normalize(TBN * normalTex);

    outPosition = vec4(frag_in.positionViewSpace, 1.0);
    outNormal = vec4(mappedNormalViewSpace, 1.0);
    outAlbedo = vec4(albedo, pc.materialProperties.x);
    outMaterial = pc.materialProperties;
}
