#version 330 core
out vec4 FragColor;
in vec2 TexCoords;

uniform sampler2D image;

void main()
{
    mat3 sx = mat3( 
        1.0, 2.0, 1.0, 
        0.0, 0.0, 0.0, 
        -1.0, -2.0, -1.0 
    );

    mat3 sy = mat3( 
        1.0, 0.0, -1.0, 
        2.0, 0.0, -2.0, 
        1.0, 0.0, -1.0 
    
    );

    vec3 normal = texelFetch(image, ivec2(gl_FragCoord), 0 ).xyz * 2.0f - 1.0f;
    vec3 I[3];
    for (int i=0; i<3; i++) {
        vec3 norm1 = texelFetch(image, ivec2(gl_FragCoord) + ivec2(i-1,-1), 0 ).rgb * 2.0f - 1.0f;
        vec3 norm2 =  texelFetch(image, ivec2(gl_FragCoord) + ivec2(i-1,0), 0 ).rgb * 2.0f - 1.0f;
        vec3 norm3 = texelFetch(image, ivec2(gl_FragCoord) + ivec2(i-1,1), 0 ).rgb * 2.0f - 1.0f;
        float sampleValLeft  = dot(normal, norm1);
        float sampleValMiddle  = dot(normal, norm2);
        float sampleValRight  = dot(normal, norm3);
        I[i] = vec3(sampleValLeft, sampleValMiddle, sampleValRight);
    }

    float gx = dot(sx[0], I[0]) + dot(sx[1], I[1]) + dot(sx[2], I[2]); 
    float gy = dot(sy[0], I[0]) + dot(sy[1], I[1]) + dot(sy[2], I[2]);

    float g = sqrt(pow(gx, 2.0)+pow(gy, 2.0));

    if(g > 1.0) {
        FragColor = vec4(1., 1., 1., 1);
    } else {
        FragColor = vec4(0., 0., 0., 0.);
    }
}