OSG屏幕坐标转世界坐标

 1 static osg::Matrix getScreenToWorldMatrix(osg::View *view)
 2 {
 3     return osg::Matrix::inverse(getWorldToScreenMatrix(view));
 4 }
 5 
 6 static osg::Matrix getWorldToScreenMatrix(osg::View *view)
 7 {
 8     auto camera = view->getCamera();
 9     auto view_matrix = camera->getViewMatrix();
10     auto proj_matrix = camera->getProjectionMatrix();
11     auto vp = camera->getViewport();
12     auto screen_matrix = vp->computeWindowMatrix();
13 
14     return view_matrix * proj_matrix * screen_matrix;
15 }
16 
17 static osg::Vec3 ndcPointToWorld(osg::View *view, const osg::Vec2 &pt)
18 {
19     auto camera = view->getCamera();
20     auto view_matrix = camera->getViewMatrix();
21     auto proj_matrix = camera->getProjectionMatrix();
22     auto vp_matrix = view_matrix * proj_matrix;
23     auto pv_matrix = osg::Matrix::inverse(vp_matrix);
24 
25     auto world_pt = osg::Vec3(pt, 0) * pv_matrix;
26     return world_pt;
27 }
28 
29 static osg::Vec3 screenPointToWorld(osg::View *view, const osg::Vec2 &pt)
30 {
31     auto camera = view->getCamera();
32     auto view_matrix = camera->getViewMatrix();
33     auto proj_matrix = camera->getProjectionMatrix();
34     auto vp = camera->getViewport();
35     auto screen_matrix = vp->computeWindowMatrix();
36     auto vps_matrix = view_matrix * proj_matrix * screen_matrix;
37     auto spv_matrix = osg::Matrix::inverse(vps_matrix);
38 
39     // QT 及 Windows窗口坐标系统原点(0,0)在左上角,OpenGL默认在左下角,注意D3D在左上角
40     auto world_pt = osg::Vec3(pt.x(), vp->y() - pt.y(), 0);
41     world_pt = world_pt * spv_matrix;
42     return world_pt;
43 }
44 
45 static osg::Vec2 screenPointToNdc(osg::View* view, const osg::Vec2& pt){
46     auto camera = view->getCamera();
47     auto vp = camera->getViewport();
48     auto ndc_pt = osg::Vec2(pt.x(), vp->y() - pt.y());
49     auto x = ndc_pt.x() * 2. / vp->x() - 1.;
50     auto y = 1. - (2. * ndc_pt.y() / vp->y());
51     return osg::Vec2(x, y);
52 }

 

  在 OpenGL 中,屏幕坐标原点取决于你的视口设置和投影矩阵。OpenGL 使用一个三维笛卡尔坐标系,其中 X 轴向右延伸,Y 轴向上延伸,Z 轴指向屏幕内部。屏幕坐标原点通常位于视口的左下角,而不是左上角。如果你没有进行任何额外的变换和调整,OpenGL 默认的屏幕坐标原点是位于视口的左下角,即 (0, 0) 坐标。

  请注意,OpenGL 使用的是右手坐标系,X 轴指向右边,Y 轴指向上方,Z 轴指向屏幕内部。这与一些其他图形库和屏幕坐标系统的约定可能有所不同。在处理 OpenGL 坐标时,需要注意坐标系的方向,以确保正确地定位和渲染图形。

  Windows窗口及Qt窗口坐标系原点在左上角。

posted @ 2023-07-27 15:27  網韻  阅读(234)  评论(0编辑  收藏  举报