我无法理解为什么我没有获得给定程序的任何输出。这个问题在我的最后2个openGL程序中已经发生,前一个是DDA算法,再次我没有得到任何输出。这个算法有问题,还是我理解openGL如何在内部工作?
#include <iostream>
#include <GL/glut.h>
using namespace std;
float X1 = 0, X2 = 100, Y1 = 0, Y2 = 400, X11, Y11, X22, Y22, slope, dely, delx, c, intercept, pi;
float absl(float x) {
if (x >= 0) return x;
return -1*x;
}
void drawScene() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
glClearColor(1.0, 1.0, 1.0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
//start bresenham algo
glBegin(GL_POINTS);
glVertex2f(X1, Y1);
while(X1 <= X2) {
X1++;
if(pi < 0) {
glVertex2f(X1, Y1);
}
else {
Y1++;
glVertex2f(X1, Y1);
}
float flag = (pi >= 0);
pi = pi + 2*dely - 2*delx*flag;
}
glEnd();
//end DDA algo
glFlush();
}
int main(int argc, char **argv) {
//cin >> X1 >> Y1 >> X2 >> Y2;
// dely = Y2 - Y1;
// delx = X2 - X1;
// pi = 2*dely - delx;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0,0);
glutCreateWindow("DDA");
glutDisplayFunc(drawScene);
glutMainLoop();
return 0;
}
答案 0 :(得分:2)
gluOrtho2D
定义了2D正交投影矩阵。但它也将矩阵堆栈上的当前矩阵与正交投影矩阵相乘,并用产品替换当前矩阵。
注意,在OpenGL固定功能管道中,所有矩阵运算都是这样的(glPushMatrix
,glPopMatrix
,glLoadMatrix
和glLoadIdentity
除外。
这意味着您必须使用单位矩阵(glLoadIdentity
)替换当前矩阵,因为您应用了正交投影矩阵:
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
或者在主函数中启动主循环之前只执行gluOrtho2D
次:
gluOrtho2D(0, 500, 0, 500);
glutMainLoop();
由于显示函数是连续调用的(drawScene
),因此您应该使用本地控件变量而不是修改X1
和Y1
:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
glClearColor(0.0, 0.0, 0.0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
//start bresenham algo
int x = X1, y = Y1;
glBegin(GL_LINES);
glVertex2f(100, 400);
glVertex2f(400, 100);
glEnd();
glBegin(GL_POINTS);
glVertex2f(x, Y1);
while(x <= X2) {
x ++;
if(pi < 0) {
glVertex2f(x, y);
}
else {
y ++
glVertex2f(x, y);
}
}
int flag = (pi >= 0);
pi = pi + 2*dely - 2*delx*flag;
glEnd();