屏幕 space 到世界 space

Screen space to world space

我正在用 C++ 编写绘图程序,但不知道如何从屏幕 space 转换为世界 space

我可以访问投影和视图矩阵以及屏幕尺寸等

这是我正在使用的代码,但它不起作用

没有错误,但它根本不输出世界space坐标,它只是稍微改变了所有像素坐标

我正在关注我在此处找到的答案 OpenGL Math - Projecting Screen space to World space coords

我现在只使用正交相机

glm::mat4 proj = cameraComp.Camera.GetProjection();
glm::mat4 view = glm::translate(glm::mat4(1.0f), transformComp.Position)
       * glm::rotate(glm::mat4(1.0f), glm::radians(transformComp.Rotation.z), glm::vec3(0, 0, 1));

glm::mat4 inversed = glm::inverse(proj * view);

glm::vec4 worldPos = { newMousePos, 0, 1 };
worldPos *= inversed;

视图矩阵从世界 space 转换为视图 space。因此,逆视图矩阵从视图 space 转换为世界 space.
投影矩阵从视图 space 转换为剪辑 space,逆投影矩阵从剪辑 space 转换为视图 space。 Clip space 是一个 Homogeneous coordinate system. In order to transform from the clip space to normalized device space, you must do a Perspective divide. Normalized device space is Cartesian coordinates 系统。 Hency,如果要从normalized devicespace变换到viewspace,需要通过逆投影矩阵变换,通过w分量划分x,y,z分量[=18] =] 另见

由于您使用的是 GLM,我建议使用 glm::unProject 进行转换。

它不是 GLM,但对于任何类型的数学库来说都是更常见的风格

// make cursor coordinates from -1 to +1
float pt_x = (point.x / screenSize.x) * 2.f - 1.f;
float pt_y = -(point.y / screenSize.y) * 2.f + 1.f;

//                       z value from 0.f to 1.f for d3d
vec4 origin = math::mul(vec4(pt_x, pt_y, -1.f, 1.f), VPinv);
origin.w = 1.0f / origin.w;
origin.x *= origin.w;
origin.y *= origin.w;
origin.z *= origin.w;

当您的相机已被修改以提高性能时,您只需计算一次 ViewProjectInvert 矩阵。

void camera::update(){
    ....
    m_viewProjectionMatrix = m_projectionMatrix * m_viewMatrix;
    m_viewProjectionInvertMatrix = m_viewProjectionMatrix;
    m_viewProjectionInvertMatrix.invert();
}