PocketMatrix forums

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

Bitwise help!!!

I have a problem. I have a value that I don't want to be bigger than 255. If it is higher than 255 then it should use 255. In other words

270: use 255
75: use 75

Now, I can do this easily using a conditional if statment or maybe even inline conditions (a > b ? a : b), but both of these operations are sloooow, so what I want is some way to make it using bitshifts and bitwise operators. I know you guys are programming minds so I know you can help me. Besides it would be a fun mini competition you guys could have or something. Simply showing who is the best "bitboy". I would also like to have the reverse, where if the value is below 0 it should be 0.

Both are appreciated.

Thanks!

- F
Moose or Chuck · 20 Jul 2001, 15:29 UTC
if (a > b) {
int c;
a - b = c;
a << (c/2);
}

I just came up with quickly, so it's probably wrong, and I've never used bit shifters before. But that's my best guess. And I don't know what you're talking about, which thing is slow? The ":" or the ">" ? Cause if it's the ">" then I could come up with another way to use bitshifts too.
Moose or Chuck · 20 Jul 2001, 15:33 UTC
if (a/255 = 1)
could work well too.
But .. whatever, I'm just guessing anyway.
Moose or Chuck · 20 Jul 2001, 16:27 UTC
Se.. told you I had no clue what you were talking about Freddy Mauler.
That can be done very easily and efficiently. Say i is the integer in question:

i&=0xff;

[edit] Just thought about that more. The result will never be greater than 255, but it may be less than that if i>255. Let me think on that one.

Dan East
Is an int or short or what?

you could do
i&=0xff

Which is best and fastest, but has the problem stated by Dan East.

Why not (A>B?A:B) ?  Its gonna be faster than anything else I can think of.  I mean you'd have to get all the bits in the hiword to flip on if it is >0 and then OR it with the original anyway to do the test, so you have a comparisson no matter what, right?
What you wish to do is called Saturated Arithmetic.  I do this when mixing (summing) audio wave data because you don't want values rolling over/under as it results in a click or pop in the output.  I also do it clamping lighting values in my 3D code.  My stuff is done in ARM assembly and can't be translated to C/C++ easily, but basically is does a compare based on the Carry flag.

I haven't given a lot of thought to this sort of thing from a high-level language perspective, but why do you think the conditional is slow?  Have you measured it?  How many times are you calling this code per frame?

Dan,
The AND op you've posted is not the proper solution.  If the value is 256, your AND will give 0, when what he needs is 255.

Let me stew on this over lunch and if I come up with something I'll share it.

OK, you can try this. (Credit to The Broiler)

x = original value
L=lobyte of x
H=hibyte of x

L|=H; H<<;
L|=H; H<<;
L|=H; H<<;
L|=H; H<<;
L|=H; H<<;
L|=H; H<<;
L|=H; H<<;
L|=H;

Should produce the right value....but is it faster than a<b?a:b .... I don't know.
Oops...can't use a normal shift....you have to use a wrap shift.....will find assm function and get back to you.
Bad Fredrik!

You have occupied the minds of my office with this problem of yours!

I have an idea for you.  Use the register keyword when you define the variables for the comparison.  Then it'll be quick...

Bad Fredrik!

:)

Hey, is this for Argentum?  I thought you were shipping in a few weeks?  Hmmm.......
It is for argentum. It is called for every semi-transparent pixel in a sprite each frame (which makes it quite many). I'd just thought I could do some optimizations. It works fine as it is, but if I managed to get this problem solved it would probably mean a lot to performance.

as for the i&=0xff; sollution I get the same results by just having it as a unsigned char so that doesn't help :(

Thanks for the effort. It appears noone has found the ultimate sollution so keep working on it lads. Who will be the first to "crack the nut"?
I came up with this for a 32-bit int:

   x &= (!(x >> 31))*0x7fffffff;
   x |= (!!(x >> 8 ))*255;
   x &= 255;

Obviously it's not all bit shifts as there are two multiplies used.  You could replace those with 2-entry lookup tables since the multiplicand will be either 1 or 0.  However fetching from a table in memory is probably going to be slower than doing the multiplication since x will most likely be in a register.

I still contend that doing the conditional test to perform the clamp will be faster, not to mention it's more readable.

  x = min(255, max(0, x));


Fredrik, I can't think of an efficient way to do it without conditional logic. What you want (not even counting negative integers) from a bitwise standpoint is if any bit 0xffffff00 is non zero, then the output should be 0x000000ff. Obviously the lowest 8 bits can be any value in that case, so we would have to set them explicitly. Only one of the upper 24 bits need be set, so we don't have a known set of bits to shift over or try and work with.
[pause]
I've thought about it some more, and I'm pretty sure it can't be done (more efficiently) without conditional statements. In some situations you want to leave the bits 0xff as-is, while in others you want to set them. That requires logic.

