Thursday, April 5, 2012

Premultiplied hip hip.... huraaah!

Although I agree that premultiplied alpha is getting to be some sort of "thing you do, even without an alpha channel", it can make your life easier or in this case visualize PNG data into the Unity editor right. The following picture and related caption, illustrate a problem when alpha and blending are not working along right.
Image taken from Cocos2D's forums

Without going too far into premultiplied alpha, the blog I linked to - from the great Tom Forsyth -  will tell you everything you might want to know and more about the advanced reasons why you should use premultiplied alpha, but essentially in a pre-multiplied alpha pipeline, all source images have thier RGB color channels multiplied by their alpha component when they are either imported or loaded and before they are used. As you might have read, this has important implications far beyond changing arguments in the default blending equation (SRC_ALPHA * SRC_RGB + (1-SRC_ALPHA) * DST_RGB --> GL_ONE * SRC_RGB + (1-SRC_ALPHA)*DST_RGB).

Unity by default does not play around with your PNG unlike for example Xcode which, following good Apple tradition, thinks it knows better than you do... truth to be told it is right in this case for example when it decides PNG's should be premultiplied and go through pngcrush (the last thing might be up for debate). Unity does not seem to be able to make up his mind about what kind of alpha set-up it likes best so you have the images looking all wrong in the preview window inside the inspector (well, the alpha portion of it does) while fine luckily in the game scene and in the scene editor where it actually counts.
If you edit the default ex2D (popular Unity toolkit for 2D graphics management) shader and change the blending equation to be premultiplied alpha based you will see the game window and the scene editor with alpha issues. What to do? Well, to our help a nice developer called maxme developed a nice little Python and C based utility that converts PNG's into premultiplied ones if they need to be changed. You can find his github page here. You can then use a bash script or an Automator action if you run MacOS X to quickly edit your files and apply alpha premultiplication if they have not been premultiplied yet.
To go back to the linked Automator scripting fun we talked about quite a while ago, here is the script you would run to actually convert the PNG (assuming you have copied, su cp, the compiled C script into /usr/bin/):

for f in "$@"
do
    echo $(dirname "$f")
    cd $(dirname "$f")
    echo "Premultipling alpha"
    /usr/bin/NPMApng2PMApng "$f" "$f"
done

The result is the following nice Unity's Inspector pane -->

... and voilà!


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...