PocketMatrix forums

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

Polygon Drawing Algorithm

What are the fastest algorithms for drawing solid, filled polygons? Thanks.

Dan East
Same thing for filled triangles.

Dan East
ehhh? aren't you repeating your question?:)
anyway probably the fastest way (or at least a very fast way which is very often used) is to:
1.sort your verticles by y (from low to high)
2.calculate deltas for left/right edges
3.starting from x1,y1 (sorted x1,y1 so it's the topmost verticle) you're going down your triangle one by line drawing pixels between left and right edge of your triangle (you don't precalculate those values into an array and draw from there as some ppls do, it's easier to implement but slower)

that's a very basic explanation, you can find a bunch of tutorials about it on www.gamedev.net for ex. It used to be a very often covered topic when software rendering was used a lot. If you want I can send you over some stuff (my poly filler and gourand shader and phantom's affine tmapper , all work with 320 screen width. don't remember about phantom's but my use 24:8 fixedpoint math (probably will go to 22:10 like phantom uses in his matrix stuff soon))
so if you have some questions feel free to ask, if my knowledge won't be enought Jacco will surelly know the answer:)
Dan,

This is covered in Graphics Gems and by Abrash in his Zen of Graphics Programming and reprinted in his later Black Book of Graphics Programming.  The text of Black Book is online in a number of places - here's one of them:

http://www.ddj.com/documents/s=865/ddj0165f/

Have a look at chapters 38 and 39.


Mirek,
Those edge arrays can come in handy if you're rasterizing triangular strips and fans.

Digby:but is it faster that way? I doubt it, as apart from calculating the deltas you're doing just an add to left and right array edge to get your new position. a perspective correct tmapper might be a problem here, but I guess it's still faster then loading all data from memory(and you have got to precalculate this edge anyway while it won't be used more then twice, so the basic problem is what's faster, calculating 2 times edge at runtime or precalculating an edge every frame it's used and read it 2 times from array at runtime - in a perfect case for your method)
as far as I have heard from your chats ARM cpu has got (at least)16 registers, so it should allow you to keep all data in them without using cache or anything, which fits "my" method very well.
You only cache the values for the edge that is shared.  You don't walk all the edges, saving all the values in an array, then go back and walk the array again to perform the fill.  The way it works is that you write to the array as you're stepping down the edge and performing the fill.  The next triangle can read from that array for the shared edge, and if it shares another edge with the next triangle, it caches the values as it steps down that edge.  You toggle the edge buffers between triangles similar to a flipping chain of frame buffers.

Is it faster?  To tell you the truth I don't know because I haven't implemented it both ways and measured the results. I'm doing perspective correct texture mapping and that requires a division operation for every pixel along that edge.  You did know that the ARM has no divide instruction, right?  One thing nice about the ARM though is those load/store multiple register instructions.  In one instruction you can read/write all the values saved in that array to/from registers.

Speaking of the ARM... You can use 14 of the 16 ARM registers.  The other two are the stack pointer and the program counter.  That might be enough registers for interpolating r, g, b but not for alpha, z, u, and v.  Unless I've missed something you'll need 2 additional values per interpolated value (for stepping in x and y).  You'll also need a pointer to the render target buffer, a pointer to the texture map buffer, and a register to pack r, g, and b into a 565 value (or to pack two pixels into a DWORD so you don't pay a write penalty), and throw in an extra register for performing alpha blending.  How many registers is that?  I've lost count.

digby:"your" method won't be faster and it needs a lot of tweaking (preparing model etc) to work pretty well(precalculating to an array is surelly slower, so if you need to do it without a shared edge you're wasteing a lot of time)
anyway why don't you use quake-like trick to calculate perspective correct tmapping every 8/16-th pixel

You still don't get it.  At a minimum, reading a value from the array is going to be much faster than performing the divide for each pixel along the edge.  I've also shown that you won't be able to fit all of the values necessary to walk an edge in the registers.  So you're saying that even though I have to read/write some of these to memory as you fill the triangle,  throwing away the values and having to recalculate them again is going to be faster?  I don't understand this logic.  Perhaps you can clear it up for me?

You would not do any of this edge cacheing if you weren't drawing a triangular strip of fan.  That would be silly.

I don't do the divide for every pixel along the span.  I skip by a value that is stored in the Registry (usually 8 pixels).