Like you suggested:
i>0xff ? 0xff : i;

I would recommend creating a lookup table. I assume you are performing math on two bytes and want the result to be a byte. Precalculate a lookup table, which will take 65k or RAM (which really is not much, PQ allocates at least 100 times more at startup). Not only will it save you the processing required to check for the overflow / underflow problem you stated above, but it will save the actual math required to do the sprite transparency.

Dan East
You know what? I think I'm gonna leave it as it is with the conditional statement for now. In a later patch we might have an optimized version. Now that code is pretty fast anyways, so there shouldn't be any big troubles...but it is always fun to have the code FASTER!!!

THANKS FOR ALL YOUR HELP!!! You guys are great and this is the only forum where I can actually get some decent replies. In other forums I would just get "what is a bitwise operator?" and "Malmer, what kinda name is that, it sounds like Mauler" ;-)

-- F

Before you revisit this you might want to comment out the alpha blending routine and profile the drawing code.  Then put it back in and note the difference.  If the performance increase is miniscule, then you might want to point your optimization efforts elsewhere.

I wish there was a decent profiler available for eVC.  I'd like to compare the speed of using a lookup table to perform alpha blending vs. using a multiply and a bit shift.

PQ allocates over 6.5M at startup?  Now that is sassy!

Now that I think of it, if you're doing alpha blending correctly it won't overflow anyway.  Here's the typical alpha blending equation:

sC = source color (sprite)
dC = dest color (frame buffer)
a = alpha blending value

NB: assumes color and alpha are in the range 0.0..1.0.

dC = (sC * a) + (dC * (1 - a))

How is this addition going to overflow?

if you do alpha like that it will be incredibly slow (floats). no, it would be insanely slow. Besides getting the source pixel color in this case requires you to calculate the "real" color since in the source image it is faded out to black. So I have to use the alpha to figure out the real value, then I have to draw the pixel over using an alpha value. Now I don't do that process because that would be slow with many multiplications (SLOW) and maybe some divisions (SLOWER). So instead I managed to isolate a pretty nice formula using just bitshifts and one multiplication. The thing itself takes litterarly no performance if it wasn't for that it in rare cases can overflow. Why do you think Ag is the first PPC game with alpha blended sprites (am I right here?)

As for the technical name of this type of alpha blending I think it is called additive alpha blending.

// Fredrik
Actually...been testing some...and it isn't the method itself that causes it. What is causing it is the fact that images containing the sprite and the alpha channel aren't truecolor but are palletized making the color of certain areas of them to be less exact compared with the alpha.

Either way, I think I've found a way to fix these issues quite easily...I'll get back to you...So hopefully I can remove the conditionals alltogether. Hurray!
HAHA! I fixed it! Now we just saved three if-statements per transparent pixel! Hurray! Hurray!
Quake allocates a minumum of 5.57 MB off the heap at startup. Actually it will allocate all the program memory available. Plus there's a few other chunks taken off the heap (for particles, etc). I think it needs close to a megabyte heap as well. The SH3 devices needed a larger heap for some reason (must need data aligned at larger intervals).

Dan East
Glad you got it working!

The only reason I expressed the equation using floats was so that you and others could understand it.  No one would be using floating point in an actual alpha blit routine.  

If it were me, I'd probably use premultiplied alpha in my source image and save the inverse alpha (here expressed with an 8-bit value) rather than the actual alpha, then the pixel calculation looks like:

dC = sC + (iA*dC)>>8

I'd measure the performance of this versus using a lookup table to perform the multiplication and shift.

I'm curious as to why you're using palettized sprites instead of storing them in the format native to the display?

It's good to see that you guys are in the optimization phase of the project.  You must be in the home stretch now.

I could quite easily change to premultiplied alpha. The formula I have is not very far from the one you have, but if I changed to premultiplied alpha I would have to remake all unit gfx preparations (ouch!) and john would have to rerender it all. Besides, I don't think all rendering packages out there support premultiplied alpha, so for the mod-ing community I think it is best to keep it the way it is.

Or maybe I could make it an option on each sprite...hmm...

-f
You could perform the premultiply and alpha inversion when the image is loaded.

Refractor · 04 Feb 2002, 09:28 UTC — Clamping... (bitwise help)
Hiya.

Sorry to bubble an old thread up to the top... :)

However, I thought I could help on this one.

Firstly, clamping a value to 0 is pretty straightforward on an ARM processor (once you know how :P ).

Assuming you're using a 32 bit integer, and you want to do:

Code:
if (value<0)
value = 0;


Then you can dump the compare entirely and have:

Code:
; input in r0
bic r0,r0,r0,ASR #31


Ta daaaaa. One cycle. 8)

The trick is the (wonderful) barrel shifter on the ARM. An arithmetic shift right will fill the bits shifted.. with the sign of the value.

