Page 1 of 1

Are my Alpha Blending functions correct?

PostPosted: Sep 12, 2006 @ 11:07am
by Hachaso
Hi!

For the last couple of weeks I have tried to figure out how this works. Going from a simple calculation to a optimized one.
The problem I always encounter is that the result is not the same.

Here's the non optimized function.
The function takes to Colors A and B and an Alpha value the goes from 0.0 - 1.0.
Is this correctly written?

#define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8 ))|(((DWORD)(BYTE)(b))<<16 )))

#define GetR(pixel) (((pixel) & 0x00ff0000) >> 16)
#define GetG(pixel) (((pixel) & 0x0000ff00) >> 8 )
#define GetB(pixel) ((pixel) & 0x000000ff)

unsigned double blend_rgb2( unsigned int ColorA, unsigned int ColorB, double Alpha)
{
unsigned int res = 0;

int abR = (int) (GetR(ColorA) * Alpha + (1-Alpha) * GetR(ColorB));
int abG = (int) (GetG(ColorA) * Alpha + (1-Alpha) * GetG(ColorB));
int abB = (int) (GetB(ColorA) * Alpha + (1-Alpha) * GetB(ColorB));

res = RGB(abB, abG, abR);

return res;
}


Here's the optimized function that results in another value.
Alpha is now mapped to an unsigned char of value 0 - 32

unsigned int blend_rgb3( unsigned int ColorA, unsigned int ColorB, unsigned char ALPHA)
{
unsigned long res = 0;
DWORD sr,sg,sb,dr,dg,db;
DWORD sTemp,dTemp;

sTemp = ColorA;

dTemp = ColorB;
sb = sTemp & 0xff;
db = dTemp & 0xff;
sg = (sTemp >> 8 ) & 0xff;
dg = (dTemp >> 8 ) & 0xff;
sr = (sTemp >> 16) & 0xff;
dr = (dTemp >> 16) & 0xff;

res = (WORD)((ALPHA * (sb - db) >> 5 ) + db | ((ALPHA * (sg - dg) >> 5) + dg) << 8 | ((ALPHA * (sr - dr) >> 8 ) + dr) << 16);

return res;
}


What am I doing wrong?


The part that I don't understand is the bit shift.

For instance if I in the first function send in Alpha = 0.75 and do the calculation I get one result

If I then use the same values for ColorA and ColorB but now I have Alpha = 24 (Meaning that I multiply by 32)
And in turn I divide by 32 in the equation.
Here's the part I get lost in the equation.

Alpha / 32 is the same as Alpha >> 5, since 2^5 is 32.
Doesn't this mean that the result of the bit shift of 5, should be 0.75 ?


Thanks for you help!

PostPosted: Sep 12, 2006 @ 2:15pm
by drgoldie
Hi Hachaso,

this is probably not what you want to hear but:

- your code is far from being optimized (just look into the forum. you can do the complete blend with a single multiplication).

- since you have a working reference function: where is the problem to step through your code and check where the numbers go wrong?

bye,
Daniel

Re: Are my Alpha Blending functions correct?

PostPosted: May 3, 2007 @ 8:55pm
by pappaxray

PostPosted: May 5, 2007 @ 2:10am
by j.edwards
Have a look at Tala's post on this thread:

PostPosted: May 6, 2007 @ 2:34pm
by pappaxray