OpenGL数学-将屏幕空间投影到世界空间坐标 [英] OpenGL Math - Projecting Screen space to World space coords

查看:151
本文介绍了OpenGL数学-将屏幕空间投影到世界空间坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一天结束时要花点时间做数学.

Time for a little bit of math for the end of the day..

我需要投影窗口大小的4个点:

< 0,0>< 1024,768>

<0,0> <1024,768>

进入世界空间坐标,因此它将形成四边形,以后将用于地形剔除-不使用GluUnproject

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

推荐答案

已解决

这里是逐步进行精确操作的方法.

Here's how to do it exactly, step by step.

  1. 在客户区域内获取鼠标坐标
  2. 如果不需要模型矩阵,则获取投影矩阵和视图矩阵.
  3. 乘以投影*查看
  4. 求逆结果
  5. 构造由以下组成的vector4

  1. Obtain your mouse coordinates within the client area
  2. Get your Projection matrix and View matrix if no Model matrix required.
  3. Multiply Projection * View
  4. Inverse the results of multiplication
  5. Construct a vector4 consisting of

x = mouseposition.x在x窗口范围内

x = mouseposition.x within a range of window x

  • 转换为-1和1之间的值

y = mouseposition.y在窗口y的范围内

y = mouseposition.y within a range of window y

  • 转换为-1和1之间的值
  • 请记住在需要时将mouseposition.y反转

z = the depth value(可以使用glReadPixel获得)

z = the depth value ( this can be obtained with glReadPixel)

  • 您可以手动将-1设为1(zNear,zFar)

w = 1.0

将矢量乘以之前创建的逆矩阵

Multiply the vector by inversed matrix created before

通过矩阵乘法(透视除法)后的w分量对结果向量进行除法

Divide result vector by it's w component after matrix multiplication ( perspective division )

    POINT mousePos;
    GetCursorPos(&mousePos);
    ScreenToClient( this->GetWindowHWND(), &mousePos );         

    CMatrix4x4 matProjection = m_pCamera->getViewMatrix() *  m_pCamera->getProjectionMatrix() ;

    CMatrix4x4 matInverse =  matProjection.inverse();


    float in[4];
    float winZ = 1.0;


    in[0]=(2.0f*((float)(mousePos.x-0)/(this->GetResolution().x-0)))-1.0f,
    in[1]=1.0f-(2.0f*((float)(mousePos.y-0)/(this->GetResolution().y-0)));
    in[2]=2.0* winZ -1.0;
    in[3]=1.0;          

    CVector4 vIn = CVector4(in[0],in[1],in[2],in[3]);
    pos = vIn * matInverse;

    pos.w = 1.0 / pos.w;

    pos.x *= pos.w;
    pos.y *= pos.w;
    pos.z *= pos.w;

    sprintf(strTitle,"%f %f %f / %f,%f,%f ",m_pCamera->m_vPosition.x,m_pCamera->m_vPosition.y,m_pCamera->m_vPosition.z,pos.x,pos.y,pos.z);

    SetWindowText(this->GetWindowHWND(),strTitle);

这篇关于OpenGL数学-将屏幕空间投影到世界空间坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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