一、实验目的
1、掌握在利用OpenGL图形库进行图形程序设计的基本方法。
2、掌握Windows环境下的消息处理方法。
3、理解OpenGL运行机制。
二、实验内容
使用OpenGL实现线段的裁剪
三、主要代码
//判断位置
void chopLine(Point& p, unsigned char code, double dely, double delx) {
if (code & 1) { //0001 左方,位与运算,结果不为0时证明在窗口左方有交点
p.y += (myWindow.l - p.x) * dely / delx;
p.x = myWindow.l;
}
else if (code & 2) { //0010 右方
p.y += (myWindow.r - p.x) * dely / delx;
p.x = myWindow.r;
}
else if (code & 4) { //0100 下方
p.x += (myWindow.b - p.y) * delx / dely;
p.y = myWindow.b;
}
else { //1000 上方
p.x += (myWindow.t - p.y) * delx / dely;
p.y = myWindow.t;
}
}
//按位或,生成编号
void generateCode(Point& p, unsigned char& code) {
if (p.x < myWindow.l) code |= 1;
if (p.y > myWindow.t) code |= 8;
if (p.x > myWindow.r) code |= 2;
if (p.y < myWindow.b) code |= 4;
}
//裁剪
int cut(pair<Point, Point>& tmp) {
unsigned char code1;
unsigned char code2;
int k = 0;
do {
code1 = 0;
code2 = 0;
generateCode(tmp.first, code1);
generateCode(tmp.second, code2);
if ((code1 | code2) == 0) { //完全在窗口里面(0000|0000)
return 1;
}
else if ((code1 & code2) != 0) { //在某条边界同侧,即完全在窗口外面
return 0;
}
if (code1 != 0) {
chopLine(tmp.first, code1, tmp.second.y - tmp.first.y, tmp.second.x - tmp.first.x);
}
if (code2 != 0) {
chopLine(tmp.second, code2, tmp.second.y - tmp.first.y, tmp.second.x - tmp.first.x);
}
k++;
} while (1);
}
void func() {
pair<Point, Point> tmp(Point(vertice[0].x, vertice[0].y), Point(vertice[1].x, vertice[1].y));
V.push_back(tmp);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f);
glVertex2f(V[0].first.x, V[0].first.y);
glVertex2f(V[0].second.x, V[0].second.y);
glColor3f(1.0f, 0.0f, 0.0f);
int a = cut(V[0]);
if (a == 1) {
glVertex2f(V[0].first.x, V[0].first.y);
glVertex2f(V[0].second.x, V[0].second.y);
}
glEnd();
glFlush();
//V.pop_back();
//vertice.pop_back();
V.clear();
vertice.clear();
}
void mydisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); //clear the screen
glColor3f(0.0f, 0.0f, 0.0f);
glLineWidth(3.0);
draw();
//func();
glFlush();
}
void mymouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
draw_a_point(x, screenHeight - y);
Point p(x, screenHeight - y);
vertice.push_back(p);
cout << "起点" << ": (" << x << ", " << y << ")" << endl;
}
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
draw_a_point(x, screenHeight - y);
Point p(x, screenHeight - y);
vertice.push_back(p);
cout << "终点" << ": (" << x << ", " << y << ")" << endl;
cout << "开始剪裁" << endl;
func();
}
}