OpenGL 数学 - 将屏幕空间投影到世界空间坐标
是时候在一天结束时进行一些数学运算了。
我需要投影窗口大小的 4 个点:
<0,0> <1024,768>
进入世界空间坐标,因此它将形成一个四边形形状,稍后将用于地形剔除 - 不使用 GluUnproject
仅用于测试,我使用鼠标坐标 - 并尝试投影他们到世界坐标上
Time for a little bit of math for the end of the day..
I need to project 4 points of the window size:
<0,0> <1024,768>
Into a world space coordinates so it will form a quadrilateral shape that will later be used for terrain culling - without GluUnproject
For test only, I use mouse coordinates - and try to project them onto the world coords
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
已解决
以下是具体的步骤。
构造一个由以下组成的向量4
x =
mouseposition.x
在窗口 x 范围内y =
mouseposition.y
在窗口 y 范围内z =
深度值
(可以使用 glReadPixel 获得)w =
1.0
将结果向量除以矩阵相乘后的 w 分量(透视除法)
RESOLVED
Here's how to do it exactly, step by step.
Construct a vector4 consisting of
x =
mouseposition.x
within a range of window xy =
mouseposition.y
within a range of window yz =
the depth value
( this can be obtained with glReadPixel)w =
1.0
Multiply the vector by inversed matrix created before
Divide result vector by it's w component after matrix multiplication ( perspective division )
我必须对此处提供的答案进行一些调整。但这是我最终得到的代码(注意我正在使用 GLM,这可能会影响乘法顺序)。 closeResult 是近平面上的投影点,farResult 是远平面上的投影点。我想执行光线投射来查看鼠标悬停的位置,因此我将它们转换为方向向量,然后该方向向量将源自相机的位置。
I had to make some adjustments to the answers provided here. But here's the code I ended up with (Note I'm using GLM, that could affect multiplication order). nearResult is the projected point on the near plane and farResult is the projected point on the far plane. I want to perform a ray cast to see what my mouse is hovering over so I convert them to a direction vector which will then originate from my camera's position.
将所有矩阵相乘。然后将结果反转。投影后的点总是在-1,1内。所以四个角屏幕点分别为-1,-1; -1,1; 1,-1;1,1。但您仍然需要选择 z 值。如果你在 OpenGL 中,z 介于 -1 和 1 之间。对于 directx,范围是 0 到 1。最后获取你的点并用矩阵变换它们
Multiply all your matrices. Then invert the result. Point after projection are always in the -1,1. So the four corner screen points are -1,-1; -1,1; 1,-1;1,1. But you still need to choose th z value. If you are in OpenGL, z is between -1 and 1. For directx, the range is 0 to 1. Finally take your points and transform them with the matrix
如果您有权访问 glu 库,请使用 gluUnProject(winX 、winY、winZ、模型、投影、视口、&objX、&objY、&objZ);
winX
和winY
将以像素为单位表示屏幕的角点。winZ
是 [0,1] 中的一个数字,它将指定点应落在zNear
和zFar
(剪裁平面)之间的位置。objX-Z
将保存结果。中间变量是相关矩阵。如果需要的话可以查询。If you have access to the glu libraries, use gluUnProject(winX, winY, winZ, model, projection, viewport, &objX, &objY, &objZ);
winX
andwinY
will be the corners of your screen in pixels.winZ
is a number in [0,1] which will specify where betweenzNear
andzFar
(clipping planes) the points should fall.objX-Z
will hold the results. The middle variables are the relevant matrices. They can be queried if needed.