2008-09-22 37 views
8

我有這種說法集:的OpenGL:投影鼠標點擊到幾何

glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective 
glLoadIdentity(); //Reset the drawing perspective 

和我從鼠標點擊屏幕上的位置(SX,SY)。

給定z的值,如何從sx和sy中計算x和y三維空間中的x和y?

回答

11

你應該使用gluUnProject

首先,計算 「逆投影」 到近平面:

GLdouble modelMatrix[16]; 
GLdouble projMatrix[16]; 
GLint viewport[4]; 

glGetIntegerv(GL_VIEWPORT, viewport); 
glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix); 
glGetDoublev(GL_PROJECTION_MATRIX, projMatrix); 

GLdouble x, y, z; 
gluUnProject(sx, viewport[1] + viewport[3] - sy, 0, modelMatrix, projMatrix, viewport, &x, &y, &z); 

,然後到遠平面:

// replace the above gluUnProject call with 
gluUnProject(sx, viewport[1] + viewport[3] - sy, 1, modelMatrix, projMatrix, viewport, &x, &y, &z); 

現在你在世界座標中找到一條線,可以找出可能已被點擊的所有可能點。所以現在你只需要插入:假設你給出了Z座標:

GLfloat nearv[3], farv[3]; // already computed as above 

if(nearv[2] == farv[2])  // this means we have no solutions 
    return; 

GLfloat t = (nearv[2] - z)/(nearv[2] - farv[2]); 

// so here are the desired (x, y) coordinates 
GLfloat x = nearv[0] + (farv[0] - nearv[0]) * t, 
     y = nearv[1] + (farv[1] - nearv[1]) * t; 
+0

對不起noob評論。 gluUnproject調用中的第三個參數是否總是相同(0和1),或者當我們使用gluPerspective設置投影矩陣時,它是否依賴於zNear和zFar值? – rgngl 2011-07-02 16:25:24

2

什麼這實際上是依賴於投影矩陣,而不是模型視圖矩陣。 http://www.toymaker.info/Games/html/picking.html應該會幫助你 - 它是以D3D爲中心的,但理論是一樣的。

但是,如果您正在尋找基於鼠標的拾取,我建議使用選擇渲染模式。

編輯:請注意,模型視圖矩陣確實起作用,但是由於您的身份是非公開的,

3

最好的來源是最權威人士OpenGL's web site

+0

把你的答案的源名稱將是有益的,而不是點擊鏈接找出。 – danio 2008-09-22 08:29:34