#include "commonMLDX.h"
#include "alpha.h"
#include "inputShaderHelper.h"
#include "inputColorHelper.h"

fragment float4 fragmentFunc(inputVertexType in [[stage_in]]
                                 ,texture2d<half> inputTex0 [[ texture(0) ]]
                                 ,texture2d<half> inputTex1 [[ texture(1) ]]
                                 ,texture2d<half> inputTex2 [[ texture(2) ]]
                                 ,texture2d<half> inputTex3 [[ texture(3) ]]
                                 ,texture2d<half> maskTex [[ texture(4) ]]
                                 ,constant planarUniforms& uniforms[[ buffer(0) ]]
)
{
    vec4 yuvIn;
    yuvIn.a=0.0;
    yuvIn.g = textureFetchNearest(inputTex0, in.texCoordY).r;
    int x=in.texCoordPS.x;
    x&=~1;
    float2 texU=float2(x/8192.0,in.texCoordUV.y);
    yuvIn.b = textureFetchNearest(inputTex0, texU).r;
    x++;
    float2 texV=float2(x/8192.0,in.texCoordUV.y);
    yuvIn.r = textureFetchNearest(inputTex0, texV).r;
    
//    float4 outColor=float4(yuvIn.g);
#ifdef HAS_ALPHA
    yuvIn.a = textureFetchNearest(inputTex3, in.texCoordY).r;
#endif

#ifdef IS_10BIT
    yuvIn*=float4(64.0, 64.0, 64.0, 64.0);;
#endif
    
#ifdef IS_12BIT
    yuvIn*=float4(16.0, 16.0, 16.0, 16.0);
#endif
    
    yuvIn+=stdbias;

#ifndef HAS_ALPHA
    yuvIn.a=1.0;
#endif
    
    
    float4 outColor=vec4(dot(yuv2R, yuvIn),
                  dot(yuv2G, yuvIn),
                  dot(yuv2B, yuvIn),
                  yuvIn.a);
    
    outColor=processColorProfile(outColor);

#ifdef USE_MASK
    multiplyOpacity(outColor, textureFetchNearest(maskTex, in.maskCoord).a);
#endif

#ifdef USE_END_COLOR
    mixColor(outColor, uniforms.endColor, outColor, uniforms.endOpacity);
#endif

    return outColor;
}
