这节课NeHe课程向我们介绍了如何读取帧缓存中的像素值,并把 它作为场景中的纹理加载到几何体上。也就是我们常说的渲染到纹理(Render To Texture)功能,也称纹理烘培。这一功能主要有两个作用:第一是实现场景离屏渲染之后的后置处理;第二是实现多种不同场景的融合显示效果。
首先创建我们场景中需要显示的Helix模型,代码如下:
osg::Geode* createHelix()
接下来我们需要将这个模型加载的场景写到纹理中去,在OSG中可以通过创建渲染到纹理的相机完成这样的操作:
osg::Camera* createRenderToTextureCamera(int w, int h) { osg::Camera *rtt = new osg::Camera; rtt->setClearColor(osg::Vec4(0.0f, 0.0f, 0.5f, 0.5)); rtt->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); rtt->setReferenceFrame(osg::Transform::ABSOLUTE_RF); rtt->setViewport(0, 0, w, h); rtt->setRenderOrder(osg::Camera::PRE_RENDER); rtt->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); rtt->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(640)/static_cast<double>(480), 0.1f, 100.0f ); rtt->setViewMatrixAsLookAt(osg::Vec3d(0, 5, 50), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0)); osg::MatrixTransform *zoomMT = new osg::MatrixTransform; zoomMT->setMatrix(osg::Matrix::translate(0,0,-50)); osg::MatrixTransform *xRotMT = new osg::MatrixTransform; xRotMT->addUpdateCallback(new RotAxisCallback(osg::X_AXIS, 0.02)); osg::MatrixTransform *yRotMT = new osg::MatrixTransform; yRotMT->addUpdateCallback(new RotAxisCallback(osg::Y_AXIS, 0.01)); zoomMT->addChild(xRotMT); xRotMT->addChild(yRotMT); yRotMT->addChild(createHelix()); rtt->addChild(zoomMT); return rtt; }通过设置相机渲染方式是PRE_RENDER可以保证在渲染其他场景之前先渲染这个相机中的场景,并通过下面的操作将其保存到纹理之中:
g_Texture = createTexture(128,128); osg::Camera *rttCamera = createRenderToTextureCamera(128, 128); rttCamera->attach(osg::Camera::COLOR_BUFFER, g_Texture);这样我们需要的纹理就创建好了。
接下来加载使用纹理的几何体:
osg::Node* createBlur(int times, float inc)同时在几何体的更新中不断修改纹理坐标的位置,实现微小的偏移,整个场景看起来像一种运动模糊的效果:
class BlurGeometryUpdateCallback : public osg::Drawable::UpdateCallback
附:本课源码(源码中可能存在错误和不足,仅供参考)
#include "../osgNeHe.h" #include <QtCore/QTimer> #include <QtGui/QApplication> #include <QtGui/QVBoxLayout> #include <osgViewer/Viewer> #include <osgDB/ReadFile> #include <osgQt/GraphicsWindowQt> #include <osg/MatrixTransform> #include <osg/AnimationPath> #include <osg/Material> #include <osg/LightSource> #include <osg/BlendFunc> #include <osg/Texture2D> #include <osg/State> float angle; float vertexes[4][3]; float normal[3]; osg::Texture2D *g_Texture; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// void ReduceToUnit(float vector[3]) // Reduces A Normal Vector (3 Coordinates) { // To A Unit Normal Vector With A Length Of One. float length; // Holds Unit Length // Calculates The Length Of The Vector length = (float)sqrt((vector[0]*vector[0]) + (vector[1]*vector[1]) + (vector[2]*vector[2])); if(length == 0.0f) // Prevents Divide By 0 Error By Providing length = 1.0f; // An Acceptable Value For Vectors To Close To 0. vector[0] /= length; // Dividing Each Element By vector[1] /= length; // The Length Results In A vector[2] /= length; // Unit Normal Vector. } void calcNormal(float v[3][3], float out[3]) // Calculates Normal For A Quad Using 3 Points { float v1[3],v2[3]; // Vector 1 (x,y,z) & Vector 2 (x,y,z) static const int x = 0; // Define X Coord static const int y = 1; // Define Y Coord static const int z = 2; // Define Z Coord // Finds The Vector Between 2 Points By Subtracting // The x,y,z Coordinates From One Point To Another. // Calculate The Vector From Point 1 To Point 0 v1[x] = v[0][x] - v[1][x]; // Vector 1.x=Vertex[0].x-Vertex[1].x v1[y] = v[0][y] - v[1][y]; // Vector 1.y=Vertex[0].y-Vertex[1].y v1[z] = v[0][z] - v[1][z]; // Vector 1.z=Vertex[0].y-Vertex[1].z // Calculate The Vector From Point 2 To Point 1 v2[x] = v[1][x] - v[2][x]; // Vector 2.x=Vertex[0].x-Vertex[1].x v2[y] = v[1][y] - v[2][y]; // Vector 2.y=Vertex[0].y-Vertex[1].y v2[z] = v[1][z] - v[2][z]; // Vector 2.z=Vertex[0].z-Vertex[1].z // Compute The Cross Product To Give Us A Surface Normal out[x] = v1[y]*v2[z] - v1[z]*v2[y]; // Cross Product For Y - Z out[y] = v1[z]*v2[x] - v1[x]*v2[z]; // Cross Product For X - Z out[z] = v1[x]*v2[y] - v1[y]*v2[x]; // Cross Product For X - Y ReduceToUnit(out); // Normalize The Vectors } class RotAxisCallback : public osg::NodeCallback { public: RotAxisCallback(const osg::Vec3& axis, double rotSpeed = 0.0, double currentAngle = 0.0) : _rotAxis(axis), _rotSpeed(rotSpeed), _currentAngle(currentAngle){ } virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { osg::MatrixTransform *rotMT = dynamic_cast<osg::MatrixTransform*>(node); if (!rotMT) return; _currentAngle += _rotSpeed; rotMT->setMatrix(osg::Matrix::rotate(_currentAngle, _rotAxis)); traverse(node, nv); } void setRotateSpeed(double speed) { _rotSpeed = speed; } double getRotateSpeed() const { return _rotSpeed; } double getCurrentAngle() const { return _currentAngle; } private: osg::Vec3 _rotAxis; double _currentAngle; double _rotSpeed; }; osg::Geode* createHelix() { GLfloat x; // Helix x Coordinate GLfloat y; // Helix y Coordinate GLfloat z; // Helix z Coordinate GLfloat phi; // Angle GLfloat theta; // Angle GLfloat v,u; // Angles GLfloat r = 1.5f; // Radius Of Twist int twists = 5; // 5 Twists osg::Geode *geode = new osg::Geode; osg::Geometry *geometry = new osg::Geometry; osg::Vec3Array *vertexArray = new osg::Vec3Array; osg::Vec3Array *normalArray = new osg::Vec3Array; ////////////////////////////////////////////////////////////////////////// for(int phi=0; phi <= 360; phi+=20.0) // 360 Degrees In Steps Of 20 { for(int theta=0; theta<=360*twists; theta+=20.0) // 360 Degrees * Number Of Twists In Steps Of 20 { v=(phi/180.0f*3.142f); // Calculate Angle Of First Point ( 0 ) u=(theta/180.0f*3.142f); // Calculate Angle Of First Point ( 0 ) x=float(cos(u)*(2.0f+cos(v) ))*r; // Calculate x Position (1st Point) y=float(sin(u)*(2.0f+cos(v) ))*r; // Calculate y Position (1st Point) z=float((( u-(2.0f*3.142f)) + sin(v) ) * r); // Calculate z Position (1st Point) vertexes[0][0]=x; // Set x Value Of First Vertex vertexes[0][1]=y; // Set y Value Of First Vertex vertexes[0][2]=z; // Set z Value Of First Vertex v=(phi/180.0f*3.142f); // Calculate Angle Of Second Point ( 0 ) u=((theta+20)/180.0f*3.142f); // Calculate Angle Of Second Point ( 20 ) x=float(cos(u)*(2.0f+cos(v) ))*r; // Calculate x Position (2nd Point) y=float(sin(u)*(2.0f+cos(v) ))*r; // Calculate y Position (2nd Point) z=float((( u-(2.0f*3.142f)) + sin(v) ) * r); // Calculate z Position (2nd Point) vertexes[1][0]=x; // Set x Value Of Second Vertex vertexes[1][1]=y; // Set y Value Of Second Vertex vertexes[1][2]=z; // Set z Value Of Second Vertex v=((phi+20)/180.0f*3.142f); // Calculate Angle Of Third Point ( 20 ) u=((theta+20)/180.0f*3.142f); // Calculate Angle Of Third Point ( 20 ) x=float(cos(u)*(2.0f+cos(v) ))*r; // Calculate x Position (3rd Point) y=float(sin(u)*(2.0f+cos(v) ))*r; // Calculate y Position (3rd Point) z=float((( u-(2.0f*3.142f)) + sin(v) ) * r); // Calculate z Position (3rd Point) vertexes[2][0]=x; // Set x Value Of Third Vertex vertexes[2][1]=y; // Set y Value Of Third Vertex vertexes[2][2]=z; // Set z Value Of Third Vertex v=((phi+20)/180.0f*3.142f); // Calculate Angle Of Fourth Point ( 20 ) u=((theta)/180.0f*3.142f); // Calculate Angle Of Fourth Point ( 0 ) x=float(cos(u)*(2.0f+cos(v) ))*r; // Calculate x Position (4th Point) y=float(sin(u)*(2.0f+cos(v) ))*r; // Calculate y Position (4th Point) z=float((( u-(2.0f*3.142f)) + sin(v) ) * r); // Calculate z Position (4th Point) vertexes[3][0]=x; // Set x Value Of Fourth Vertex vertexes[3][1]=y; // Set y Value Of Fourth Vertex vertexes[3][2]=z; // Set z Value Of Fourth Vertex calcNormal(vertexes,normal); // Calculate The Quad Normal normalArray->push_back(osg::Vec3(normal[0],normal[1],normal[2])); normalArray->push_back(osg::Vec3(normal[0],normal[1],normal[2])); normalArray->push_back(osg::Vec3(normal[0],normal[1],normal[2])); normalArray->push_back(osg::Vec3(normal[0],normal[1],normal[2])); // Render The Quad vertexArray->push_back(osg::Vec3(vertexes[0][0],vertexes[0][1],vertexes[0][2])); vertexArray->push_back(osg::Vec3(vertexes[1][0],vertexes[1][1],vertexes[1][2])); vertexArray->push_back(osg::Vec3(vertexes[2][0],vertexes[2][1],vertexes[2][2])); vertexArray->push_back(osg::Vec3(vertexes[3][0],vertexes[3][1],vertexes[3][2])); } } ////////////////////////////////////////////////////////////////////////// geometry->setVertexArray(vertexArray); geometry->setNormalArray(normalArray, osg::Array::BIND_PER_VERTEX); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, vertexArray->size())); osg::Material *helixMat = new osg::Material; helixMat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.4f,0.2f,0.8f,1.0f)); helixMat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(0.4f,0.2f,0.8f,1.0f)); helixMat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0f,1.0f,1.0f,1.0f)); helixMat->setShininess(osg::Material::FRONT, 128.0f); geometry->getOrCreateStateSet()->setAttributeAndModes(helixMat); geometry->getOrCreateStateSet()->setMode(GL_LIGHT0, osg::StateAttribute::ON); geode->addDrawable(geometry); return geode; } class ViewerWidget : public QWidget, public osgViewer::Viewer { public: ViewerWidget(osg::Node *scene = NULL) { QWidget* renderWidget = getRenderWidget( createGraphicsWindow(0,0,640,480), scene); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(renderWidget); layout->setContentsMargins(0, 0, 0, 1); setLayout( layout ); connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) ); _timer.start( 10 ); } QWidget* getRenderWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene ) { osg::Camera* camera = this->getCamera(); camera->setGraphicsContext( gw ); const osg::GraphicsContext::Traits* traits = gw->getTraits(); camera->setClearColor( osg::Vec4(0.0, 0.0, 0.0, 0.5) ); camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) ); camera->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 0.1f, 100.0f ); camera->setViewMatrixAsLookAt(osg::Vec3d(0, 5, 50), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0)); this->setSceneData( scene ); return gw->getGLWidget(); } osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false ) { osg::DisplaySettings* ds = osg::DisplaySettings::instance().get(); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->windowName = name; traits->windowDecoration = windowDecoration; traits->x = x; traits->y = y; traits->width = w; traits->height = h; traits->doubleBuffer = true; traits->alpha = ds->getMinimumNumAlphaBits(); traits->stencil = ds->getMinimumNumStencilBits(); traits->sampleBuffers = ds->getMultiSamples(); traits->samples = ds->getNumMultiSamples(); return new osgQt::GraphicsWindowQt(traits.get()); } virtual void paintEvent( QPaintEvent* event ) { frame(); } protected: QTimer _timer; }; class BlurGeometryUpdateCallback : public osg::Drawable::UpdateCallback { public: BlurGeometryUpdateCallback(int renderTimes, float inc) : _times(renderTimes), _inc(inc){ } void update(osg::NodeVisitor*, osg::Drawable* d) { osg::Geometry *geometry = dynamic_cast<osg::Geometry*>(d); if (!geometry) return; osg::Vec2Array *texArray = dynamic_cast<osg::Vec2Array*>(geometry->getTexCoordArray(0)); if(!texArray) return; osg::Vec4Array *colorArray = dynamic_cast<osg::Vec4Array*>(geometry->getColorArray()); if(!colorArray) return; float spost = 0.0f; float alphainc = 0.9f / _times; float alpha = 0.2f; alphainc = alpha / _times; texArray->clear(); colorArray->clear(); for (int num = 0;num < _times;num++) { colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); texArray->push_back(osg::Vec2(0+spost,1-spost)); colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); texArray->push_back(osg::Vec2(0+spost,0+spost)); colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); texArray->push_back(osg::Vec2(1-spost,0+spost)); colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); texArray->push_back(osg::Vec2(1-spost,1-spost)); spost += _inc; alpha = alpha - alphainc; } texArray->dirty(); colorArray->dirty(); } int _times; float _inc; }; osg::Node* createBlur(int times, float inc) { float spost = 0.0f; float alphainc = 0.9f / times; float alpha = 0.2f; alphainc = alpha / times; osg::BlendFunc *blendFunc = new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE); osg::Geode *geode = new osg::Geode; osg::Geometry *geometry = new osg::Geometry; geometry->setUpdateCallback(new BlurGeometryUpdateCallback(times, inc)); osg::Vec2Array *vertexArray = new osg::Vec2Array; osg::Vec2Array *texArray = new osg::Vec2Array; osg::Vec4Array *colorArray = new osg::Vec4Array; for (int num = 0;num < times;num++) { colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); vertexArray->push_back(osg::Vec2(0,0)); texArray->push_back(osg::Vec2(0+spost,1-spost)); colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); vertexArray->push_back(osg::Vec2(0,480)); texArray->push_back(osg::Vec2(0+spost,0+spost)); colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); vertexArray->push_back(osg::Vec2(640,480)); texArray->push_back(osg::Vec2(1-spost,0+spost)); colorArray->push_back(osg::Vec4(1.0f, 1.0f, 1.0f, alpha)); vertexArray->push_back(osg::Vec2(640,0)); texArray->push_back(osg::Vec2(1-spost,1-spost)); } geometry->setVertexArray(vertexArray); geometry->setTexCoordArray(0, texArray, osg::Array::BIND_PER_VERTEX); geometry->setColorArray(colorArray, osg::Array::BIND_PER_VERTEX); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, vertexArray->size())); geometry->getOrCreateStateSet()->setAttributeAndModes(blendFunc); geometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, g_Texture); geometry->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); geometry->getOrCreateStateSet()->setMode(GL_LIGHT0, osg::StateAttribute::ON); geode->addDrawable(geometry); return geode; } osg::Camera* createBlurHUD() { osg::Camera* camera = new osg::Camera; camera->setProjectionMatrix(osg::Matrix::ortho2D(0,640,0,480)); camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); camera->setViewMatrix(osg::Matrix::identity()); camera->setRenderOrder(osg::Camera::POST_RENDER); camera->setAllowEventFocus(false); camera->addChild(createBlur(25, 0.02f)); return camera; } osg::Texture2D* createTexture(int w, int h) { osg::Texture2D *texture = new osg::Texture2D; texture->setInternalFormat(GL_RGBA); texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); texture->setTextureSize(w,h); return texture; } osg::Camera* createRenderToTextureCamera(int w, int h) { osg::Camera *rtt = new osg::Camera; rtt->setClearColor(osg::Vec4(0.0f, 0.0f, 0.5f, 0.5)); rtt->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); rtt->setReferenceFrame(osg::Transform::ABSOLUTE_RF); rtt->setViewport(0, 0, w, h); rtt->setRenderOrder(osg::Camera::PRE_RENDER); rtt->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); rtt->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(640)/static_cast<double>(480), 0.1f, 100.0f ); rtt->setViewMatrixAsLookAt(osg::Vec3d(0, 5, 50), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0)); osg::MatrixTransform *zoomMT = new osg::MatrixTransform; zoomMT->setMatrix(osg::Matrix::translate(0,0,-50)); osg::MatrixTransform *xRotMT = new osg::MatrixTransform; xRotMT->addUpdateCallback(new RotAxisCallback(osg::X_AXIS, 0.02)); osg::MatrixTransform *yRotMT = new osg::MatrixTransform; yRotMT->addUpdateCallback(new RotAxisCallback(osg::Y_AXIS, 0.01)); zoomMT->addChild(xRotMT); xRotMT->addChild(yRotMT); yRotMT->addChild(createHelix()); rtt->addChild(zoomMT); return rtt; } osg::Node* buildScene() { GLfloat light0pos[4]= {0.0f, 5.0f, 10.0f, 1.0f}; GLfloat light0ambient[4]= {0.2f, 0.2f, 0.2f, 1.0f}; GLfloat light0diffuse[4]= {0.3f, 0.3f, 0.3f, 1.0f}; GLfloat light0specular[4]={0.8f, 0.8f, 0.8f, 1.0f}; osg::Group *root = new osg::Group; osg::Light *light = new osg::Light; light->setLightNum(0); light->setAmbient(osg::Vec4(light0ambient[0],light0ambient[1],light0ambient[2],light0ambient[3])); light->setDiffuse(osg::Vec4(light0diffuse[0],light0diffuse[1],light0diffuse[2],light0diffuse[3])); light->setPosition(osg::Vec4(light0pos[0], light0pos[1],light0pos[2],light0pos[3])); light->setSpecular(osg::Vec4(light0specular[0],light0specular[1],light0specular[2],light0specular[3])); osg::LightSource *lightSource = new osg::LightSource; lightSource->setLight(light); root->addChild(lightSource); osg::MatrixTransform *zoomMT = new osg::MatrixTransform; zoomMT->setMatrix(osg::Matrix::translate(0,0,-50)); osg::MatrixTransform *xRotMT = new osg::MatrixTransform; xRotMT->addUpdateCallback(new RotAxisCallback(osg::X_AXIS, 0.02)); osg::MatrixTransform *yRotMT = new osg::MatrixTransform; yRotMT->addUpdateCallback(new RotAxisCallback(osg::Y_AXIS, 0.01)); zoomMT->addChild(xRotMT); xRotMT->addChild(yRotMT); yRotMT->addChild(createHelix()); g_Texture = createTexture(128,128); osg::Camera *rttCamera = createRenderToTextureCamera(128, 128); rttCamera->attach(osg::Camera::COLOR_BUFFER, g_Texture); root->addChild(rttCamera); root->addChild(zoomMT); root->addChild(createBlurHUD()); return root; } int main( int argc, char** argv ) { QApplication app(argc, argv); ViewerWidget* viewWidget = new ViewerWidget(buildScene()); viewWidget->setGeometry( 100, 100, 640, 480 ); viewWidget->show(); return app.exec(); }