我的基本问题是 - 使用'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();
}
然后我从我的Camera对象中调用此方法:
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();
一切正常,直到我将LookAt点移动到X上的1并且在X轴和Y轴上稍微旋转相机。之后,矢量不再正确。我不知道我做错了什么?
编辑:仔细看后,我认为我的Matrix4.Invert方法可能是原因。我正在尝试使用Row major,任何想法?
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.X*Z.Y*W.W - Y.X*Z.W*W.Y - Z.X*Y.Y*W.W + Z.X*Y.Y*W.Y + W.X*Y.Y*Z.W - W.X*Y.W*Z.Y,
-Y.X*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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 :(得分: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。
答案 1 :(得分:0)
事实证明我的Matrix4.Invert方法错了。我使用OpenTK作为Row-Major Invert方法的参考。
编辑:实际上'https://github.com/Dav1dde/gl3n'有更好的方法来实现它。