Linear scanning algorithm and region filling algorithm implemented by OpenGL

Source: Internet
Author: User

General Introduction

1, using linear scanning algorithm to draw a line segment, the line is composed of discrete points

2, using the region filling algorithm to draw the polygon region, the region is composed of discrete points

Development environment VS2012+OPENGL

Development platform Intel Core I5,intel HD Graphics Family

Design Ideas first, linear scanning algorithm 1. Numerical differential method (DDA)

The straight segment X1 = kx + B, which is known over the endpoint P0 (x0, y0), P1 (Y1, l:y), is easy to know that the line slope is: k = (y1-y0)/(x1-x0), (assuming x1≠x0).

We assume that |k|≤1, so that x each additional 1,y will increase the k, and ensure that x increments of 1,y per increment cannot be greater than 1; if |k| > 1, you should swap x and Y. Because K is a floating-point number, the algorithm needs to round the Y to int and round to the nearest position.

The DDA algorithm in each iteration of x, Y value is the value of the previous step plus an increment obtained, so it is an incremental algorithm. However, this method is intuitive but inefficient because each step requires a floating-point multiplication and a rounding operation.

2. Midpoint Drawing Line Method

In the case where the linear slope is 0~1 Direct, the current pixel is set to (x, y), then its next pixel is P1 (x+1,y) or P2 (x+1,y+1), if the midpoint m (p1) of P2 and px+1,y+0.5, Q is the intersection of the ideal line and the x+1 perpendicular, When Q is below M, P1 is the next pixel, otherwise the P2 is the next pixel point.

3. Bresenham algorithm

A set of virtual gridlines is constructed across rows of pixel centers. Calculates the intersection of the line and each vertical gridline in the order of the line from the start point to the end point, and then determines the pixel closest to this intersection in the column pixel. The trick of the algorithm is to use incremental calculation, so that for each column, just check the symbol of an error term, you can determine the pixel of the column.


, the linear equation is set to Yi+1=yi+k (Xi+1-xi) +k. Suppose that the column coordinate pixel has been determined as Xi, whose line coordinates are Yi. Then the next pixel's column coordinates are xi+1, and the row coordinates are either Yi or increment by 1 to yi+1. Whether 1 increases depends on the value of the error item D. The initial value of the error term D d0=0,x coordinates increment the slope value of the straight line by a 1,d of the values K, i.e. d=d+k. Once d≥1, subtract 1, so that D is guaranteed to be between 0 and 1. When d≥0.5, the straight and perpendicular x=xi+1 intersections are closest to the upper right pixel (xi+1,yi+1) of the current pixel (xi,yi) and, when d<0.5, closer to the left pixel (xi+1,yi). For the convenience of calculation, the initial value of E=d-0.5,e is 0.5, and the increment is K. When E≥0, take the upper right Pixel (xi+1,yi+1) of the current pixel (xi,yi), and when E<0, take (xi,yi) the Pixel (xi+1,yi).

second, the region filling algorithm 1. Recursive algorithm

Starts from the specified seed point, searches in all directions, processes pixels by pixel, until a boundary is encountered, and the various seed-filling algorithms differ only in how colors and boundaries are handled.

2. Scan line Algorithm

The basic process of the scan line seed filling algorithm is as follows: When a given seed point (x, y) is first filled to the left and right in two directions, the seed point is located on the scan line in a section of a given region, and note the range of this section [Xleft, Xright], and then determine the link to this section of the upper, The section of the next two scan lines in a given area, and then save it in turn. Repeat this process until the fill is finished.

The scan line seed fill algorithm can be implemented in the following four steps:

(1) Initialize an empty stack to hold the seed point, and the seed point (x, y) into the stack;

(2) Determine whether the stack is empty, if the stack is empty to end the algorithm, otherwise remove the top element of the stack as the current scan line seed point (x, y), Y is the current scan line;

(3) from the seed point (x, y), fill in the left and right two directions of the current scan line until the boundary. The coordinates of the left and right endpoints of each marked section are Xleft and xright;

(4) respectively check the y-1 and y + 12 scan lines adjacent to the current scan line in the interval [xleft,xright] pixels, starting from xleft to xright direction search, if there are non-boundary and unfilled pixels, then find these adjacent pixels in the rightmost one, and press it as a seed point into the stack, and then return to step (2);

Third, the implementation of the algorithm



Summary and learning sentiment

In the study of the linear scanning algorithm, the beginning always can not draw out, and later found that the sentence Glbegin (gl_points), less a s, no s will only draw a point, the details are very important.

Learning region filling algorithm, the basic idea is to start with a point, and constantly explore around, if in this area, fill the color, if you encounter the boundary to stop. The scanning line algorithm is also to draw a line at a certain point and fill in the line segments within the area.

We are like a selected point, everything around us is unknown to the black, only to continue to explore, we know where the boundary, may not have boundaries, perhaps the border is a bigger new world ... Poof, I think more.

