/*
==========================================================================================
 Cg Acceleration Research

 Optimized: Edgar Velázquez-Armendáriz - edgar [at] graphics [dot] cornell [dot] edu
 Original:  Eugene Lee (el77 [at] cornell [dot] edu)
------------------------------------------------------------------------------------------
 AntiAliasing.cg

 Performs cheap anti-aliasing given pixel classification information.
==========================================================================================
*/

// This:  # 23 instructions, 3 R-regs, 1 H-regs
// Orig:  # 33 instructions, 3 R-regs, 1 H-regs

half4 AntiAliasing(
    in half2 pixelPos : WPOS, 
    const uniform samplerRECT pixelClass, 
    const uniform samplerRECT color,
    const uniform samplerRECT neighborWeightTable) : COLOR
{       
    int dx, dy;
    half4 selfColor;
    half2 edge;
    half3 neighborColor;
    half2 bitmask;
    half  neighbor, weight;

    // Will not be needed until later, mask latencies
    selfColor = texRECT(color, pixelPos);

    edge = round(texRECT(pixelClass, pixelPos).rg * half2(255, 255*64));
    bitmask = half2(edge.r + edge.g, 0);
    
    half2 neighborWeight = texRECT(neighborWeightTable, bitmask).rg;
    neighbor = neighborWeight.r;
    weight = neighborWeight.g;
    
    half2 d;    // x=dx, y=dy
    d.x = modf(neighbor/4.0, d.y);
    d = half2(-1, 1) + half2(4, -1) * d;
    const half2 neighborCoord = pixelPos + d;

    neighborColor = texRECT(color, neighborCoord).rgb;

    half4 outColor;

    outColor.rgb = lerp(neighborColor, selfColor.rgb, weight);
    outColor.a = selfColor.a;

    return outColor;
}