Qt+OpenGL——3D坐标转2D坐标

原理介绍https://learnopengl-cn.github.io/01%20Getting%20started/08%20Coordinate%20Systems/

 

代码实现

为了获取模型中的顶点在窗口中显示的坐标。我们可以借用glm库对模型坐标进行转换。代码如下:

struct GLW_POINT{
    double x = 0.0;
    double y = 0.0;
    double z = 0.0;

    void clear()
    {
        x = 0.0;
        y = 0.0;
        z = 0.0;
    }

    GLW_POINT(){
        clear();
    }

};
GLW_POINT modelPosTo2D(const GLW_POINT &point)
{
    GLW_POINT p;
    glm::mat4 mat4Model;
    glm::mat4 mat4Projection;
    glm::mat4 mat4View;

    mat4Model = glm::mat4(1.0);
    mat4Projection = glm::perspective(glm::radians(45),
                                        w / h, 0.1f, 100.0f);
    mat4View = glm::mat4(1.0);

    glm::vec4 pos = glm::vec4(point.x,point.y,point.z,1.0);
    glm::vec4 res = mat4Projection * mat4View * mat4Model * pos;
    float w = glm::value_ptr(res)[3];

    if(w != 0){
        p.x = glm::value_ptr(res)[0] / w;
        p.y = glm::value_ptr(res)[1] / w;
        p.z = glm::value_ptr(res)[2] / w;
    }

    return p;
}

其中w与h是显示区域的大小,mat4View为观察矩阵。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值