Cuda: Write to depth buffer

After several tests, finally find how to write to the depth buffer (z-buffer).  The ultimate tip when writing the depth buffer:
Do NOT disable GL_DEPTH_TEST!!

Here are the codes (only showing codes related to the depth-buffer).  Thanks to my colleges for the references:

1. Create PBO and resources:

GLuint m_pbo_depth; 
cudaGraphicsResource *m_cuda_pbo_depth_resource;

void initPBO()
{
if (m_pbo) {
	// delete old buffer          
	CUDA_SAFE_CALL(cudaGraphicsUnregisterResource(m_cuda_pbo_resource));
	glDeleteBuffersARB(1, &m_pbo_depth);                    
}

glGenBuffersARB(1, &m_pbo_depth);

glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pbo_depth);
glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, imgWidth*imgHeight*sizeof(GLuint), 
0, GL_STREAM_DRAW_ARB);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

CUDA_SAFE_CALL(cudaGraphicsGLRegisterBuffer(&m_cuda_pbo_resource, m_pbo, 
cudaGraphicsMapFlagsNone ));
CUDA_SAFE_CALL(cudaGraphicsGLRegisterBuffer(&m_cuda_pbo_depth_resource, 
m_pbo_depth, cudaGraphicsMapFlagsNone ));

}         
2. Map PBO and call cuda
void executeKernel()
{
// map PBO to get CUDA device pointer        

uint *d_depth_buffer;
size_t num_bytes;
CUDA_SAFE_CALL(cudaGraphicsMapResources(1, &m_cuda_pbo_depth_resource, 0));
CUDA_SAFE_CALL(cudaGraphicsResourceGetMappedPointer((void **)&d_depth_buffer, 
&num_bytes, m_cuda_pbo_depth_resource));

     d_render<<<...>>>(..., d_depth_buffer);

CUDA_SAFE_CALL(cudaGraphicsUnmapResources(1, &m_cuda_pbo_depth_resource, 0));    
}
3. In the rendering step, write the depth pbo to the rendering depth buffer
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);
//	glDisable(GL_DEPTH_TEST); !!! cannot disable depth test
	glDepthFunc(GL_ALWAYS);

	// normalize matrix
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0); 

	// draw image from PBO
	glRasterPos2i(0, 0);

	// depth
	glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pbo_depth);
	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	glDrawPixels(vrParam.imgWidth, vrParam.imgHeight, 
GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
	glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);

	// recall matrix
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	glDepthFunc(GL_LESS);

0 comments: