Java glReadPixels()返回零数组
我使用JOGL与OpenGL一起工作,但无法获得像素颜色。方法glReadPixels始终返回一个全零数组 我就是这样使用它的:Java glReadPixels()返回零数组,java,opengl,jogl,Java,Opengl,Jogl,我使用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,
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]);
}
在显示方法中重新绘制时,我用灰色填充窗口,然后在用户单击窗口中的任意位置时测试结果:
@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,即从另一个线程调用。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! */
}
-1、将你的代码归结为一个问题,并将其编辑成问题。“随机的Dropbox会消失,永远也不会消失。”genpfault,在我将代码缩短为SSCCE后,我找到了问题的根源。我应该重新加载代码并用一个工作项目替换它吗?太好了!这就是SSCCE很棒的原因之一:你应该在问题中编辑错误的SSCCE,然后在你的答案中编辑正确的SSCCE。