Vẽ đường thẳng C++

Mô tả thuật toán

dt

dt2 dt3 dt4

Sau đây xin phép được hiện thực thuật toán vẽ đường thẳng qua code C++


#include "stdafx.h"
#include "glut.h"
#include 
#include 
int screenWidth=640;
int screenHeight=640;
typedef struct
{ 
	GLint x1,y1;
	GLint x2,y2;
} GLintPoint;
#define NUM 100
GLintPoint list[NUM];
int last=-1;
GLfloat x,y,xt1,xt2,yt1,yt2;
void hoanvi(int &x,int &y)
{
	int tam;
	tam=x;
	x=y;
	y=tam;
}
void BRE(int x1,int y1,int x2,int y2)
{
	int x,y,dx,dy,p;
	if(x1>x2)
	{
		hoanvi(x1,x2);
	 	hoanvi(y1,y2);
	}
	glColor3f(0.0f, 0.4f, 1.0f);
		 glBegin(GL_POINTS);
			glVertex2i(x1,y1); 
	dx=abs(x2-x1);
	dy=abs(y2-y1);
	x=x1;
	y=y1;
	long const1y=2*dy;
	long const1x=2*dx;
	long const2y=2*(dy-dx);
	long const2x=2*(dx-dy);
	if(dx>dy)
	{
		p=2*dy-dx;
		glVertex2i(x,y); 
		while(x<=x2)
		{
			
			if(p<0)
				p+=const1y;
			else
			{     
				if(y1else
				{
					
					p+=const2y;
					y--;
				}
			}
			x++;
			glVertex2i(x,y); 
		}
	}
	else{
		p=2*dx-dy;
		glVertex2i(x,y); 
		if(y1while(y<=y2)
			{
				
				if(p<0)
					p+=const1x;
				else
				{
					
					p+=const2x;
					x++;
				}
				y++;
				glVertex2i(x,y); 
			}
		}
		else
		{
			while(y>=y2)
			{
				
				if(p<0)
					p+=const1x;
				else
				{
					
					p+=const2x;
					x++;
				}
				y--;
				glVertex2i(x,y); 
			}
		}
	}
}

void output()
{
	glClear(GL_COLOR_BUFFER_BIT);
	for(int i=0;i <=last;i++)
	{
		BRE(list[i].x1,list[i].y1,list[i].x2,list[i].y2);
	}
		BRE(xt1,yt1,xt2,yt2);
		glClear(GL_COLOR_BUFFER_BIT);
	glEnd();
	glutSwapBuffers();
}
void xulychuot(int button,int status,int x,int y)
{
	if(button==0&&status==0)
	{
		xt1=x;
		yt1=screenHeight-y;
	}
	if(button==0&&status==1)
	{
		xt2=x;
		yt2=screenHeight-y;
		BRE(xt1,yt1,xt2,yt2);
		last++;
		list[last].x1=xt1;
		list[last].y1=yt1;
		list[last].x2=xt2;
		list[last].y2=yt2;
		output();
	}
	if(button==2 && status==0)
			last=-1;
}
void chuotdichuyen(int x,int y)
{
	glClear(GL_COLOR_BUFFER_BIT);
	xt2 = x;
	yt2 = screenHeight-y;
	output();
}
void SetupRC()
{
	glClearColor(0,0,0,0);
	glClear(GL_COLOR_BUFFER_BIT);
	glPointSize(3.0);
	gluOrtho2D(0,640,0,640);
}

int _tmain(int argc, char* argv[])
{
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_DOUBLE);
	glutInitWindowSize(screenWidth,screenHeight);
	glutCreateWindow("ve duong thang thuat toan Bresenham");
	glutMouseFunc(xulychuot);
	glutMotionFunc(chuotdichuyen);
	glutDisplayFunc(output);
	SetupRC();
	glutMainLoop();
	return 0;
}

Chủ đề liên quan
Vẽ đường thẳng C++

Cùng chuyên mục

Xem nhiều hôm nay