直线生成算法的实现:分别利用DDA算法、中点Bresenham算法和改进的Bresenham算法扫描转换直线段P1P2

直线生成算法的实现:分别利用DDA算法、中点Bresenham算法和改进的Bresenham算法扫描转换直线段P1P2,其中P1为(0, 0), P2为(8, 6)。

 

// fhk.cpp : 定义控制台应用程序的入口点。
//

#include 
#include "stdio.h"
#include 
#include 
#include 
using namespace std;

void DDALine(int x0,int y0,int x1,int y1)
{
	int dx,dy,esp;
	float x,y,xIncre,yIncre;
	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);
	glColor3f(1.0f,0.0f,0.0f);
    glPointSize(3.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)
{
	 
	glColor3f(0.0f,1.0f,0.0f);
	glPointSize(3.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)
{
	glColor3f(0.0f,0.0f,1.0f);
	glPointSize(3.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 Inital(void)
{
	glClearColor(1.0f,1.0f,1.0f,0.0f);
	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0.0,200.0,0.0,150.0);
}

void Display(void)
{
	int x0 = 0,y0 = 0;
	int x1 = 100,y1 = 100;
	DDALine(x0,y0,x1,y1);
	BresenhamLine(x0+1,y0,x1+1,y1);
	Bresenham(x0+2,y0,x1+2,y1);
}
  

int main(int argc,char* argv[])
{
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowSize(400,300);
	glutInitWindowPosition(100,120);
	glutCreateWindow("DDALine");
	Inital();
	glutDisplayFunc(Display);	
	glutMainLoop();
	return 0;
}


你可能感兴趣的:(openGL)