////////////////////////////////////////////////////////////////////////////////
//
//  ADOBE SYSTEMS INCORPORATED
//  Copyright 2009 Adobe Systems Incorporated
//  All Rights Reserved.
//
//  NOTICE: Adobe permits you to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
<languageVersion : 1.0;>
kernel LuminosityMaskFilter
<   namespace : "Flame";
    vendor : "Adobe";
    version : 0;
    description : "Luminosity Mask filter - Flex SDK";
>
{
    parameter int mode <
        minValue:int(0);
        maxValue:int(3);
        defaultValue:int(0);
    >;

    input image4 mask;
    output pixel4 result;

    void
    evaluatePixel()
    {
        result = sampleNearest(mask, outCoord());

        // AI Luminosity mask calculation
        // input is artwork mask argb
        // Flex will only use alpha channel in an "alpha" mask
	  // calculate new alpha channel using AI luminosity calculation

        // invert option is mode bit 1
        // clip option is mode bit 2

        // if (clip != invert) background = 0 else background = 1
        // luminosity = 0.3*red + 0.59*green + 0.11*blue
        // output alpha = alpha*luminosity + (1-alpha)*background;
        // if (invert) output alpha = 1 - output alpha

        // calculate alpha*luminosity for result argb
        // in flash, the mask artwork is premultiplied
        // so we use luminosity and not alpha*luminosity
        float alphaLum = (0.3 * result.r) + (0.59 * result.g) + (0.11 * result.b);
        
        // mode 0 - clip 0, invert 0, background 1 = alpha*luminosity + (1-alpha)*1
        if (mode == 0)
            result.a = 1.0 - result.a + alphaLum;
        
        // mode 1 - clip 0, invert 1, background 0 = 1 - (alpha*luminosity + (1-alpha)*0)
        if (mode == 1)
           result.a = 1.0 - alphaLum;
        
        // mode 2 - clip 1, invert 0, background 0 = alpha*luminosity + (1-alpha)*0
        if (mode == 2) 
            result.a = alphaLum;
        
        // mode 3 - clip 1, invert 1, background 1 = 1 - (alpha*luminosity + (1-alpha)*1)
        if (mode == 3)
           result.a = result.a - alphaLum;
    }
}
