C ++/OpenGL将世界坐标转换为屏幕(2D)坐标 [英] C++/OpenGL convert world coords to screen(2D) coords

查看:876
本文介绍了C ++/OpenGL将世界坐标转换为屏幕(2D)坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在OpenGL中制作一个游戏,在这个游戏中我在世界空间中有一些物体.我想创建一个函数,在其中可以获取对象的位置(3D)并将其转换为屏幕的位置(2D)并返回它.

I am making a game in OpenGL where I have a few objects within the world space. I want to make a function where I can take in an object's location (3D) and transform it to the screen's location (2D) and return it.

我知道以下变量中对象,投影矩阵和视图矩阵的3D位置:

I know the the 3D location of the object, projection matrix and view matrix in the following varibles:

Matrix projectionMatrix;
Matrix viewMatrix;
Vector3 point3D;

推荐答案

要执行此转换,必须首先获取模型空间位置并将其转换为剪贴空间.这是通过矩阵乘法完成的.我将使用GLSL样式的代码来使自己的工作变得显而易见:

To do this transform, you must first take your model-space positions and transform them to clip-space. This is done with matrix multiplies. I will use GLSL-style code to make it obvious what I'm doing:

vec4 clipSpacePos = projectionMatrix * (viewMatrix * vec4(point3D, 1.0));

在乘法之前,请注意我如何将3D向量转换为4D向量.这是必需的,因为矩阵是4x4,并且您不能将4x4矩阵与3D向量相乘.您需要第四个组件.

Notice how I convert your 3D vector into a 4D vector before the multiplication. This is necessary because the matrices are 4x4, and you cannot multiply a 4x4 matrix with a 3D vector. You need a fourth component.

下一步是将该位置从片段空间转换为规范化的设备坐标空间(NDC空间). NDC空间在所有三个轴上都在[-1,1]范围内.这是通过将前三个坐标除以第四个坐标来完成的:

The next step is to transform this position from clip-space to normalized device coordinate space (NDC space). NDC space is on the range [-1, 1] in all three axes. This is done by dividing the first three coordinates by the fourth:

vec3 ndcSpacePos = clipSpacePos.xyz / clipSpacePos.w;

很明显,如果clipSpacePos.w为零,则说明您有问题,因此应事先进行检查.如果为零,则表示对象在投影平面中;否则为0.它的视图空间深度为零. OpenGL会自动裁剪这些顶点.

Obviously, if clipSpacePos.w is zero, you have a problem, so you should check that beforehand. If it is zero, then that means that the object is in the plane of projection; it's view-space depth is zero. And such vertices are automatically clipped by OpenGL.

下一步是将[-1,1]空间转换为相对于窗口的坐标.这需要使用您传递给glViewport的值.前两个参数是距窗口左下角的偏移量(vec2 viewOffset),后两个参数是视口区域的宽度/高度(vec2 viewSize).鉴于这些,窗口空间位置为:

The next step is to transform from this [-1, 1] space to window-relative coordinates. This requires the use of the values you passed to glViewport. The first two parameters are the offset from the bottom-left of the window (vec2 viewOffset), and the second two parameters are the width/height of the viewport area (vec2 viewSize). Given these, the window-space position is:

vec2 windowSpacePos = ((ndcSpacePos.xy + 1.0) / 2.0) * viewSize + viewOffset;

这就是您所需要的.请记住:OpenGL的窗口空间是相对于窗口的左下角,而不是左上角.

And that's as far as you go. Remember: OpenGL's window-space is relative to the bottom-left of the window, not the top-left.

这篇关于C ++/OpenGL将世界坐标转换为屏幕(2D)坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