#include <windows.h>
#include <malloc.h>
#include <glut.h>
#include<iostream>
using namespace std;
typedef struct point
{ int x;
int y;
struct point *next;
}cpoint;
typedef struct
{
int n;//顶点数
cpoint *cp;
}polygon;
polygon pol;
//修正算法
void IntegerBresenham(int x0,int y0,int x1, int y1)
{
float x,y,dx,dy,e;
float k;
dx = x1-x0,dy = y1-y0,e=-dx;
x=x0; y=y0;
k=dy/dx;
//对dx<0&&0<k<6666(正无穷)的修正
if(0<=k&&k<6666)
{
if(dx<0)
{
dx=x0-x1,dy=y0-y1,e=-dx;
x=x1; y=y1;
}
for (int i=0; i<=dx; i++)
{
glVertex2f(x,y);
x++; e=e+2*dy;
if (e>=0)
{
y++; e=e-2*dx;
}
}
}
if(k<0&&k>-6666)//对k<0的修正
{
if(dx>0)
{
e=-0.5;
for (int i=0; i<=dx; i++)
{
glVertex2f(x,y);
x++; e=e-2*dy;
if (e>=0)
{
y--; e=e+2*dx;
}
}
}
else
{
for (int i=0; i<=-dx; i++)
{
glVertex2f(x,y);
x--; e=e+2*dy;
if (e>=0)
{
y++; e=e-2*dx;
}
}
}
}
//对x0=x1即dx=0情况的修正
if(dx==0)
{
if(dy<0)//y1<y0
{
for (int i=0; i<=-dy; i++)
{
glVertex2f(x,y);
y--;
}
}
if(dy>0)//y1<y0
{
for (int i=0; i<=dy; i++)
{
glVertex2f(x,y);
y++;
}
}
glVertex2f(x,y);//同一点时
}
}
void drawpolygon()
{
int x0,y0,x1,y1;
cpoint *h=pol.cp;
cpoint *s;
do{
x0=h->x;
y0=h->y;
s=h->next;
x1=s->x;
y1=s->y;
IntegerBresenham(x0,y0,x1,y1);
h=s;
if(s->next==NULL)
{
s=pol.cp;
x0=s->x;
y0=s->y;
x1=h->x;
y1=h->y;
IntegerBresenham(x0,y0,x1,y1);
break;
}
}while(true);
}
void renderScene()
{
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,400,0,400,0,400);
glPointSize(3.0);
glBegin(GL_POINTS);
glColor3f(0.0,0.0,1.0);
drawpolygon();
glEnd();
glFlush();
}
void input(cpoint *&h)
{
cpoint *L;
cpoint *s;
L=h;
cout<<"x0=";
cin>>h->x;
cout<<"y0=";
cin>>h->y;
int j=--pol.n;
int i=1;
while(true)
{
if(j!=0)
{
s=(cpoint *)malloc(sizeof(cpoint));
h->next=s;
h=s;
cout<<"x"<<i<<"=";
cin>>h->x;
cout<<"y"<<i<<"=";
cin>>h->y;
j--;
i++;
}
else
{
h->next=NULL;
break;
}
}
}
void init(cpoint *&h)
{
h=(cpoint *)malloc(sizeof(cpoint));
h->next=NULL;
}
void main(int argc, char **argv)
{
//初始化
init(pol.cp);
char j;
cout<<"请输入顶点数\nn=";
cin>>pol.n;
cpoint *h=pol.cp;
cout<<"请输入各顶点\n";
input(h);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(320,320);
glutCreateWindow("Bresenham绘制多边形");
glutDisplayFunc(renderScene);
glutMainLoop();
}