#version 430

in vec2 uv;

layout(location = 0) out vec4 frag;

uniform float g_time;


layout(binding=0, rgba32i) uniform iimage2D mesherTriangles;
layout(binding=1, rgba32f) uniform image2D mesherVertPos;
layout(binding=2, rgba32f) uniform image2D mesherTriNorm;

uniform float div = 1.0;

uniform mat4 modelMatrix;


ivec2 getTrip(int idt) {
    ivec2 triBufSize = imageSize(mesherTriangles);
    ivec2 trip;
    trip.y = idt/triBufSize.x;
    trip.x = idt-trip.y*triBufSize.x;
   // trip.y = 0;
    return trip;
}

void main() {
    ivec2 uvs = ivec2(gl_FragCoord.xy);

    vec4 screen = vec4(0.0);

    ivec2 triBufSize = imageSize(mesherTriangles);

    int divi = int(div);

    int pid = uvs.x+uvs.y*triBufSize.x;

    if (pid > div*div*2) {
        discard; return;
    }

    vec3 n = vec3(0.0);
    ivec4 tvids = imageLoad(mesherTriangles, getTrip(pid));

    vec3 va = imageLoad(mesherVertPos, getTrip(tvids.x)).xyz;
    vec3 vb = imageLoad(mesherVertPos, getTrip(tvids.y)).xyz;
    vec3 vc = imageLoad(mesherVertPos, getTrip(tvids.z)).xyz;

    vec3 d1 = vb-va;
    vec3 d2 = vc-va;

    n = cross(d1,d2);

  //  n.xy /= 256.0;

//     n.xyz = (modelMatrix*vec4(n.xyz, 1.0)).xyz;

    n = normalize(n);
//    n = vec3(1.0, 0.0, 0.0);

    imageStore(mesherTriNorm, uvs, vec4(n, 0.0));

    discard;

    screen.a = 1.0;
    frag = screen;


}
