目的:理解基本图形元素光栅化的基本原理;掌握一种基本图形元素光栅化算法;利用OpenGL实现直线光栅化的DDA算法。
要求:根据所给的直线光栅化的示范源程序,在计算机上编译运行,输出正确结果;了解和使用OpenGL的生成直线的命令,来验证程序运行结果。
#include <GL/glut.h>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
int color[3],wideth=0;
void LineDDA(int x0,int y0,int x1,int y1,int color[]){
int x,dy,dx,y;
float m;
dx=x1-x0;
dy=y1-y0;
m=dy/dx;
y=y0;
glColor3f(color[2]*1.0f,color[1]*1.0f,color[0]*1.0f);
glPointSize(wideth);
for(x=x0;x<=x1;x++){
glBegin(GL_POINTS);
glVertex2i(x,(int)(y+0.5));
glEnd ();
y+=m;
}
}
void myDisplay(void){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
glRectf(25.0, 25.0, 75.0, 75.0);
glPointSize(5.0f);
glBegin(GL_POINTS);
glColor3f(1.0f, 1.0f, 1.0f);
glVertex2f(100.0f,200.0f);
glEnd();
LineDDA(0, 0, 200, 300,color);
glBegin(GL_LINES);
glColor3f(1.0f, 0.0f, 0.0f); glVertex2f (100.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f); glVertex2f (180.0f, 240.0f);
glEnd();
glFlush ();
}
void Init(){
glClearColor(0.0,0.0,0.0,0.0);
glShadeModel(GL_FLAT);
}
void Reshape(int w,int h){
glViewport(0,0,(GLsizei) w,(GLsizei) h); //改变显示区域,起始位置为客户端窗口左下角(非坐标原点
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,(GLdouble) w,0.0,(GLdouble) h);//定义剪裁面,通过正交投影,把景物(模型)按照1:1的比例绘制到一个剪裁面上,相当于对世界坐标窗口的一个截取。
}
void select(){
printf("选择1~7,各画线颜色对应如下:\n");
printf(" 蓝 青 绿 红 玫瑰 黄 白\n");
printf("1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111)\n");
printf("Select[1~7]:\n");
int cr; scanf("%d",&cr);
int i=0; memset(color,0,sizeof(color));
while(cr){
color[i++]=cr%2;
cr/=2;
}
printf("Plese select the line's wideth:\n");
scanf("%d",&wideth);
wideth*=1.0;
}
int main (int argc, char *argv[]){
select();
glutInit (&argc, argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowPosition(100,100);
glutInitWindowSize(400,400);
glutCreateWindow("Hello World!");
Init();
glutDisplayFunc(myDisplay);
glutReshapeFunc(Reshape);
glutMainLoop ();
return 0;
}
运行截图: