Question

Suppose we have a 32-bit PNG file of some ghostly/incorporeal character, which is drawn in a semi-transparent fashion. It is not equally transparent in every place, so we need the per-pixel alpha information when loading it to a surface.

For fading in/out, setting the alpha value of an entire surface is a good way; but not in this case, as the surface already has the per-pixel information and SDL doesn't combine the two.

What would be an efficient workaround (instead of asking the artist to provide some awesome fade in/out animation for the character)?

Was it helpful?

Solution

I think the easiest way for you to achieve the result you want is to start by loading the source surface containing your character sprites, then, for every instance of your ghost create a working copy of the surface. What you'll want to do is every time the alpha value of an instance change, SDL_BlitSurface (doc) your source into your working copy and then apply your transparency (which you should probably keep as a float between 0 and 1) and then apply your transparency on every pixel's alpha channel.

In the case of a 32 bit surface, assuming that you initially loaded source and allocated working SDL_Surfaces you can probably do something along the lines of:

SDL_BlitSurface(source, NULL, working, NULL);
if(SDL_MUSTLOCK(working)) 
{
    if(SDL_LockSurface(working) < 0) 
    {
        return -1;
    }
}

Uint8 * pixels = (Uint8 *)working->pixels;
pitch_padding = (working->pitch - (4 * working->w));
pixels += 3; // Big Endian will have an offset of 0, otherwise it's 3 (R, G and B)
for(unsigned int row = 0; row < working->h; ++row) 
{
    for(unsigned int col = 0; col < working->w; ++col) 
    {
        *pixels = (Uint8)(*pixels * character_transparency); // Could be optimized but probably not worth it
        pixels += 4;
    }
    pixels += pitch_padding;
}

if(SDL_MUSTLOCK(working)) 
{
    SDL_UnlockSurface(working);
}

This code was inspired from SDL_gfx (here), but if you're doing only that, I wouldn't bother linking against a library just for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top