how to rasterize rotated rectangle (in 2d by setpixel)

纵然是瞬间 提交于 2019-11-26 01:09:27

问题


I have got a four 2d vertices A B C D of rotated rectangle, I need to rasterize/draw it (efficiently) in pixelbufer with setpixel(x,y,color)

how to do it?

i was trying with some code like

    // convertilg a b c d do up down left right, 
    // calculating some dx_left dx_right on y--
    // etc (frustrating on special cases when there are 2 up_y vertices in same line etc)


    for(;;)
    {

     drawhorizontalline(y, xstart, xend, color);

     if(y==downy) break;

     y--;
     xstart+=dxstart;
     xend+=dxend;

     if(y==lefty)  dxstart = dxright;
     if(y==righty) dxend = dxleft;

     }

but it is most frustrating (terribly bug prone and most frustrating) i am really tired of debuging this all day yesterday and i need to find maybe some working code rather than to try to debug this


回答1:


To fill your rectangle handle it as closed convex polygon (almost the same as triangle filling)

  1. order your points to match winding rule

    so there are lines AB BC CD DA or reverse

  2. create left and right buffer

    address is y-coordinate, its an array of x-positions and if needed also array of color,texture coordinates,.... for starters:

    • int buf_x0[ys],buf_x1[ys];

    where ys is screen y-resolution

  3. implement any draw line algorithm

    but instead of draw to screen just store x coordinate of pixel to buffer.

    • instead of: setpixel(x,y,color); do: buf_x?[y]=x;.

    Which buffer is the destination depends on the line Y direction

    • if dy<0 then fill buff_x0
    • if dy>0 then fill buff_x1
    • if dy==0 then buf_x0[y]=min(x) and buf_x1[y]=max(x)
  4. apply this line algorithm to all border lines of polygon (AB,BC,CD,DA)

    after this the buffers contains start and end x-positions of your horizontal lines

  5. fill the rectangle on screen

        for (y=min(Ay,By,Cy,Dy);y<=max(Ay,By,Cy,Dy);y++)
         draw_horizontal_line(y,buf_x0[y],buf_x1[y],color);
    

Image for clarity (taken from my lectures on low level computer graphics)

image description:

  • vertical rectangles represents the border buffers buf_x0[],buf_x1[]
  • clockwise winding rule ensures the destination buffer. If its coded properly than buf_x0[y] <= buf_x1[y] so draw of horizontal line colapses to single for loop

Also here simple C++ example of mine for this



来源:https://stackoverflow.com/questions/10061146/how-to-rasterize-rotated-rectangle-in-2d-by-setpixel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!