glReadPixels in mousePressed

2019-02-25 05:45发布

I am trying to get the color of a pixel in JOGL when the user clicks on it. If I put the following code in the display method (coming from the GLEventListener), it works fine.

FloatBuffer buffer = FloatBuffer.allocate(4);

gl.glReadBuffer(GL3.GL_FRONT);
gl.glReadPixels(10, 10, 1, 1, GL3.GL_RGBA, GL3.GL_FLOAT, buffer);
float[] pixels = new float[3];
pixels = buffer.array();
float red = pixels[0];
float green = pixels[1];
float blue = pixels[2];
System.out.println(red + ", " + green + ", " + blue);

However, if I put my code in the mousePressed method, I get an invalid operation error when checking for success and the color returns black (0, 0, 0).

Is there a way to get this to work in my mousePressed method, or will I have to store the selected pixel, along with a boolean to indicate selection (so that I don't call glReadPixels every frame) and do the selection in the display method?

P.s. the (x,y) coords = (10,10) is just to make sure the selection is really inside my window (which it is, since the pixel color comes out correctly in the display method).

标签: opengl jogl
1条回答
贼婆χ
2楼-- · 2019-02-25 06:12

An OpenGL context can only be active in a single thread at a time, if your event handling for mouse presses comes on a different thread, you won't be able to properly query information from OpenGL at that time. Generally speaking, I would err on the side of reading the pixel value in the display function. If you want to avoid reading pixels every frame, you could keep track of the last location you read from, and only call glReadPixels if the position to read from has changed.

As datenwolf mentions, it is possible to deactivate and activate your context to access it across multiple threads, if you need to do so.

查看更多
登录 后发表回答