Question

I use JOGL to work with OpenGL and I can't get a pixel color. Method glReadPixels() always returns an array of all zeros.

That's how I use it:

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]);
}

On redraw (in the display() method) I fill the window with a gray color and then test the result when user clicks anywhere in the window:

@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());
        }
}

But there is no output in the console. I've tested it on discrete and integrated graphics. Result has been the same.

Tell me what I'm doing wrong. Or share a working example, if you have by a fluke any program that uses JOGL and method glReadPixel().

Was it helpful?

Solution

The problem was that I was calling getPixel() in mouseClicked() (i.e. from another thread). An OpenGL context can only be active in a single thread at a time. Solutions are discussed here.

For example, it is more correct to use OpenGL context in this method:

/**
 * 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! */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top