计算机图形学基础(OpenGL版) 实验二 直线生成

计算机图形学基础 实验二 直线生成


实验代码

#include "Dependencies\glew\glew.h"
#include "Dependencies\freeglut\freeglut.h"
#include 

//微分法画直线
void LineDDA(int x1, int y1, int x2, int y2)
{
	int x, dy, dx, y;
	int m;
	dx = x2 - x1;
	dy = y2 - y1;
	m = dy / dx;
	y = y1;

	glColor3f(1.0f, 1.0f, 0.0f);
	glPointSize(1);
	for (x = x1; x <= x2; x++)
	{
		glPointSize(5);
		glBegin(GL_POINTS);
		glVertex2i(x, (int)(y + 0.5));
		glEnd();
		y += m;
	}
}


void mydisplay(void)
{
	glClear(GL_COLOR_BUFFER_BIT);
	
	//画矩形
	glColor3f(1.0f, 0.0f, 0.0f);	//控制颜色
	glRectf(25.0, 25.0, 75.0, 75.0);	//控制矩形的对角线坐标

	//画点
	glBegin(GL_POINTS);
	//glPointSize(5);	//点的大小,默认为1
	glColor3f(0.0f, 1.0f, 0.0f);
	glVertex2f(0.0f, 0.0f);	//点的坐标
	glEnd();

	LineDDA(0, 0, 200, 300);

	//画直线
	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(void)
{
	glClearColor(0.0, 0.0, 0.0, 0.0); //窗口颜色(红:[0.0~1.0]R, 绿:[0.0~1.0]G,蓝:[0.0~1.0]B, 透明度:[0.0~1.0]
	glShadeModel(GLU_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);
}

void lineSegment(void)
{
	glClear(GL_COLOR_BUFFER_BIT);//GL_COLOR_BUFFER_BIT是一个OpenGL符号常量,用来指定它的颜色缓存(刷新缓存)中的位值
	glColor3f(1.0f, 1.0f, 0.0f);//设置线段颜色为红色

	//画矩形
	glBegin(GL_POLYGON);
	//三个点的坐标
	glVertex2f(50.0, 50.0);
	glVertex2f(250.0, 50.0);
	glVertex2f(250.0, 250.0);
	glEnd();

	glFlush(); //执行所有的OpenGL程序
}

int main(int argc, char *argv[])
{
	glutInit(&argc, argv);//初始化GULT
	glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);//设置显示模式
	glutInitWindowPosition(100, 100);//设置左上角窗口显示位置
	glutInitWindowSize(400, 400);//设置窗口显示的宽与高
	glutCreateWindow("An Example OpenGL Program!");//创建一个窗口,并命名
	init();//执行初始化程序
	//把图形显示在窗口
	glutDisplayFunc(mydisplay);
	glutReshapeFunc(reshape);
	glutMainLoop();//显示所有并进入等待状态
	return 0;
}

要求要找出来的错误:

//微分法画直线
void LineDDA(int x1, int y1, int x2, int y2)
{
	int x, dy, dx, y;
	int m;
	dx = x2 - x1;
	dy = y2 - y1;
	m = dy / dx;
	y = y1;

	glColor3f(1.0f, 1.0f, 0.0f);
	glPointSize(1);
	for (x = x1; x <= x2; x++)
	{
		glPointSize(5);
		glBegin(GL_POINTS);
		glVertex2i(x, (int)(y + 0.5));
		glEnd();
		y += m;
	}
}

m应改为浮点型

你可能感兴趣的:(计算机图形学基础)