PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Help for OPACITY effect algorithm ?

Given :

PIXEL* frontbuffer = new PIXEL[240 * 320];

PIXEL* backbuffer = new PIXEL[240 * 320];

And assuming that PIXEL is 'unsigned short', how would I implement an OPACITY effect?

Any algo, code or help are welcome. Thanks in advance.
I'm unsure about your all in one approach as it implies a fixed opacity.

My code for blend of two pixels is based on a 32 levels of mix and 565 RGB which is very common.

int mask=0x07e0f81f; // This is My favorite number. :-)
int c1=*frontbuffer++; // you need 32 bits it's a conversion anyway
int c2=*backbuffer++; // Don't know if it complains without (int)
int opacity=13; // whatever 0-32

c1|=c1<<16;
c1 =c1&mask;
c2|=c2<<16;
c2 =c2&mask;
c1 =c1*opacity;
c1+=c2*(32-opacity);
c1=(c1>>5)&mask;
c1|=c1>>16;
*anotherbuffer++=c1; // Don't know if they are both created each frame
// Can't just keep adding to one or it'll white out
Do above (320*240) times in a loop.

Im sure it's signed - unsigned has hick ups, but its the rough version.
First optimisation would be to try to write in words, so pairs of above and in sequential memories. And with so much effort do some tricks with the opacity level. Thiner at the edges to make beveled glass make it earn that many CPU cycles. Don't allow the opacity to <0 or >32
Basically I want to implement a fade out/ fade in effect and fixed opacity.

Thanks Jinks.
This is what I use, but it's not optimised except for only using 2 multiplications per pixel (but I saw a post where Johan was saying he could do it on one). Basically I copied what PocketFrog does and put it into my class structure:

Code:


const TPixel16 RED_MASK = 0x1F << 11;
const TPixel16 GREEN_MASK = 0x3F << 5;
const TPixel16 BLUE_MASK = 0x1F;
const int RED_SHIFT = 11;
const int GREEN_SHIFT = 5;
const int BLUE_SHIFT = 0;


void CopyMaskedAlphaTo(TSurface16 *Surface, int x, int y, TPixel16 MaskColor, int Alpha)
{
PPixel16 pSrc, pDest, pEnd;
int iSrcWidth, iDestWidth;

//if alpha is 100% then just call masked draw
if (Alpha >= 32)
{
CopyMaskedTo(Surface, x, y, MaskColor);
return;
}

if (!CalcClipping(Surface, x, y, &pSrc, &pDest, &pEnd, &iSrcWidth, &iDestWidth)) return;

do
{
int i = 0;
do
{
if (*(pSrc+i) != MaskColor)
{
TPixel16 RB1 = *(pDest+i) & (RED_MASK | BLUE_MASK);
TPixel16 G1 = *(pDest+i) & (GREEN_MASK );
TPixel16 RB2 = *(pSrc+i) & (RED_MASK | BLUE_MASK);
TPixel16 G2 = *(pSrc+i) & (GREEN_MASK );

TPixel16 RB = RB1 + (((RB2-RB1) * (Alpha)) >> 5);
TPixel16 G = G1 + (((G2-G1)*(Alpha))>>5);
RB &= (RED_MASK | BLUE_MASK);
G &= (GREEN_MASK);

*(pDest+i) = RB | G;

}

i++;
} while (i < iSrcWidth);

pSrc += Width;
pDest += iDestWidth;
} while (pSrc < pEnd);
Actually I did a little search for opacity after posting.

GAPIDRAW forum came up seemed to have ways of doing it easily.
If you are not planning anything other than block, and you post there so I assume you are using GAPI, just use its function.

Comes up in screen fades by the look of it.

I don't use any of these fancy librarys myself so I won't quote the code in case I make a dumb error.
If you combine your approaches, you would end up only having a single multiplication. What i am doing here is basically the three color ops in single register like Jinks, and using the simple transformation
s1*a+s2*(1-a) = a*(s1-s2)+s2
like j.edwards.

//spread colors
source1 = (source1 | (source1<<16)) & mask;
source2 = (source2 | (source2<<16)) & mask;

//do alpha op
dest = ((((source1-source2)*alpha)>>5) + source2)&mask;

//recombine colors
dest |= dest >> 16;

Voila a single multiplication :)
Thanks Tala! I just quickly updated my alpha blit functions and it works, but I've not had time to do any performance testing yet. Do you have a ballpark idea of how much faster it is?
Tala:
Very nice routine. I added this in about 30 seconds and it works great.

Well done!

Cheers,

rcp
Tala: it's a very neat algorythm. I did not imagine that it could be done with one multiply. Thanks for posting it.
Tala: You will get overflow using your algorithm (e.g. if R and B are shifted to the high bit and R is 31 the multiplication will not fit into 32 bits). The only way I know that you can reach one multiplication per pixel is to operate on two pixels simultaneously and use two multiplications for these. And achieving that is not trivial.
I took it as the mask being:

0x07e0f81f

I.e. the green goes high and the red and blue stay low.

So, red has 6 clear bits above it, green has 5, blue has 5. That way it can't overflow can it?

Oh and for a ballpark guess ;):

Routine that separates all 3 registers and uses 3 multiplies: 0 setup + ~25 cycles per pixel
Single-multiply routine: 2 cycles setup + ~11 cycles per pixel

(Cycle counts don't include loop costs).
refractor wrote:
So, red has 6 clear bits above it, green has 5, blue has 5. That way it can't overflow can it?


Negative numbers like a 6th bit, I would think, But you should be able to see it!!!!!

Anyone know cycle timings for MUL in StrongARM, in days pre StrongARM when we counted everything. It worked on pairs of bits from the low end, 0-3 in one cycle etc so negative was too be avoided. Don't even know which is multiplied by which now a days ( So SLACK ).

Anyway I'm building a dust cloud over a space scape today, so I'll have a look. :D
Answering my own question:

0x07e0f81f * 0x1f = F43E0BC1

0xF43E0BC1>>5 = 11110100001 1111000001011110

1111000001011110 |
0000011110100001 =
1111011111111111

Ok, so the bottom bit of red (or is it blue - I always forget the pixel order) got killed by underflow (killed by the shift). But that's all.
Anyone know cycle timings for MUL in StrongARM


Yep.

Multiplies
The multiplier-accumulator is a separate unit running in parallel with the execute (E) and buffer (B)
stages of the pipe. However, use of the multiplier blocks other instructions from using the execute
and buffer stages of the pipe for one or more cycles. For calculating instruction timing, the
multiplier portion occupying the E-stage and the accumulator in the B-stage of the pipeline can be
viewed as follows:
• The E-stage (multiply array) takes 1-3 cycles depending on the value of Rs.
• The B-stage takes one cycle for a MUL or MLA and two cycles for a UMULL, SMULL,
UMLAL or SMLAL; one cycle for a 32-bit result, and two cycles for a 64-bit result.
The multiplier supports signed early termination on Rs, and retires 11 bits on the first buffer stage
cycle and 12 bits on the second buffer stage cycle. In other words, if bits 31 to 11 are all 0 or all 1,
then the multiply will spend only one cycle in the execute stage. If bits 31 to 23 (but not 31 to 11)
are all 0 or all 1, then the multiply will spend two cycles in the execute stage. If neither of these is
true, it will spend three cycles in the execute stage.
A multiply can read its inputs through bypasses at the start of the execute stage. The result of a
multiply becomes available through bypasses when the instruction leaves the buffer stage.
If there are two consecutive multiplies in the instruction stream, then the second multiply stalls in the
decode stage, and does not enter the execute stage until the first multiply completes its buffer stage.
A multiply can enter the buffer stage as soon as the previous instruction leaves the buffer stage.
Outstanding cache fills do not prevent a multiply from entering the buffer stage.
A long multiply takes one extra cycle. The multiplier outputs RdLo first, then RdHi in the last
buffer stage cycle.
If a multiply sets the condition code, there will be at least a 3-cycle delay between the multiply
entering the execute stage and the next instruction entering the execute stage. This is due to the
need to feed back the condition codes from the B-stage for conditional execution, requiring an
additional cycle and a NUL instruction bubble in the E-stage.
The timings of multiply and accumulate instructions are the same as those of multiply instructions.


Cut and pasted from the "StrongARM** SA-110 Microprocessor Instruction Timing Application Note" (cunningly called 27819401.pdf).

Addendum: naming conventions to help with the above:
MUL{<cond>}{S} <Rd>, <Rm>, <Rs>
Thanks for the timing stuff, I'll seperate my MULs where possible. No idea about the initial phase thingy was there.

Rd can't be Rm, so it's not always a matter of changing order when you are short of registers.

And on the topic, I can't see it, Very funky.
Maybe a slight blue tint. :wink:
Rd can't be Rm, so it's not always a matter of changing order when you are short of registers.

Exactly. Sometimes it gets quite involved trying to figure out whether freeing up a register to store the result in order to switch the parameter order is actually worth it. But as that's probably the most complicated thing about cycle-counting in ARM assembly (loads and stores being the next obvious candidates), I'll let them off (ignoring XScale with all its weird timings).

As you said, the main thing is not to put multiplies next to each other, and to try not to use the result in the immediately following instruction(s). Oh, and never to set the flag with a MUL.

in days pre StrongARM

As you're in the UK, I'm presuming you had/have a Risc PC (or an older Acorn)? :p
I was thinking that if, for instance, your subtraction of the blue components went negative - it would 'borrow' from the next high bit.

Wouldn't that screw up the colors somewhat?
Good point - I'll poke it when I get home and find out properly (if nobody else does it beforehand).
0x07e0f81f * 0x1f = F43E0BC1

0xF43E0BC1>>5 = 11110100001 1111000001011110

1111000001011110 |
0000011110100001 =
1111011111111111

Ok, so the bottom bit of red (or is it blue - I always forget the pixel order) got killed by underflow (killed by the shift). But that's all.



I am not quite sure, what you are trying to show here. But lets take your example:

0x07e0f81f * 0x1f = F43E0BC1

which is the exact number including the fraction after the decimal point (think of it as fixed point 6.5_5.5_0_ 5.5 number). Then you shift back and clear the fraction by applying the mask again.

(F43E0BC1>>5)&mask; = 111101000001111000000011110

combine:

1111000000011110 |
0000011110100000 =
1111011110111110

R = 11110
G = 111101
B = 11110

which is correct without any under/overflow). G of course has a higher precision.

