点击屏蔽,获取点击的图元,并用红色进行渲染。
具体的方法:分两步绘制
- 创建一个framebuffer,并链接一个颜色缓存和深度缓存,渲染时颜色缓存中保存的是像素所对应的物体的索引、物体部件的索引和渲染的图元的索引。物体索引和物体部件索引由程序传入着色器。使用深度缓存可以保证颜色缓存中保存的是距离近平面最近的图元的信息。
//像素信息结构体
struct PixelInfo {
GLuint ObjectID;
GLuint DrawID;
GLuint PrimID;
PixelInfo()
{
ObjectID = 0;
DrawID = 0;
PrimID = 0;
}
};
bool PickingTexture::Init(unsigned int WindowWidth, unsigned int WindowHeight)
{
// Create the FBO
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
// Create the texture object for the primitive information buffer
glGenTextures(1, &m_pickingTexture);
glBindTexture(GL_TEXTURE_2D, m_pickingTexture);
//注意texutre的格式要与像素信息结构体相匹配
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32UI, WindowWidth, WindowHeight, 0, GL_RGB_INTEGER, GL_UNSIGNED_INT, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pickingTexture, 0);
// Create the texture object for the depth buffer
glGenTextures(1, &m_depthTexture);
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
glReadBuffer(GL_NONE);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
// Verify that the FBO is correct
GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (Status != GL_FRAMEBUFFER_COMPLETE) {
printf("FB error, status: 0x%x\n", Status);
return false;
}
// Restore the default framebuffer
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);