osg.FrameBufferObject
osg.FrameBufferObject
是OpenSceneGraph中用于创建和管理帧缓冲对象(FBO)的类。使用FBO可以在离屏内存中渲染图像,并在需要时将其传输到屏幕上。以下是 osg.FrameBufferObject
的一些重要特征和方法:
osg::Texture
对象将渲染结果附加到FBO。osg::Texture
附加到FBO,实现多重渲染目标(MRT)功能。osg::ref_ptr<osg::FrameBufferObject> fbo = new osg::FrameBufferObject();
创建一个FBO对象。
void fbo->setAttachment(osg::FrameBufferAttachment attachment, osg::Texture* texture);
将指定的 osg::Texture
对象作为FBO的一个附件,attachment参数可以是:
COLOR_ATTACHMENT0
,表示将texture附加到颜色缓冲区。DEPTH_ATTACHMENT
,表示将texture附加到深度缓冲区。STENCIL_ATTACHMENT
,表示将texture附加到模板缓冲区。void fbo->apply(osg::State& state) const;
将当前FBO绑定到OpenGL上下文中,即使后续渲染操作不再使用FBO,也需要调用此方法以解除FBO绑定。
void fbo->release(osg::State& state) const;
解除FBO对象与当前OpenGL上下文的绑定。
bool fbo->validate() const;
检查FBO对象的完整性和有效性,返回true表示FBO对象有效,返回false表示FBO对象无效。
osg::ref_ptr<osg::Node> scene = osgDB::readNodeFile("cessna.osgt");
osg::ref_ptr<osg::Texture2D> colorTexture = new osg::Texture2D;
colorTexture->setTextureSize(1024, 1024);
colorTexture->setInternalFormat(GL_RGBA);
colorTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
colorTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
osg::ref_ptr<osg::Texture2D> depthTexture = new osg::Texture2D;
depthTexture->setTextureSize(1024, 1024);
depthTexture->setInternalFormat(GL_DEPTH_COMPONENT);
depthTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
depthTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
osg::ref_ptr<osg::FrameBufferObject> fbo = new osg::FrameBufferObject;
fbo->setAttachment(osg::FrameBufferAttachment::COLOR_ATTACHMENT0, colorTexture);
fbo->setAttachment(osg::FrameBufferAttachment::DEPTH_ATTACHMENT, depthTexture);
osg::Camera* camera = new osg::Camera;
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
camera->setViewport(0, 0, 1024, 1024);
camera->setClearColor(osg::Vec4(0.2f, 0.2f, 0.6f, 1.0f));
camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
camera->attach(osg::Camera::COLOR_BUFFER0, colorTexture);
camera->attach(osg::Camera::DEPTH_BUFFER, depthTexture);
camera->addChild(scene.get());
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
viewer->setSceneData(camera);
viewer->realize();
while (!viewer->done())
{
viewer->frame();
}