Tala

ps. One could argue, that one need at least 33 bits to make this work correctly (due to sign issues). However, since we know that the result of the whole operation is always positive, the sign can be neglected.
Code:
int topme=65536;
int mask=0x07e0f81f;
for(int fx=32;fx>=0;fx--) {
int bad=0;
int vbad=0;

int red=0;
int green=0;
int blue=0;

for(int s0=1;s0<topme;s0++) {
int c0=(s0|(s0<<16))&mask;
for(int s1=1;s1<topme;s1++ ) {
int c1=(s1|(s1<<16))&mask;

int jinks=(((c1*fx)+(c0*(32-fx)))>>5)&mask;
int tala=((((c1-c0)*fx)>>5)+c0)&mask;
if(jinks!=tala) {
bad++;
int err=abs((jinks&0x1f)-(tala&0x1f));
if(err>blue) blue=err;
if(err>1) vbad++;
err=(abs((jinks&0xf800)-(tala&0xf800)))>>11;
if(err>red) red=err;
if(err>1) vbad++;
err=(abs((jinks&0x7e00000)-(tala&0x7e00000)))>>21;
if(err>green) green=err;
if(err>1) vbad++;
}
}
}
printf("FX=%i,bad %i,vbad %i, R%i G%i B%i\n",fx,bad,vbad,red,green,blue);
}


I expected one bad which is why I put the stats in, but nothing so far 0-8 fx one way, 31-29 the other "it will take some time". Is int always 32-bit obviously I'm running on PC. The forum appears to strip my white space sorry if it's hard to read.

long int same so far.
I am not quite sure, what you are trying to show here.


That it didn't overflow for positives (I didn't mask the result - I was in a hurry :P).
Jinks: wrap it in "[code]" tags rather than "[quote]".
refractor wrote:Jinks: wrap it in "[code ]" tags rather than "[quote ]".

Thankyou, far better.

I ran +=8 loops and nothing came up. Ran same starting at 7 to try for the high bits nothing.

It is looking quite safe, not even a blue tint. Ain't maths pretty! I think the point is stop thinking of it as RGB data just a number. If the maths sais that number is right it's right. Then start thinking of it as RGB data again.

Think I'm going to run it in on computer I'm not using and get on with the space scape. Then get the real question is it FASTER.

MODIFY**
Result not one bad, so the stats are n/a.
Didn't expect it when I wrote it, anyway find a value that doesn't work as I can't I've tried to check all 2^37 combinations.
Pejo Software - Per · 23 Apr 2004, 20:21 UTC
This is pretty good!
I tried it and it was about 17% slower than my 2 pixel solution (tested a sprite with keysource). This means that I will use your solution when source and destination isn't aligned. Previosly I had almost 100% performance penalty there. So thank you! I will of corse not use your solution when doing a 50% blend because then you can go even faster.

I don't see how this would lead to overflow. Isn't this is basicly the same thing you do when operating on 2 pixels. I have not given this much thought though, I'll leave this to all you smart people out there!

I am also really glad that I went for a template solution, this makes it really easy to add new pixel operations (like this one), I am getting a slight performance penalty for this compared to specialized functions but it gives a much more maintainable code.
Cool discussion. Smart people pops up :-)

Btw, I have 1 more issue with my code. Can I post it here? and hope someone can help me again.

Thanks.
You don't need to ask - just post the question :P
Jinks,