So, if the value is positive, the instruction uses a value of 0 to clear the bits (i.e. it does nothing at all). If, however, the value is negative, then the BIC uses a value of 0xFFFFFFFF (-1) to clear the bits in the input... and thus clears everything... and thus = 0.



Clamping to a higher value is slightly different (unless I'm missing something). For clamping to 255 I'd probably do something like:

Code:
;r0 = value , r4 = temp
movs r4,r0,lsl #24
movcs r0,#255


Basically you shove it 24 to the left. If it's above 0xFF then a bit will go off the end and the carry flag will be set... and thus it should be clamped.

Clamping to other (non 2^n) values I'd probably do something like:

Code:
;r0 = value, r4 = temp

subs r4,r0,#max
movmi r0,#max


Which essentially says that:
Code:
if (value - max)<0
value = max;


Hope that helps, cheers,

Refractor.
Man, why doesn't the frigging ARM compiler support inline assembly?! :twisted:

Dan East
Not sure if this will help anyone, but I once read that saturation of a byte value can best be done using a small lut. Suppose you want to add to 8-bit values, with saturation, you could simply use a 512 entry table, fill it with a+b for the first 256 elements and 255 for the other elements... Really fast. :)

For color components, you'll probably just need 5 or 6 bits, so it's even better.

BTW, there's a cool color addition with saturation in EasyCE: It adds two colors after generating bitgaps (to prevent color components from effecting eachother during the addition); then it checks for oveflow, and only when there is an overflow, it fixes it. Reduces the 'ifs' to a single 'if'. Pretty efficient.

- Jacco.
Kzinti · 04 Feb 2002, 14:54 UTC — Adding bytes with saturation with LUT
I have implemented saturation using a 768 bytes LUT (I was clamping to both 0 and 255) and the results were actually slower then using this conditional:

Code:

int sum = a + b;
if ( sum >> 8 ) sum = ~(sum >> 24);
Have you tried a 768 element dword lut? The ARM is very bad at reading bytes. Just an idea.
refractor,

I'm wondering if it might be worth doing a test first to see if the value would need to be clamped. That might satisfy the majority of cases and could save an instruction.
Digby,

I'm not sure I follow you. :?

In the upper-limit clamping I wrote above, the comparison is performed by the MOVS/SUBS instruction, and the total instruction count is always 2 (whether the value is >=limit or <limit).

So far as I can tell, clamping to an arbitrary range isn't going to get much better than two cycles! :wink:

For the clamping to 0, it's always 1 instruction.

How are you going to save an instruction? (Remember that any conditional instructions that are NOT executed still take one cycle).

Sorry if I'm missing something,

Refractor.
refractor,

OK unless I'm missing something, it's going to take 3 instructions using the code you posted to make certain that a value is within an arbitrary range. Two cycles to handle the upper bound and one to handle clamping to zero.

I suppose if you know from the operations you're performing on the data, you would only need to clamp against one of the bounds. In that case, there's no win in testing up front.

One other thing to mention, in the case of clamping to an aribtrary upper limit (non-pow2), you're going to run into problems if the max value can't be described with 8-bits that are shifted by an arbitrary amount (shifter-operand). It could take another instruction to load the correct immediate data.
Hello again,

I still can't see how you're going to get it to be < 3 instructions for an arbitrary clamping?

With an additional compare you're still testing against only one of the values at the start. Even if you find the value is >MAX :

Code:
; Pretend R0 = #MAX + 1

CMP R0,#MAX
MOVGT R0,#MAX


You're still going to have to cope for the case where it *isn't* caught out-of-bounds and put the BIC instruction in there.

Really, as you said, you want to figure out what the routines before are doing and whether you need to clamp to both values... that's the only way you can save one (or two instructions).

Incidentally, I slipped up earlier:

Code:
SUBS R4,R0,#MAX ; if (value - max)>0
MOVPL R0,#MAX ; PL, not MI

(I prefer the CMP above anyway 'cos it doesn't use an extra register .. I thought I had a reason for using the SUB, but I can't think what it was).

As for the immediate constant, you're right, of course. If you were repeatedly testing against a "strange" value, it'd probably be best to
LDR rn,=0xdeadbeef
it into a temporary register (from a literal pool).

Cheers,

Refractor.
For an arbitrary clamping you probably won't get less than 3 instructions because you'll have to test against the upper bound and the lower bound explicitly. However, your BIC method won't work for an arbitrary clamping either, but it works nice for clamping against 0.

We were initially discussing clamping color components which are 8 bits. In this case I'm just saying that if you assume that the majority of the time the values won't need to be clamped, you can reduce the number of instructions by performing a test up front which would be 2 instructions. Yes, you'll have that additional overhead with values that require clamping but if most don't it will be a win. My point is that you might be able to do better if you know something about your data.