2012-04-26 51 views
0

我的基本問題是 - 什麼是使用'gluUnProject'從我的鼠標/光標位置獲取Ray或法向量的正確方法。如何從'gluUnProject'中獲取Ray

我已將gluUnProject代碼從mesa glu C代碼轉換爲C#。

public Vector3 UnProject(Matrix4 projectionMatrix, Matrix4 viewMatrix, int viewX, int viewY, int viewWidth, int viewHeight) 
{ 
    var finalMatrix = viewMatrix.Multiply(projectionMatrix).Invert(); 

    var vec = new Vector4(this, 1); 
    vec.X = (vec.X - viewX)/viewWidth; 
    vec.Y = (vec.Y - viewY)/viewHeight; 
    vec = (vec * 2) - 1; 
    vec.Y = -vec.Y; 

    var outVec = vec.Transform(finalMatrix); 
    outVec.X /= outVec.W; 
    outVec.Y /= outVec.W; 
    outVec.Z /= outVec.W; 

    return outVec.ToVector3(); 
} 

然後我從我的相機對象調用這個方法:

public Vector3 UnProject(Vector3 screenPosition) 
{ 
    return screenPosition.UnProject(ProjectionMatrix, ViewMatrix, ViewPort.Location.X, ViewPort.Location.Y, ViewPort.Size.X, ViewPort.Size.Y); 
} 

要從射線得到我的法向量我做的:

var rayLoc = camera.UnProject(new Vector3(Game.Mouse.Location, 0)); 
var rayLoc2 = camera.UnProject(new Vector3(Game.Mouse.Location, 1)); 
var rayDirection = (rayLoc2 - rayLoc).Normalize(); 

一切工作正常,直到我將我的注視在X上指向1並在X軸和Y軸上旋轉相機一點。之後,矢量不再正確。我不知道我在做什麼錯?

編輯:經過仔細觀察,我認爲我的Matrix4.Invert方法可能是原因。我正在嘗試使用Row專業版,有什麼想法?

public Matrix4 Invert() 
{ 
    var mat = new Matrix4(
     new Vector4(
      Y.Y*Z.Z*W.W - Y.Y*Z.W*W.Z - Z.Y*Y.Z*W.W + Z.Y*Y.W*W.Z + W.Y*Y.Z*Z.W - W.Y*Y.W*Z.Z, 
      -Y.X*Z.Z*W.W + Y.X*Z.W*W.Z + Z.X*Y.Z*W.W - Z.X*Y.W*W.Z - W.X*Y.Z*Z.W + W.X*Y.W*Z.Z, 
      Y.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*X.W*Y.Z, 
      X.X*Y.Z*Z.W - X.X*Y.W*Z.Z - Y.X*X.Z*Z.W + Y.X*X.W*Z.Z + Z.X*X.Z*Y.W - Z.X*X.Z*Y.Z, 
      -X.X*Y.Y*Z.W + X.X*Y.W*Z.Y + Y.X*X.Y*Z.W - Y.X*X.W*Z.Y - Z.X*X.Y*Y.W + Z.X*X.W*Y.Y, 
      X.X*Y.Y*Z.Z - X.X*Y.Z*Z.Y - Y.X*X.Y*Z.Z + Y.X*X.Z*Z.Y + Z.X*X.Y*Y.Z - Z.X*X.Z*Y.Y)); 

    Num delta = X.X*mat.X.X + X.Y*mat.Y.X + X.Z*mat.Z.X + X.W*mat.W.X; 
    delta = 1/delta; 
    return mat * delta; 
} 

回答

0

它。原來我的Matrix4.Invert方法是錯誤的,我用OpenTK做了一個Row-Major Invert方法。

編輯:其實'https://github.com/Dav1dde/gl3n'有更好的方法去實現它。

0

通常我此:

GLint m_viewport[4]; 
GLdouble m_modelview[16]; 
GLdouble m_projection[16]; 

glGetIntegerv(GL_VIEWPORT, m_viewport); 
glGetDoublev(GL_MODELVIEW_MATRIX, m_modelview); 
glGetDoublev(GL_PROJECTION_MATRIX, m_projection); 

GLdouble rx, ry, rz; 
gluUnProject(x, y, depth, m_modelview, m_projection, m_viewport, &rx, &ry, &rz); 

其中X和Y是鼠標座標和深度在(0某個值,1] - 我通常採取0.5