簡體   English   中英

glReadPixels()返回零數組

[英]glReadPixels() returns array of zeros

我使用JOGL與OpenGL配合使用,但無法獲得像素顏色。 glReadPixels()方法始終返回全零的數組。

這就是我的用法:

private static GL2 gl;

static Color getPixel(final int x, final int y) {
    ByteBuffer buffer = ByteBuffer.allocate(4);
    gl.glReadBuffer(GL.GL_FRONT);
    gl.glReadPixels(x, y, 1, 1, GL2.GL_RGB, GL2.GL_UNSIGNED_BYTE, buffer);
    byte[] rgb = buffer.array();

    return new Color(rgb[0], rgb[1], rgb[2]);
}

在重繪時(在display()方法中),我用灰色填充窗口,然后在用戶單擊窗口中的任何位置時測試結果:

@Override
public void mouseClicked(MouseEvent e) {
    // On mouse click..
    for (int j = 0; j < this.getWidth(); ++j)
        for (int i = 0; i < this.getHeight(); ++i) {
            // ..I iterate through all pixels..
            Color pxl = Algorithm.getPixel(j, i);   //! pxl should be GRAY, but it is BLACK (0,0,0)
            if (pxl.getRGB() != Color.BLACK.getRGB())
                // ..and print to console only if a point color differs from BLACK
                System.out.println("r:" + pxl.getRed() + " g:" + pxl.getGreen() + " b:" + pxl.getBlue());
        }
}

但是控制台中沒有輸出。 我已經在離散和集成圖形上對其進行了測試。 結果是一樣的。

告訴我我在做什么錯。 或分享一個工作示例,如果您偶然有使用JOGL和方法glReadPixel()的任何程序。

問題是我在mouseClicked()調用了getPixel() mouseClicked() (即從另一個線程調用)。 OpenGL上下文一次只能在單個線程中處於活動狀態。 解決方案在這里討論。

例如,在此方法中使用OpenGL上下文更為正確:

/**
 * Called back by the animator to perform per-frame rendering.
 */
@Override
public void display(GLAutoDrawable glAutoDrawable) {
    GL2 gl = glAutoDrawable.getGL().getGL2();   // get the OpenGL 2 graphics context

    gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);    // clear background
    gl.glLoadIdentity();                    // reset the model-view matrix

    // Rendering code
    /* There you can fill the whole window with a color, 
       or draw something more beautiful... */

    gl.glFlush();

    /* Here goes testing cycle from mouseClicked(); and it works! */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM