actionscript-3pixel-shaderpixel-bender

pixel bender 4-color shader


I have no experience with Pixel Bender, and shading languages seem like gibberish to me, so I was wondering if anybody could help me rewriting the following as3 code to function as a Pixel Bender filter/shader. The way it works is that I want to convert 16777215 colors into 4 color tones that I have defined in my palette array (lightest color first, darkest color last). The result is satisfactory, but the performance is bad, which is why I want to make a filter. Here's the code: (sbitmap being an image in my library)

var display:Bitmap = new Bitmap(new sbitmap());
var palette:Vector.<uint> = new <uint>[0x485B61, 0x4B8E74, 0xA6E76D, 0xD1FE85];
var data:BitmapData = display.bitmapData;

addChild(display);

const inc:int = int(0xFFFFFF/4)+1;

for(var i:int = 0; i < data.height; i++)
{
    for(var j:int = 0; j < data.width; j++)
    {
        var color:uint = data.getPixel(j, i);
        var pIndex:int = 0;

        for(var k:int = 0; k < 0xFFFFFF; k += inc)
        {
            if(color >= k && color < k + inc)
            {
                data.setPixel(j, i, palette[pIndex]);
                break;
            }

            pIndex++;
        }
    }
}

Here's a result I got: http://fc05.deviantart.net/fs70/f/2012/243/c/6/screen_shot_2012_08_30_at_1_19_10_pm_by_johnjensen-d5d1ms3.png


Solution

  • <languageVersion : 1.0;>
    
    kernel test
    <   namespace : "Your Namespace";
    vendor : "Your Vendor";
    version : 1;
    >
    {
    input image4 src;
    output pixel4 dst;
    
    void
    evaluatePixel()
    {
        pixel4 k1=pixel4(0.282,0.71,0.38,1);
        pixel4 k2=pixel4(0.294,0.557,0.455,1);
        pixel4 k3=pixel4(0.65,0.91,0.475,1);
        pixel4 k4=pixel4(0.82,0.99,0.52,1);
        pixel4 s;
        s = sampleNearest(src,outCoord());
        if (s.r<0.25) dst=k1; else
        if (s.r<0.5) dst=k2; else
        if (s.r<0.75) dst=k3; else dst=k4;
    }
    }
    

    Catch. The algorithm you use is based on red component only, so the filter only checks ".r" for 1-based float value.