Source code scan Line main algorithm
void K1 ()   //0<k<1  {glclear (gl_color_buffer_bit);     glcolor3f (0.0,0.0,0.0);     Glbegin (gl_points);     Glint x1=0,y1=0,x2=400,y2=200;     Glint X=x1,y=y1;     Glint dx=x2-x1,dy=y2-y1,dt=2* (DY-DX), Ds=2*dy;     Glint D=2*DY-DX;     Glvertex2i (x, y);     while (x<x2)  {    x + +;    if (d<0)    d=d+ds;    else    {     y++;     D=d+dt;    }  Glvertex2i (x, y);  }      Glend ();  Glflush ();  }

Area fill
#include "gl/glut.h" #include "windows.h" const int pointnum=7;  Polygon points./****** defines the structure used for the active side table aet and the new edge table net***********************************/typedef struct XET {float x;  float Dx,ymax; Xet* Next;  }aet,net;/****** defines the point structure of the point******************************************************/struct, dot {float x; Float y; } polypoint[pointnum]={250,50,550,150,550,400,250,250,100,350,100,100,120,30};//polygon vertex void PolyScan () {/****** Calculates the y-coordinate of the highest point (scanned to this end) ****************************************/int maxy=0; int i;  for (i=0;i<pointnum;i++) if (polypoint[i].y>maxy) maxy=polypoint[i].y;  /******* Initialize AET table ***********************************************************/aet *paet=new aet;  paet->next=null;  /****** Initialize NET table ************************************************************/net *pnet[1024];   for (i=0;i<=maxy;i++) {pnet[i]=new NET;  pnet[i]->next=null;        } glclear (Gl_color_buffer_bit);    The assigned window is displayed.             glcolor3f (0.0,0.0,0.0); Sets the color of the line Red Glbegin (gl_points);/****** scans andCreate net Table *********************************************************/for (i=0;i<=maxy;i++) {for (int j=0;j< pointnum;j++) if (polypoint[j].y==i) {//A point follows a previous point to form a line segment, followed by a point also forming a segment if (polypoint[(j-1+pointnum)%pointnum].y&      GT;POLYPOINT[J].Y) {net *p=new net;      p->x=polypoint[j].x;      p->ymax=polypoint[(j-1+pointnum)%pointnum].y; P->dx= (polypoint[(j-1+pointnum)%pointnum].x-polypoint[j].x)/(polypoint[(J-1+pointnum)%POINTNUM].y-polypoint      [J].Y];      p->next=pnet[i]->next;           pnet[i]->next=p;            } if (polypoint[(j+1+pointnum)%pointnum].y>polypoint[j].y) {NET *p=new net;      p->x=polypoint[j].x;      p->ymax=polypoint[(j+1+pointnum)%pointnum].y; P->dx= (polypoint[(j+1+pointnum)%pointnum].x-polypoint[j].x)/(polypoint[(J+1+pointnum)%POINTNUM].y-polypoint      [J].Y];      p->next=pnet[i]->next;     pnet[i]->next=p; }}}/****** Create and update the active edge table aet**************************************************/for (i=0;i<=maxy;i++) {//Calculate new intersection x, update aet NET *p=paet->next;    while (p) {p->x=p->x + p->dx;   p=p->next;   }//Updated after the new AET sort *************************************************************///broken table sorting, no longer open space AET *tq=paet;   p=paet->next;   tq->next=null;    while (p) {while (Tq->next && p->x >= tq->next->x) tq=tq->next;    NET *s=p->next;    p->next=tq->next;    tq->next=p;    P=s;   Tq=paet;   }//(improved algorithm) first removes ymax==i node ****************************************/aet *q=paet from the AET table;   p=q->next;     while (p) {if (p->ymax==i) {q->next=p->next;     Delete p;    p=q->next;     } else{q=q->next;    p=q->next;   }}//Add the new point in net to the AET and use the insertion method to increment by x value **********************************/p=pnet[i]->next;   Q=paet;    while (p) {while (Q->next && p->x >= q->next->x) q=q->next;    NET *s=p->next;    p->next=q->next;    q->next=p; P=s;   Q=paet;   }/****** pairing fill Color ***************************************************************/p=paet->next; while (P && p->next) {for (float j=p->x;j<=p->next->x;j++) glvertex2i (static_cast<int&gt    ;(j), I); p=p->next->next;//consider the endpoint condition}} glend (); Glflush (); }void init (void) {Glclearcolor (1.0,1.0,1.0,0.0);//The background color of the window is set to white Glmatrixmode (gl_projection); Gluortho2d ( 0.0,600.0,0.0,450.0);}                void Main (int argc,char* argv) {glutinit (&AMP;ARGC,&AMP;ARGV);    I initialize the GLUT. Glutinitdisplaymode (Glut_single |    GLUT_RGB);        Set display mode: Single cache and use RGB model glutinitwindowposition (50,100);        Set the top and left positions of the window glutinitwindowsize (400,300);    Sets the height and width of the window Glutcreatewindow ("An Example OpenGL program");                                Create a display window init ();        Call initialization process Glutdisplayfunc (Polyscan);    The definition of the graph is passed to me window.                        Glutmainloop (); Show all the graphics and wait}


Linear scanning algorithm and region filling algorithm implemented by OpenGL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.