The method needs no tweaking however the 3D models do.  Modelling software can stripify meshes, there are also utilities (free) to do this.  It's not like this is some time-consuming processes to provide strips.  The artist just runs his software through the stripifier and they are done.

Don't use edge arrays, thats my experience...

Example follows... (not org by me)

Any optimalization hints to this code would be greatly appreciated... (especially FLAT_HLine)

Code:

#define MIN(a,b) ((a<b)?(a):(b))
#define MAX(a,b) ((a>b)?(a):(b))
#define MaxPoint(a,b) ((a.y > b.y) ? a : b)
#define MinPoint(a,b) ((b.y > a.y) ? a : b)
#define MaxPoint3(a,b,c) MaxPoint(MaxPoint(a,b),MaxPoint(b,c))
#define MidPoint3(a,b,c) MaxPoint(MinPoint(a,b),MinPoint(a,c))
#define MinPoint3(a,b,c) MinPoint(MinPoint(a,b),MinPoint(b,c))

typedef struct {
     short r,g,b;
} _Color;

typedef struct {
     short x, y;
     _Color Color;
} _2D;

/**
** Flat Shader
*/
void polygonFlat(_2D p1,_2D p2,_2D p3) {
     PIXEL* buffer=getbuffer();
     _2D p1d,p2d,p3d;
     int xd1,yd1,xd2,yd2,i;
     int Lx,Rx;
     p1d = MinPoint3(p1,p2,p3);
     p2d = MidPoint3(p2,p3,p1);
     p3d = MaxPoint3(p3,p1,p2);

     if(p2.y<p1.y) {
           p1d=MinPoint3(p2,p1,p3);
           p2d=MidPoint3(p1,p3,p2);
     }

     xd1=p2d.x-p1d.x;
     yd1=p2d.y-p1d.y;
     xd2=p3d.x-p1d.x;
     yd2=p3d.y-p1d.y;

     if(yd1)
           for(i=p1d.y;i<=p2d.y;i++) {
                 Lx=p1d.x+((i-p1d.y)*xd1)/yd1;
                 Rx=p1d.x+((i-p1d.y)*xd2)/yd2;
                 if(Lx!=Rx)
                       FLAT_HLine(buffer,MIN(Lx,Rx),MAX(Lx,Rx),i,p1.Color.r,p1.Color.g,p1.Color.b);
           }
     xd1=p3d.x-p2d.x;
     yd1=p3d.y-p2d.y;

     if(yd1)
           for(i=p2d.y;i<=p3d.y;i++) {
                 Lx=p1d.x+((i-p1d.y)*xd2)/yd2;
                 Rx=p2d.x+((i-p2d.y)*xd1)/yd1;
                 if(Lx!=Rx)
                       FLAT_HLine(buffer,MIN(Lx,Rx),MAX(Lx,Rx),i,p1.Color.r,p1.Color.g,p1.Color.b);
           }
}

void FLAT_HLine(PIXEL* buffer,int x1,int x2,int y,int r,int g,int b) {
     int x;
     int rgb=(r<<11)+(g<<5)+b;      
     buffer+=(x1+y*240);
     for(x=x1;x<=x2;x++)
           *buffer++=rgb;
}
simonjacobs · 09 Jan 2002, 16:33 UTC
That code isnt so bad on a desktop processor, but for a pocket pc it is worth knowing that the ARM does not have a divide instruction.

Any c code of the form a = b / c; is going to be expensive. Obviously dividing by powers of 2 can be optimised to a shift which is fast, but general division is slow.
Maybe I didn't make this clear.  I would only use the edge array on the edge of a triangle that would be shared with the edge of the next triangle in a strip or fan.  If I were rendering triangles that were not submitted as strips or fans I would be using the same method that Mirek described above.  Caching something that would never be reused is a bit foolish.  Caching something that would take longer to read/write to the cache than to recompute would also be foolish.  

I doubt that I would use this method in drawing 2D solid-color filled triangles because the calculations made each step along the edge are miniscule since you aren't needing to interpolate values across the face of the polygon.

I can't see that one can code around the use of divs when doing a polygon filler or drawing lines for that matter. You'll always have to calc the deltas.

I know it's not optimal in the code above, because the delta is calculated for each line instead of just doing it once and then adding up each side. (I just realized that. What a dumb ass I have been...) Well.. thanks for opening my eyes... Last modification: paulrene - 01/09/02 at 15:32:09
paulrene: exactly, and if you are drawing triangle strips or fans, you can reuse that computed delta for the next triangle, thats what digby is trying to say

