2012-03-28 96 views
0

我已經用C++編寫了一個簡單的OpenGL程序,它顯示了一個將窗口中心連接到鼠標指針當前位置的線。使用glutPassiveMotionFunc();在GLUT

我的代碼是:

#ifdef __APPLE__ 
#include <GLUT/glut.h> 
#else 
#include <GL/glut.h> 
#endif 
#include<iostream> 

using namespace std; 

void passive(int,int); 
void reshape(int,int); 
void init(void); 
void display(void); 
void camera(void); 

int x=3,y=3; 

int main (int argc,char **argv) { 
    glutInit (&argc,argv); 
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); 
    glutInitWindowSize(1364,689); 
    glutInitWindowPosition(0,0); 
    glutCreateWindow("Sample"); 
    init(); 
    glutDisplayFunc(display); 
    glutIdleFunc(display); 
    glutPassiveMotionFunc(passive); 
    glutReshapeFunc(reshape); 
    glutMainLoop(); 
    return 0; 
} 

void display(void) { 
    glClearColor (0.0,0.0,0.0,1.0); 
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
    glLoadIdentity(); 
    camera(); 

    glBegin(GL_LINES); 
     glVertex3f(0,0,0); 
     glVertex3f(x,y,0); 
    glEnd(); 
    glutSwapBuffers(); 
}  

void camera(void) { 
    glRotatef(0.0,1.0,0.0,0.0); 
    glRotatef(0.0,0.0,1.0,0.0); 
    glTranslated(0,0,-20); 
}  

void init(void) { 
    glEnable (GL_DEPTH_TEST); 
    glEnable (GL_BLEND); 
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 
    glEnable(GL_COLOR_MATERIAL); 
}  

void reshape(int w, int h) { 
    glViewport(0,0,(GLsizei)w,(GLsizei)h); 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    gluPerspective(60,(GLfloat)w/(GLfloat)h,1.0,100.0); 
    glMatrixMode(GL_MODELVIEW); 
} 

void passive(int x1,int y1) { 
    x=x1; y=y1; 
} 

我面臨的問題是,在被動()函數設定的x和y值不正確映射成採用透視投影在屏幕上。所以繪製的線將中心連接到屏幕外的其他座標。對代碼進行任何修改以使其正常工作?

回答

1

一個簡單的方法是創建一個正交投影矩陣,然後渲染所有「2D」元素(包括此線,使用glutPassiveMotionFunc提供的屏幕座標)。

事情是這樣的:

void display() { 
    // clear 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    gluPerspective(...) // create 3D perspective projection matrix 
    glMatrixMode(GL_MODELVIEW); 

    // Render 3D content here 

    // Render 2D content 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    gluOrtho2D(0, width, height, 0); // create 2D orthographic projection matrix with coordinate system roughly equivalent to window position 
    glMatrixMode(GL_MODELVIEW); 

    glBegin(GL_LINES); 
    glVertex2f(width/2, height/2); // now we can use "pixel coordinates" 
    glVertex2f(cursorX, cursorY); 
    glEnd(); 

    ... 
} 

reshape方法比較這對你的透視投影的修改。

顯然你也想要禁用對「2D」渲染沒有意義的狀態(如深度緩衝區檢查等),但它應該很明顯。請看this GDSE post討論其他人如何完成同樣的任務。

+0

非常感謝!得到它的工作。 – 2012-03-29 13:08:12