OpenGL - glReadPixels返回不正确的值

时间:2014-08-23 10:36:45

标签: arrays opengl pixels

我可能遗漏了一些明显的东西,但我发现代码没有任何问题。这是出于测试目的,它应该做的就是将所有像素的颜色设置为白色并读取像素信息。结果是一个满0的数组。

    unsigned int frameBuffer;
    glGenFramebuffers(1,&frameBuffer);
    unsigned int texture;
    unsigned int depthTexture;
    glGenTextures(1,&texture);
    glGenTextures(1,&depthTexture);

    glBindFramebuffer(GL_FRAMEBUFFER,frameBuffer);
    glBindTexture(GL_TEXTURE_2D,texture);

    int w = 256;
    int h = 256;

    glTexImage2D(
        GL_TEXTURE_2D,
        0,
        GL_RGB,
        w,h,
        0,GL_RGB,
        GL_UNSIGNED_BYTE,
        0
    );
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,texture,0);

    glBindTexture(GL_TEXTURE_2D,depthTexture);
    glTexImage2D(
        GL_TEXTURE_2D,
        0,
        GL_DEPTH_COMPONENT16,
        w,h,
        0,GL_DEPTH_COMPONENT,
        GL_FLOAT,
        0
    );
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,depthTexture,0);

    int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(status == GL_FRAMEBUFFER_COMPLETE)
    {
        unsigned char *pixels = new unsigned char[w *h *3];
        for(unsigned int i=0;i<(w *h *3);i++)
            pixels[i] = 255;
        glDrawPixels(w,h,GL_RGB,GL_UNSIGNED_BYTE,&pixels[0]);
        glReadPixels(0,0,w,h,GL_RGB,GL_UNSIGNED_BYTE,&pixels[0]);
        for(unsigned int i=0; i<(w *h *3); i+=3)
        {
            unsigned int r = pixels[i];
            unsigned int g = pixels[i + 1];
            unsigned int b = pixels[i + 2];
            std::cout<<i<<": "<<r<<","<<g<<","<<b<<std::endl;
        }
        delete[] pixels;
        int err = glGetError(); // No error reported
    }
    glBindTexture(0,GL_TEXTURE_2D);
    glBindFramebuffer(0,GL_FRAMEBUFFER);

没有报告错误,帧缓冲区也没问题。这是怎么回事?

2 个答案:

答案 0 :(得分:1)

在通话前尝试确保栅格位置对glDrawPixels有效:

glRasterPos(0,0);
glDrawPixels(w,h,GL_RGB,GL_UNSIGNED_BYTE, pixels);
glReadPixels(0,0,w,h,GL_RGB,GL_UNSIGNED_BYTE, pixels);

答案 1 :(得分:1)

有人在不同的论坛上找到了原因。

解决方案是致电

glReadBuffer(GL_COLOR_ATTACHMENT0);

在调用glReadPixels之前,

glReadBuffer(GL_BACK);

之后,重置它。