(i think, just back from the pub so don't blame me :-)
Here are some of my experiences with filling polygons:

- The triangle method is nice (drawing it in two halves without outline tables), but it doesn't allow drawing n-sided polygons. N-sided polygons are useful when you start clipping against a frustum, since that will typically change a triangle to a n-sided poly. You could triangulate that easily, but having a special case for n-sided polies is easier.

- If you draw a cube using triangles, you'll get bad distortion because of the lack of perspective texture mapping. This effect is far less if you render quads and calculate delta's for each scanline. Rendering a quad that way is more expensive than rendering tri's with constant slopes, but you save one edge (the diagonal), you can draw longer spans (twice as long on average) and the distortion is less. I like this method. :)

- Perspective correction is a disaster on the ARM. You can't do the u/z and v/z calculus using floating point, wich means you can't really use reciprocals (bad precision), and you can't do those divides in parallel with integer stuff (like you could do on the Pentium series). Perspective correction is going to be very slow. It might be better to use face subdivision like most engines do on the Playstation 1.

- The code at the start of this thread doesn't have subpixel accuracy. That's going to be VERY ugly when the triangle moves slowly.

Well I intend to spend some time tonight on a polygon rasterizer, I'll make sure it's well documented and fast. I have another coding night tomorrow, so you should have something useful before the weekend.

Later on I'll add bilinear filtering. As opposed to perspective correction, this is very well possible on the StrongARM (and MIPS/SH3).

- Jacco.
PDAFantast · 30 Jan 2002, 05:49 UTC — Optimized GBA code.
No need to calculate a div every pixel.. total waste of cycles.

I'm using this highly optimized code in my 3D engine for GameBoy Advance. Actually, nowadays I'm using an ARM assembly variant of this. Note the fixed point calculations. fixdiv and fixmul are assembly too.


Code:

void DrawTriangle(Point p1,Point p2,Point p3, unsigned long c)
{
Fixed dx1, dx2, i;
Fixed Lx,Rx;

if(p2.y < p1.y){
Lx = p1.x;
Rx = p1.y;

p1.x = p2.x;
p1.y = p2.y;

p2.x = Lx;
p2.y = Rx;
}


if(p3.y < p2.y){
Lx = p2.x;
Rx = p2.y;

p2.x = p3.x;
p2.y = p3.y;

p3.x = Lx;
p3.y = Rx;

}

if(p2.y < p1.y){
Lx = p1.x;
Rx = p1.y;

p1.x = p2.x;
p1.y = p2.y;

p2.x = Lx;
p2.y = Rx;
}


dx1 = fixdiv( (p2.x - p1.x),(p2.y - p1.y) );
dx2 = fixdiv( (p3.x - p1.x),(p3.y - p1.y) );

Lx = p1.x;
Rx = p1.x;

if(!dx1)
Lx = p2.x;


for(i=p1.y; i<=p2.y; i+=FIXED_ONE)
{
HLine2(
(MIN(Lx,Rx)+FIXED_HALF)>>16,
(MAX(Lx,Rx)+FIXED_HALF)>>16,
i,
c);

Lx += dx1;
Rx += dx2;
}

Lx -= dx1;
dx1 = fixdiv( (p3.x - p2.x),(p3.y - p2.y) );
Lx += dx1;


for(i = p2.y + FIXED_ONE; i <= p3.y; i+=FIXED_ONE)
{

HLine2(
(MIN(Lx,Rx)+FIXED_HALF)>>16,
(MAX(Lx,Rx)+FIXED_HALF)>>16,
i,
c);

Lx += dx1;
Rx += dx2;

}
}

PDAFantast · 30 Jan 2002, 05:53 UTC — fixdiv
My fixdiv routine takes only 12 cycles, if anyone's interested. Works on 16:16 fixed numbers.
The divide is necessary for perspective correct interpolation across the face of a polygon (which you aren't doing).

Sure go ahead and post your fixdiv code. If it can perform an integer divide in 12 cycles on the ARM, you've got the ARM guys beat by quite a bit.
I would love to see that too. :) The perspective correction is not the only place in a texture mapper where divs are needed.
simonjacobs · 30 Jan 2002, 11:01 UTC
You could use a lookup table for divides :)
Ehm yes, I always do that on my PC, but on the iPaq, a lookup table for all 32bit numbers is slightly too large. ;)
simonjacobs · 30 Jan 2002, 15:38 UTC
I use a table for divides up to 256, I get a lot of them in my rendering code.

