要求:分别利用DDA算法、中点Bresenham算法和改进的Bresenham算法扫描转换直线段P1P2,其中P1为(0, 0), P2为(8, 6)。
#include <iostream>
#include "stdio.h"
#include <stdlib.h>
#include <cmath>
#include <gl/glut.h>
using namespace std;
void Inital(void)
{
glClearColor(1.0f,1.0f,1.0f,1.0f);
glMatrixMode(GL_PROJECTION);
glColor3f(0.0f,0.0f,0.0f);
gluOrtho2D(0.0,200.0,0.0,150.0);
}
void DDALine(int x0,int y0,int x1,int y1)
{
int dx,dy,esp;
float x,y,xIncre,yIncre;
glPointSize(1.0f);
dx = x1 - x0;
dy = y1 - y0;
x = x0;
y = y0;
esp = (abs(dx) < abs(dy)) ? abs(dx) : abs(dy);
xIncre = (float)dx / (float)esp;
yIncre = (float)dy / (float)esp;
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(1.0f);
glBegin(GL_POINTS);
glVertex2i((int)(x+0.5),(int)(y+0.5));
glEnd();
glFlush();
for(int k = 0;k < esp;k++)
{
glBegin(GL_POINTS);
glVertex2i((int)(x+0.5),(int)(y+0.5));
glEnd();
x += xIncre;
y += yIncre;
glFlush();
}
}
void BresenhamLine(int x0,int y0,int x1,int y1)
{
glPointSize(1.0f);
int dx = 0,dy = 0,d = 0;
int x,y;
x = x0,y = y0;
dx = abs(x1 - x0);
dy = abs(y1 - y0);
d = dx - 2 * dy;
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
while (x < x1)
{
if(d < 0)
{
x += 1;
y += 1;
d += 2 * (dx - dy);
}
if(d > 0)
{
x += 1;
d -= 2 * dy;
}
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
}
}
void Bresenham(int x0,int y0,int x1,int y1)
{
glPointSize(1.0f);
int x = x0;
int y = y0;
int dx = x1 - x0;
int dy = y1 - y0;
int e = -dx;
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
while(x <= x1)
{
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();
x++;
e += 2 * dy;
if (e > 0)
{
y++;
e -= 2 * dx;
}
}
}
void Display(void)
{
DDALine(0,0,8,6);
BresenhamLine(0,0,8,6);
Bresenham(0,0,8,6);
}
int main(int argc,char* argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,400);
glutInitWindowPosition(100,120);
glutCreateWindow("line");
Inital();
glutDisplayFunc(Display);
glutMainLoop();
return 0;
}