/*
==========================================================================================
 Cg Acceleration Research
 Edgar Velazquez-Armendariz (edgar [at] graphics [dot] cornell [dot] edu)
------------------------------------------------------------------------------------------
 EdgeSilh.cg

 Calculates which edges are part of the object silhouette
==========================================================================================
*/

// # 25 instructions, 3 R-regs, 2 H-regs
half3 main(half2 uv : WPOS, 
            uniform float3 eye,
            uniform float crease,           // Index of the first crease edge
            uniform float border,           // Index of the first border edge
            uniform float totalCount,       // Total number of edges to be tested
            uniform float texLen,           // Len of the texture
            uniform samplerRECT sV0,
            //uniform samplerRECT sV1,
            uniform samplerRECT sN0,
            uniform samplerRECT sN1) : COLOR
{

    // For each edge, recovers its vertex and normals from floating point textures
    float3 v0 = texRECT(sV0, uv).rgb;
    //float3 v1 = texRECT(sV1, uv).rgb;
    float3 n0 = texRECT(sN0, uv).rgb;
    float3 n1 = texRECT(sN1, uv).rgb;

    // Calculate the index of the current fragment given its position.
    // The values of WPOS are {0.5, 1.5, 2.5, ...}, so this computes
    // a linearization of the position
    half2 uvAux = uv - half2(0.5, 0.5);
    float index = (uvAux.x + uvAux.y*texLen);

    // The result color to be written
    half3 res = half3(0, 0, 0);

    // Calculates the vector from the eye to V0
    float3 p = eye - v0;

    
    // I will only calculate the appropiate edges
    if (index < totalCount) {
        
        float2 dot01;               // x-dot0, y-dot1
        dot01.x = dot(p, n0);
        dot01.y = dot(p, n1);

        const float2 sign01 = sign(dot01);
            
        // Regular and Crease edges require dot1 calculation        
        if (index < border) {
        
            res = ((index < crease) ? (sign01.x != sign01.y) :          // Regular edge test
                    (sign01.x > 0 || sign01.y > 0)).rrr;                // Crease edge test
        }
        else {
            res = (sign01.x > 0).rrr;                                   // Border edge test
        }
        
    }

    
    // Finally, return the color
    return res;
}