I also wonder if you can use a 256-entry lookup table to simulate a full 16.16 / 16.16 operation.

1/(a+b) = 1/[a(1+b/a)] = 1/a * 1/(1+b/a)

Say you are dividing by 534 = 256*2 + 22 and set a=22. Then you have:

x/534 = x/22 + x/(1+512/22)

or something. That might be rubbish, but it might work :)

I'm sure you should be able to get really fast 16.16 division with just a 256 entry lookup table and multiplications.
Digby,

I don't need perspective division in THIS routine, since this is a 2D flatshaded triangle renderer, not a texture renderer. The vertices are already transformed, perspective projected and culled.

What I was referring to was that you don't need a DIV in every iteration while you trace the edges of the triangle. You only need to do it ONCE to get the slope and then you just iterate and add to the left respective right edges.

The fixdiv handles fixed point division in the format 16:16. Will post it shortly.

Thanks,
PDAFantast · 30 Jan 2002, 21:40 UTC — fixdiv and fixmul.
Ok here it is: it uses a 4096-entry "1/x" shifted 0:32 fixed point table, totaling to 16Kbytes. I'm pasting the first few rows for your reference, if you want the whole table mail me at georgea@kodeness.com.

The code uses the properties of symmetry of fixed point numbers and it uses the most significant 12 bits.

Here are the first 64 entries:

Code:

onedivtab

DCD 0x00000000,0x00000000,0x80000000,0x55555555,0x40000000,0x33333333,0x2AAAAAAA,0x24924924
DCD 0x20000000,0x1C71C71C,0x19999999,0x1745D174,0x15555555,0x13B13B13,0x12492492,0x11111111
DCD 0x10000000,0x0F0F0F0F,0x0E38E38E,0x0D79435E,0x0CCCCCCC,0x0C30C30C,0x0BA2E8BA,0x0B21642C
DCD 0x0AAAAAAA,0x0A3D70A3,0x09D89D89,0x097B425E,0x09249249,0x08D3DCB0,0x08888888,0x08421084
DCD 0x08000000,0x07C1F07C,0x07878787,0x07507507,0x071C71C7,0x06EB3E45,0x06BCA1AF,0x06906906
DCD 0x06666666,0x063E7063,0x06186186,0x05F417D0,0x05D1745D,0x05B05B05,0x0590B216,0x0572620A
DCD 0x05555555,0x05397829,0x051EB851,0x05050505,0x04EC4EC4,0x04D4873E,0x04BDA12F,0x04A7904A
DCD 0x04924924,0x047DC11F,0x0469EE58,0x0456C797,0x04444444,0x04325C53,0x04210842,0x04104104

And so forth, up to 4096 entries.


Here is the code itself. It's written in 32 bit ARM assembler and it's designed to be called from 16-bit Thumb code on the GBA. Since ARMThumb is not used on the iPAQ, you might want to comment out the "bx lr" instruction at the end and replace it with "mov pc,lr".

The algorithm takes from lowest 12 up to worst case 18 cycles. The error diffusion is less than 0.45 %.

Code:

; r0 = dividend r1 = divisor
; works on 16:16 fixed point
fixdiv
stmfd sp!,{r2-r4} ; push some registers

;; r4 = signflag
mov r4,#0
tst r1,#0x80000000 ; see if neg bit is set
subne r1,r4,r1 ; negate r1 if r1 is negative
subeq r4,r4,#1 ; set r4 to -1 if unsigned else 0 if signed

ldr r2,=0xFFF00000
mov r3,#0
tst r1,r2
bne fixdiv_highbitvalue
tst r1,#0x0000F000
movne r3,#4
tst r1,#0x000F0000
movne r3,#8
b fixdiv_knowbits
fixdiv_highbitvalue
mov r3,#12
tst r1,#0x0F000000
movne r3,#16
tst r1,#0xF0000000
movne r3,#20

fixdiv_knowbits
; r3 = divisior rightshifter

mov r1,r1,lsr r3

