您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 人事档案/员工关系 > OpenGL生成指定的直线DDA算法和Bresenham算法
121.实验目的:(1)学会使用OpenGL生成指定的直线。(2)掌握生成直线的DDA算法和Bresenham算法。2.实验内容:运用DDA和Bresenham算法画出一条直线,3.实验算法分析:DDA算法:利用两点确定斜率,及在8个象限中的坐标增量的规律生成直线;Bresenham算法:1、将直线光栅化,计算误差初值Pi=2dy-dx,求出下一点的位置;2、如果Pi0,则y(i+1)=yi+1,否则y(i+1)=yi;3、画出点,继而迭代求出各点,最终生成直线。4.程序源代码:DDA算法:#includeGL/glut.hvoidinit(void){glClearColor(1.0,1.0,1.0,1.0);gluOrtho2D(0.0,50.0,0.0,50.0);}intabs(intx){inty;if(x=0)y=-x;elsey=x;returny;}voidset_pixel(floatx,floaty){glPointSize(5);glBegin(GL_POINTS);glVertex2f(x,y);glEnd();}voiddda_line(intxa,intya,intxb,intyb)3{floatdelta_x,delta_y,x,y;intdx,dy,steps,k;dx=xb-xa;dy=yb-ya;if(abs(dx)abs(dy))steps=abs(dx);elsesteps=abs(dy);delta_x=(float)dx/(float)steps;delta_y=(float)dy/(float)steps;x=xa;y=ya;set_pixel(x,y);for(k=1;k=steps;k++){x+=delta_x;y+=delta_y;set_pixel(x,y);}}voiddisplay(void){glClear(GL_COLOR_BUFFER_BIT);glColor3f(0.5,1.0,0.5);dda_line(25,25,5,45);glPointSize(6.0);glBegin(GL_POINTS);glVertex2f(1.0,1.0);glEnd();glFlush();}intmain(intargc,char**argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(250,250);glutInitWindowPosition(500,250);4glutCreateWindow(OpenGL框架之直线与点);init();glutDisplayFunc(display);glutMainLoop();return0;}Bresenham算法:#includeGL/glut.hvoidinit(void){glClearColor(1.0,1.0,1.0,1.0);gluOrtho2D(0.0,50.0,0.0,50.0);}intabs(intx){inty;if(x=0)y=-x;elsey=x;returny;}voidset_pixel(floatx,floaty){glPointSize(5);glBegin(GL_POINTS);glVertex2f(x,y);glEnd();}5voidvoidline(intx1,inty1,intx2,inty2){intdx;intdy;intx;inty;intp;intconst1;intconst2;intinc;inttmp;dx=x2-x1;dy=y2-y1;if(dx*dy=0)inc=1;elseinc=-1;if(abs(dx)abs(dy)){if(dx0){tmp=x1;x1=x2;x2=tmp;tmp=y1;y1=y2;y2=tmp;dx=-dx;dy=-dy;}p=2*dy-dx;const1=2*dy;const2=2*(dy-dx);x=x1;y=y1;set_pixel(x,y);while(xx2){x++;if(p0)p+=const1;else{y+=inc;p+=const2;6}set_pixel(x,y);}}else{if(dy0){tmp=x1;x1=x2;x2=tmp;tmp=y1;y1=y2;y2=tmp;dx=-dx;dy=-dy;}p=2*dx-dy;const1=2*dx;const2=2*(dx-dy);x=x1;y=y1;set_pixel(x,y);while(yy2){y++;if(p0)p+=const1;else{x+=inc;p+=const2;}set_pixel(x,y);}}}voiddisplay(void){glClear(GL_COLOR_BUFFER_BIT);glColor3f(0.5,1.0,0.5);voidline(25,5,45,45);glPointSize(6.0);7glFlush();}intmain(intargc,char**argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(250,250);glutInitWindowPosition(500,250);glutCreateWindow(OpenGL框架之直线与点);init();glutDisplayFunc(display);glutMainLoop();return0;}5.运行结果:DDA运行效果图:8Bresenham算法效果图:
本文标题:OpenGL生成指定的直线DDA算法和Bresenham算法
链接地址:https://www.777doc.com/doc-4608130 .html