glReadPixels()返回零数组
问题描述:
我使用JOGL与OpenGL一起工作,我无法获得像素颜色。方法glReadPixels()总是返回一个全零的数组。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()的程序侥幸。
答
问题是我打电话getPixel()
在mouseClicked()
(即从另一个线程)。 OpenGL上下文一次只能在单个线程中处于活动状态。解决方案讨论here。
例如,它是更正确的使用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,归结代码以一个[SSCCE](http://sscce.org/)并对其进行编辑进入问题。随机Dropboxes死亡,SO永远。 – genpfault
@genpfault,我将代码缩短到SSCCE后发现问题的根源。我应该重新上传代码并将其替换为正在运行的项目吗? – naXa
太棒了!这是SSCCE真棒的原因之一:)你应该在错误的SSCCE中编辑问题,然后将修正的SSCCE编辑到你的答案中。 – genpfault