首页 > 解决方案 > glReadPixels GL_DEPTH_COMPONENT 在 mousePressEvent 中不起作用

问题描述

我正在使用 QT QOpenGLWidget,我想将鼠标单击位置取消投影回 3D,所以我使用了glReadPixels。(我还阅读了Pangolin的源代码,一个非常好的旋转、平移、缩放示例,它也使用 glReadPixels)

这是我的简单代码的一部分:

void myGLWidget::initializeGL()
{
    glClearColor(0.2, 0.2, 0.2, 1.0);                    //background color
    glClearDepthf(1.0);                                  //set depth test
    glEnable(GL_DEPTH_TEST);                             //enable depth test
}

void myGLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear color and depth buffer

    glMatrixMode(GL_MODELVIEW);
    glLoadMatrixf(cameraView_.data());         // cameraView_  is a QMatrix4x4
    drawingTeapot();

    // reading pixels in paintGL works well!!! returns lots of 1s
    GLfloat zs[10 * 10];
    glReadPixels(0, 0, 10, 10, GL_DEPTH_COMPONENT, GL_FLOAT, &zs);
}

void myGLWidget::mousePressEvent(QMouseEvent *event)
{
    // glReadBuffer(GL_FRONT);      // also tried this, nothing works
    GLfloat zs[10 * 10];
    glReadPixels(0, 0, 10, 10, GL_DEPTH_COMPONENT, GL_FLOAT, &zs);
    GLenum e = glGetError();        // this gives 1282 err code!!!
}

我正在使用 macOS Sierra,Pangolin在我的笔记本电脑上完美运行,但是,我的 qt 项目确实有效??!!

说不工作,我的意思是输出变量zs仍然是随机值,如 0 和 123123e-315,并且在 glReadPixels 之前和之后它永远不会改变。

为什么 glReadPixels 仅适用于 PaintGL 函数?

我也试过python版本它给了我一个错误说

File "errorchecker.pyx", line 53, in OpenGL_accelerate.errorchecker._ErrorChecker.glCheckError (src/errorchecker.c:1218)
OpenGL.error.GLError: GLError(
    err = 1282,
    description = b'invalid operation',
    baseOperation = glReadPixels,

可能是这种情况: GL_INVALID_OPERATION is generated if format is GL_DEPTH_COMPONENT and there is no depth buffer.来自文档的参考

但我仍然不知道该怎么办

标签: qtopengl

解决方案


仅当 OpenGL 上下文处于活动状态时才应执行 OpenGL 操作。这在paintGL() 方法中是正确的,因为这可能是由框架为您设置的。您不能假设 OpenGL 在其他方法中处于活动状态,例如在其他事件响应方法和回调中,如 mousePressEvent(),因为这些方法也可以由 OpenGL 上下文不活动的不同线程运行。


推荐阅读