ldr r2,=onedivtab
ldr r2,[r2,r1,lsl #2]

mov r2,r2,lsr r3

smull r0,r1,r2,r0
mov r0,r0,lsr #16 ; shift right of low
add r0,r0,r1,lsl #16 ; shift left of high

tst r4,r4
subeq r0,r4,r0 ; negate result if r4=0 (ie signed number)

ldmfd sp!,{r2-r4} ; pop some registers
bx lr

; mov pc,lr ; this is for return to a 32bit ARM code.



Enjoy,
Oh I completely agree if you are working only in screen space you don't need to perform the divide along the edge.

You do have to do this if you are having to move from screen space to camera space and that is what I was referring to in my original post about caching the edge values so you don't have to do the divide twice.

Since I've had time to think about it, it's not the perf-win that I had originally imagined because the rasterizer doesn't draw the same pixel twice along abutting edges. The top-left fill convention guarantees that the right edge won't be drawn twice, hence there's not much being computed for one triangle that can be cached. I need to think about it some more before I write this off, but it's looking that way for now.
Humm... ok.. cool. sounds reasonable.

The fixdiv is above.
Hello.

I've "optimised" the code at an instruction-level (Friday lunch-times *are* useful for something! :wink: ).

Please note that it has *NOT* been tested 'cos I don't have an ARM machine to hand (or palm) right now. I don't think I've made any silly mistakes or assumptions... but I may have done.

I've not looked at the algorithm either - this is strictly moving code around to make it faster (or "more readable" in the case of the top-bit TST).

I've only saved a couple of cycles in the main part (better than nothing!), except for if you're calling it using ARM procedure call standard (or the MS embedded Visual C++ hybrid), in which case you can remove the stack operations and claw back an extra 6 cycles on top!

Code:
; "Optimised" (generally towards a StrongARM) by Refractor

; r0 = dividend r1 = divisor
; works on 16:16 fixed point
fixdiv

stmfd sp!,{r2-r3,r12} ; push some registers

;R using the ARM procedure call standard, r2 and r3 (maybe r12) don't need to be saved in the above
;R (or unstacked below)

;R if using this from the embedded Visual C++, R12 is defined as a temporary register, (this may be true in the ARM PCS too... I can't remember)...
;R if so we can use R12 and not stack R4 (or R12)... then we don't need to use the stack *at all*

mov r12,r1 ;R we can just store the number rather than the 0/-1 flag

cmp r1,#0 ;R
rsbmi r1,r1,#0 ;R if it's negative, negate it ... one cycle saved


ldr r2,=0xFFF00000
tst r1,r2
bne fixdiv_highbitvalue

mov r3,#0 ; moved after the comparison .. one cycle saved for the highbitvalue

tst r1,#0x0000F000
movne r3,#4
tst r1,#0x000F0000
movne r3,#8
b fixdiv_knowbits
fixdiv_highbitvalue
mov r3,#12
tst r1,#0x0F000000
movne r3,#16
tst r1,#0xF0000000
movne r3,#20

fixdiv_knowbits
; r3 = divisor rightshifter

mov r1,r1,lsr r3

ldr r2,=onedivtab
ldr r2,[r2,r1,lsl #2]

mov r2,r2,lsr r3

smull r0,r1,r2,r0
cmp r12,#0 ;R doing this here saves us one cycle (StrongARM, maybe others) because we have to wait
;R for the result of the SMULL for 1-3 cycles anyway.
;R So, anything that doesn't use the result can go in the wait period.

mov r0,r0,lsr #16 ; shift right of low
add r0,r0,r1,lsl #16 ; shift left of high

; removed tst r4,r4
; removed subeq r0,r4,r0 ; negate result if r12=0 (ie signed number)

rsbmi r0,r0,#0 ;R I *presume* that it was supposed to re-negate the number we negated earlier

ldmfd sp!,{r2-r3, r12} ; pop
;R some/all registers (may not be necessary, see above)

; targetting at a non-thumb processor
; bx lr

mov pc,lr ; this is for return to a 32bit ARM code.



Cheers, happy coding,

Refractor[/code]
Wanna save another instruction? You can "pop" from the stack directly into the PC.
Cool stuff Refractor...

I liked the rsbmi replacement a lot, why haven't I thought of that one... :roll:

Unfortunately on GBA r12 is not temporary and I can't use it. And it's called both from Thumb and ARM assembly code.


Digby,
I think, you're not saving a a cycle at all, :( since you got
to save lr on stack to be able to pop it up on exit, so the memory write/reads takes out the gain in exterminating mov pc,lr.

I might be wrong, but the ARM7TDMI fetching timing of the GBA won't give you this advantage.
You're right, it's one less instruction but probably not a perf win. The stack *should* be in the cache at that point though so it's probably not too hideous.