#include <bnb/glsl.frag>
#include <bnb/mediump.glsl>
#include <bnb/transform_uv.glsl>

BNB_IN(0)
vec2 var_uv;

BNB_IN(1)
vec3 bg_uv;

BNB_DECLARE_SAMPLER_2D(0, 1, tex_y);
BNB_DECLARE_SAMPLER_2D(2, 3, tex_u);
BNB_DECLARE_SAMPLER_2D(4, 5, tex_v);
BNB_DECLARE_SAMPLER_2D(6, 7, tex_uv);
BNB_DECLARE_SAMPLER_2D(8, 9, tex_rgb);
BNB_DECLARE_SAMPLER_2D(10, 11, tex_bg_mask);

#include <bnb/sample_camera.glsl>

void main()
{
    vec2 uv = var_uv.xy;
    bnb_FragColor = bnb_sample_camera(uv);
    // discard pixels where uv values are out of range [0, 1]
    vec2 s = step(vec2(0., 0.), uv) - step(vec2(1., 1.), uv);
    bnb_FragColor.rgb = mix(vec3(0., 0., 0.), bnb_FragColor.rgb, s.x * s.y);

    /* store background into alpha */
    float bg_mask_multiplier = bnb_rgba_camera.y;
    float bg_mask = 1. - textureLod(BNB_SAMPLER_2D(tex_bg_mask), bg_uv.xy, 0.).x * bg_mask_multiplier;

    if (bg_uv.z > 0.f) {
        float camera_frame_alpha = bnb_get_uv_frame_alpha(var_uv);
        float bg_frame_alpha = bnb_get_uv_frame_alpha(bg_uv.xy);
        bg_mask *= camera_frame_alpha * bg_frame_alpha;
    }

    bnb_FragColor.a = bg_mask;
}
