几帧后,LWJGL在glReadPixels上崩溃
问题描述:
我正在使用LWJGL向渲染缓冲区的屏幕外帧缓冲区渲染三角形。渲染场景后,我使用glReadPixels
将渲染缓冲区中的数据读出到RAM中。前几帧很好,但程序崩溃了(SEGFAULT,或SIGABRT,...)。几帧后,LWJGL在glReadPixels上崩溃
我在这里做错了什么?
//Create memory buffer in RAM to copy frame from GPU to.
ByteBuffer buf = BufferUtils.createByteBuffer(3*width*height);
while(true){
// Set framebuffer, clear screen, render objects, wait for render to finish, ...
...
//Read frame from GPU to RAM
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buf);
//Move cursor in buffer back to the begin and copy the contents to the java image
buf.position(0);
buf.get(imgBackingByteArray);
//Use buffer
...
}
答
使用
glReadPixels
,ByteBuffer.get()
,或基本上以任何方式访问的ByteBuffer,改变指针在缓冲器中的当前位置。
这里发生的是:
- 缓冲区的位置最初为零。
- 呼叫到
glReadPixels
拷贝从GPU到缓冲区中,从当前位置被改变到被写入到缓冲器的字节量的当前位置(= 0
) - 字节。
-
buf.position(0)
的位置为0。 -
buf.get()
拷贝在缓冲器中的字节复位到imgBackingByteArray
并且改变位置以所读取的字节量 - 循环的下一次迭代尝试将字节读入缓冲区,但当前位置在缓冲区的末尾,因此发生缓冲区溢出。这会触发崩溃。
解决方案:
//Make sure we start writing to the buffer at offset 0
buf.position(0);
//Read frame from GPU to RAM
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buf);
//Move cursor in buffer back to the begin and copy the contents to the java image
buf.position(0);
buf.get(imgBackingByteArray);