Why don't you compare those 2 methods with the "long" way of doing it? In other words, calc the R,G, and B values separately and put them back together.

I've tried this stuff before, and I always ended up with a blending routine that chokes on pure colors like (255,0,0)...
fast_rx wrote:Jinks,

Why don't you compare those 2 methods with the "long" way of doing it? In other words, calc the R,G, and B values separately and put them back together.

I've tried this stuff before, and I always ended up with a blending routine that chokes on pure colors like (255,0,0)...


My normal way of doing it is bomb proof. :D

MODIFY LATER TO TIE UP LOOSE ENDS.
If you split RGB into 0-31, 0-63, 0-31 for both colours then do mul and shift down by >>5. You get same components. So the method is bomb proof.

I normally push it futher than that by 0-31 opacity flip ^31 not 32- then gather the lost colour just after blend before >>5. Dither variable is open over loop.

ink+=dither&(mask<<5);
dither=(dither&mask)+(ink&mask);
ink=(ink>>5)&mask;

which does a needed job of reducing graduating colour banding in 565.

Okay I might recode it to test but I can "see" the bits in mine they just don't stray. What got me about Tala's method was +/- 0-31 clearly uses 6 bits and there is only 5 available above the green and it can't be carry or something as 0xf8 only has five to green. That's why all the stat stuff is in there to quantify the error - which then didn't happen.

Anyway I've got my simple brain trying to code two Gourauds one for space one for clouds moving in different directions. With it all trying to just use a normal set of registers so my simple head is full of crazy shit techniques and will be till I come down. :)
This code im using is an extract from easyce and mobilecore projects of Jacco ;-)

Code:
void CSurface::BltFast(LONG x, LONG y, CSurface* source)
{
BUFFER* dst = m_Buffer;
BUFFER* src = source->GetBuffer();

if ((src) && (dst))
{
int srcwidth = source->GetWidth();
int srcheight = source->GetHeight();
int srcpitch = srcwidth;

int dstwidth = GetWidth();
int dstheight = GetHeight();
int dstpitch = dstwidth;


if ((srcwidth + x) > dstwidth) srcwidth = dstwidth - x;

if ((srcheight + y) > dstheight) srcheight = dstheight - y;

if (x < 0) src -= x, srcwidth += x, x =0;

if (y < 0) src -= y * srcpitch, srcheight += y, y = 0;


if ((srcwidth > 0) && (srcheight > 0))
{

/* TRANSPARENT BLIT
*
* Pls optimized the code below for transparency. Thanks.
*/

for (int len_y = 0; len_y < srcheight; len_y++ )
{
for (int len_x = 0; len_x< srcwidth; len_x++)
{
int x1 = x + len_x;
int y1 = y + len_y;

BUFFER spritepixel = *(src + len_x + len_y * srcpitch);
BUFFER* address = dst + x1 + y1 * dstpitch;

if (spritepixel != source->GetColorKey())
*address = spritepixel;
}
}
}
}
}




I want to optimize this code for TRANPARENT BLIT. This works fine but it's too slow. Maybe the issue is on my for(....) loops. Any solutions will be appreciated. Pls read my comment on the code.

Thanks.
You've got a multiply per-pixel. That's really bad for a simple bitmask blit.

Instead of using integer indices into your color arrays, just use pointers to the arrays. Here's an example:

Code:

PIXEL buffer[width*height];

//Instead of this:
for (int y=0; y<height; y++)
for (int x=0; x<width; x++)
buffer[x+y*width]=0;

//Do this
PIXEL *pYCur=buffer;
PIXEL *pYEnd=buffer+y*width*height;

while (pYCur<pYEnd) {
PIXEL *pXCur=pYCur;
PIXEL *pXEnd=pXCur+width;
while (pXCur<pXEnd)
*pXCur++=0;
pYCur+=width;
}


That's untested, but you should get the idea. In this example I'm just setting each pixel to 0, but you would do your copy / pixel math / whatever instead. This would be substantially faster than your current method.

Dan East
Pejo Software - Per · 24 Apr 2004, 19:08 UTC
denthorq, if GetColorKey() isn't an inline function you should perhaps consider move it outside the loops.
@denthorq

Try this:

Code:

dst += x + y*dstpitch;
COLORKEY = source->getColorKey();

for (int len_y = 0; len_y < srcheight; len_y++ )

{
for (int len_x = 0; len_x< srcwidth; len_x++)
{
if ((spritepixel=*src++) != COLORKEY)
*dst = spritepixel;
dst++;
}
dst += dstpitch;
src += srcpitch;

}


Instead of having explicit loop variables, you could as well thest the buffer pointer directly as DanEast suggested. This would save you the "len_y++" and "len_x++" operations.