OpenSceneGraph实现的NeHe OpenGL教程 - 第十九课_附录1

来源:互联网 发布:简明python教程 在线 编辑:程序博客网 时间:2024/06/11 14:45
  • 简介

在第十九课中我们使用NeHe教程中的方式实现了一个简单的粒子效果,在osg中也提供了一个专门处理粒子系统的库---osgParticle,下面我们就用osgParticle库来实现同样的效果。

  • 实现

在具体实现之前,我们先了解一下osgParticle,osgParticle的粒子系统主要的模块包括如下部分:


  • ParticleSystem粒子系统类,继承自osg::Drawable可绘制对象,用来管理粒子的绘制,它包含一个Particle的数组,Particle可以理解为很多粒子中其中的一个。

ParticleSystem利用粒子的模板来产生大量的粒子

  • Particle类,刚才已经解释了,Particle可以看做ParticleSystem的一个模板,ParticleSystem依据它产生大量的粒子
  • Emitter类:它包含三个部分(一个组合类):即Shooter(发射器:发射出粒子的速度和方向),Counter(计数器:每帧发射多少粒子)以及Placer(放置器:决定粒子初始位置在哪儿)
  • Program类:Program类里面包含一个Operator类的数组,用来存放一系列的操作,在对粒子进行渲染之前、渲染中以及渲染后都可以进行一些设置,包括粒子的方方面面(颜色、位置、生命、加速度等等),非常的灵活。我们需要自定义粒子的一些操作实际上是继承Operator类并重写里面的operator函数来完成粒子的一些自定义操作

粒子系统的基本操作过程可以参考osg示例解析之osgParticle,里面对粒子系统的设置过程进行了说明。

同样我们还是需要定义粒子结构体用来更新数据:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. struct Particle  
  2. {  
  3.     bool active;    
  4.     float life;  
  5.     float fade;  
  6.     float r;          
  7.     float g;  
  8.     float b;  
  9.     float x;  
  10.     float y;  
  11.     float z;  
  12.     float xi;      
  13.     float yi;      
  14.     float zi;  
  15.     float xg;  
  16.     float yg;  
  17.     float zg;  
  18. };  
设置particles的初始值与之前的代码一样

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. for (int i=0;  i<MaxParticles; i++)  
  2. {  
  3.     particles[i].active=true;  
  4.     particles[i].life=1.0f;  
  5.     particles[i].fade=float(rand()%100)/1000.0f+0.003f;   
  6.     particles[i].r=colors[int(i*(12.0/MaxParticles))][0];  
  7.     particles[i].g=colors[int(i*(12.0/MaxParticles))][1];  
  8.     particles[i].b=colors[int(i*(12.0/MaxParticles))][2];  
  9.     particles[i].xi=float((rand()%50)-26.0f)*10.0f;  
  10.     particles[i].yi=float((rand()%50)-25.0f)*10.0f;  
  11.     particles[i].zi=float((rand()%50)-25.0f)*10.0f;  
  12.     particles[i].xg=0.0f;     
  13.     particles[i].yg=-0.8f;  
  14.     particles[i].zg=0.0f;     
  15. }  
因为我们需要控制粒子的整个运行过程(产生的1000个粒子需要一直让我们来操作,这些粒子不会增加也不会减少,因此我把粒子的生命设置为永远"存活",并且当粒子数量达到1000个之后,就不在发射粒子(Counter设置为0)),这与osgParticle示例中的方式不一样,osgParticle会一直产生粒子。

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //设置粒子模板  
  2. osgParticle::Particle particleTemplate;  
  3. particleTemplate.setShape(osgParticle::Particle::QUAD_TRIANGLESTRIP);  
  4. //负值表示粒子永远不会"死亡"  
  5. particleTemplate.setLifeTime(-1);  
  6. particleTemplate.setPosition(osg::Vec3(0.0, 0.0, 0.0));  
  7. particleTemplate.setRadius(1.0f);  
[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //设置粒子系统的光照,纹理等(与普通的Drawable设置一样)  
  2. osgParticle::ParticleSystem *particleSystem = new osgParticle::ParticleSystem();  
  3. particleSystem->setDefaultAttributes("Data/Particle.bmp"falsefalse);  
  4. osg::BlendFunc *blendFunc = new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE);  
  5. particleSystem->getOrCreateStateSet()->setAttributeAndModes(blendFunc,osg::StateAttribute::ON);  
  6. particleSystem->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);  
  7. particleSystem->setDefaultParticleTemplate(particleTemplate);  
设置Emitter的各个参数:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. osgParticle::ModularEmitter *emitter = new osgParticle::ModularEmitter;  
  2. emitter->setParticleSystem(particleSystem);  
  3.   
  4. osgParticle::PointPlacer *placer = new osgParticle::PointPlacer;  
  5. placer->setCenter(0, 0, 0);  
  6. emitter->setPlacer(placer);  
  7.   
  8. osgParticle::RandomRateCounter *counter = new osgParticle::RandomRateCounter;  
  9. counter->setRateRange(1000, 1000);  
  10. emitter->setCounter(counter);  
  11. g_counter = counter; //为了设置1000个粒子之后停止发射  
  12.   
  13. osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter;  
  14. emitter->setShooter(shooter);  
设置Program来定义自定义的操作

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. osgParticle::ModularProgram *program = new osgParticle::ModularProgram;  
  2. program->setParticleSystem(particleSystem);  
  3.   
  4. ColorOption *co = new ColorOption;  
  5. program->addOperator(co);  
在ColorOption中完成了对所有粒子的位置和颜色的更新:(更新方式使用NeHe教程中的方式)

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. void beginOperate(osgParticle::Program *pro)  
最后把粒子系统添加到一个Group节点中并设置到场景里面:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. osg::Geode *particleGeode = new osg::Geode;  
  2. particleGeode->addDrawable(particleSystem);  
  3.   
  4. osg::Group *particleEffect = new osg::Group;  
  5. particleEffect->addChild(emitter);  
  6. particleEffect->addChild(particleGeode);  
  7. particleEffect->addChild(program);  
  8. particleEffect->addChild(psu);  
当场景中的粒子数量到达1000之后,停止产生新的粒子:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. osgParticle::ParticleSystem *ps = pro->getParticleSystem();  
  2. if (ps->numParticles() >= MaxParticles)  
  3. {  
  4.     g_counter->setRateRange(0,0);  
  5. }  

键盘的交互部分和第十九课中的代码类似,详细部分参看本课的完整代码。

编译运行程序:


附:本课源码(源码中可能存在错误和不足,仅供参考)

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include "../osgNeHe.h"  
  2.   
  3. #include <QtCore/QTimer>  
  4. #include <QtGui/QApplication>  
  5. #include <QtGui/QVBoxLayout>  
  6.   
  7. #include <osgViewer/Viewer>  
  8. #include <osgDB/ReadFile>  
  9. #include <osgQt/GraphicsWindowQt>  
  10.   
  11. #include <osg/MatrixTransform>  
  12. #include <osg/BlendFunc>  
  13.   
  14. // osgParticle Related Header Files  
  15. #include <osgParticle/Particle>  
  16. #include <osgParticle/ParticleSystem>  
  17. #include <osgParticle/ParticleSystemUpdater>  
  18. #include <osgParticle/ModularEmitter>  
  19. #include <osgParticle/ModularProgram>  
  20. #include <osgParticle/RandomRateCounter>  
  21. #include <osgParticle/PointPlacer>  
  22. #include <osgParticle/SectorPlacer>  
  23. #include <osgParticle/RadialShooter>  
  24. #include <osgParticle/AccelOperator>  
  25. #include <osgParticle/FluidFrictionOperator>  
  26.   
  27.   
  28. //////////////////////////////////////////////////////////////////////////  
  29. //  
  30. //////////////////////////////////////////////////////////////////////////  
  31. const int MaxParticles = 1000;  
  32. float slowdown = 2.0f;  
  33. float xspeed;  
  34. float yspeed;  
  35. float zoom = -40.0f;  
  36. GLuint delay;  
  37. int col;  
  38. bool g_restart = false;  
  39.   
  40. struct Particle  
  41. {  
  42.     bool active;    
  43.     float life;  
  44.     float fade;  
  45.     float r;          
  46.     float g;  
  47.     float b;  
  48.     float x;  
  49.     float y;  
  50.     float z;  
  51.     float xi;      
  52.     float yi;      
  53.     float zi;  
  54.     float xg;  
  55.     float yg;  
  56.     float zg;  
  57. };  
  58.   
  59. Particle particles[MaxParticles];  
  60.   
  61. static GLfloat colors[12][4] =  
  62. {  
  63.     {1.0f,0.5f,0.5f, 1.0f},{1.0f,0.75f,0.5f, 1.0f},{1.0f,1.0f,0.5f, 1.0f},{0.75f,1.0f,0.5f, 1.0f},  
  64.     {0.5f,1.0f,0.5f, 1.0f},{0.5f,1.0f,0.75f, 1.0f},{0.5f,1.0f,1.0f, 1.0f},{0.5f,0.75f,1.0f, 1.0f},  
  65.     {0.5f,0.5f,1.0f, 1.0f},{0.75f,0.5f,1.0f,1.0f},{1.0f,0.5f,1.0f, 1.0f},{1.0f,0.5f,0.75f, 1.0f}  
  66. };  
  67.   
  68.   
  69.   
  70. //////////////////////////////////////////////////////////////////////////  
  71.   
  72. //////////////////////////////////////////////////////////////////////////  
  73. //Particle Manipulator  
  74. class ParticleEventHandler : public osgGA::GUIEventHandler  
  75. {  
  76.   
  77. public:  
  78.     ParticleEventHandler(){}  
  79.   
  80.     virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)  
  81.     {  
  82.         osgViewer::Viewer *viewer = dynamic_cast<osgViewer::Viewer*>(&aa);  
  83.         if (!viewer)  
  84.             return false;  
  85.         if (!viewer->getSceneData())  
  86.             return false;  
  87.         if (ea.getHandled())   
  88.             return false;  
  89.   
  90.         switch(ea.getEventType())  
  91.         {  
  92.         case(osgGA::GUIEventAdapter::KEYDOWN):  
  93.             {  
  94.                 if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Tab)  
  95.                 {     
  96.                     g_restart = true;  
  97.                 }  
  98.   
  99.                 if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Up)  
  100.                 {  
  101.                     if ((yspeed<200))   
  102.                         yspeed+=1.0f;             
  103.                 }  
  104.   
  105.                 if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Down)  
  106.                 {  
  107.                     if ((yspeed>-200))   
  108.                         yspeed-=1.0f;  
  109.                 }  
  110.   
  111.                 if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Left)  
  112.                 {  
  113.                     if ((xspeed>-200))   
  114.                         xspeed-=1.0f;  
  115.                 }  
  116.   
  117.                 if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Right)  
  118.                 {  
  119.                     if ((xspeed<200))   
  120.                         xspeed+=1.0f;  
  121.                 }  
  122.             }  
  123.         defaultbreak;  
  124.         }  
  125.         return false;  
  126.     }  
  127. };  
  128.   
  129.   
  130. class ViewerWidget : public QWidget, public osgViewer::Viewer  
  131. {  
  132. public:  
  133.     ViewerWidget(osg::Node *scene = NULL)  
  134.     {  
  135.         QWidget* renderWidget = getRenderWidget( createGraphicsWindow(0,0,100,100), scene);  
  136.   
  137.         QVBoxLayout* layout = new QVBoxLayout;  
  138.         layout->addWidget(renderWidget);  
  139.         layout->setContentsMargins(0, 0, 0, 1);  
  140.         setLayout( layout );  
  141.   
  142.         connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );  
  143.         _timer.start( 10 );  
  144.     }  
  145.   
  146.     QWidget* getRenderWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene )  
  147.     {  
  148.         osg::Camera* camera = this->getCamera();  
  149.         camera->setGraphicsContext( gw );  
  150.   
  151.         const osg::GraphicsContext::Traits* traits = gw->getTraits();  
  152.   
  153.         camera->setClearColor( osg::Vec4(0.0, 0.0, 0.0, 0.0) );  
  154.         camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );  
  155.         camera->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 0.1f, 100.0f );  
  156.         camera->setViewMatrixAsLookAt(osg::Vec3d(0, 0, 1), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0));  
  157.   
  158.         this->setSceneData( scene );  
  159.         addEventHandler(new ParticleEventHandler);  
  160.   
  161.         return gw->getGLWidget();  
  162.     }  
  163.   
  164.     osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name=""bool windowDecoration=false )  
  165.     {  
  166.         osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();  
  167.         osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;  
  168.         traits->windowName = name;  
  169.         traits->windowDecoration = windowDecoration;  
  170.         traits->x = x;  
  171.         traits->y = y;  
  172.         traits->width = w;  
  173.         traits->height = h;  
  174.         traits->doubleBuffer = true;  
  175.         traits->alpha = ds->getMinimumNumAlphaBits();  
  176.         traits->stencil = ds->getMinimumNumStencilBits();  
  177.         traits->sampleBuffers = ds->getMultiSamples();  
  178.         traits->samples = ds->getNumMultiSamples();  
  179.   
  180.         return new osgQt::GraphicsWindowQt(traits.get());  
  181.     }  
  182.   
  183.     virtual void paintEvent( QPaintEvent* event )  
  184.     {   
  185.         frame();   
  186.     }  
  187.   
  188. protected:  
  189.   
  190.     QTimer _timer;  
  191. };  
  192.   
  193. osgParticle::RandomRateCounter *g_counter = NULL;  
  194. //////////////////////////////////////////////////////////////////////////  
  195.   
  196. class ColorOption : public osgParticle::Operator  
  197. {  
  198. public:  
  199.     ColorOption()   
  200.         : osgParticle::Operator(){}  
  201.   
  202.     ColorOption(const ColorOption &copy, const osg::CopyOp &copyop = osg::CopyOp::SHALLOW_COPY)  
  203.         : osgParticle::Operator(copy, copyop){}  
  204.   
  205.     META_Object(osgParticle, ColorOption);  
  206.   
  207.     void beginOperate(osgParticle::Program *pro)  
  208.     {  
  209.         osgParticle::ParticleSystem *ps = pro->getParticleSystem();  
  210.         if(!ps)  
  211.             return;  
  212.   
  213.         if (ps->numParticles() >= MaxParticles)  
  214.         {  
  215.             g_counter->setRateRange(0,0);  
  216.         }  
  217.         //如果按下Tab键  
  218.         if (g_restart) {  
  219.             osgParticle::ParticleSystem *ps = pro->getParticleSystem();  
  220.             if (!ps)  
  221.                 return;  
  222.               
  223.             for (unsigned i = 0; i < ps->numParticles(); ++i)  
  224.             {  
  225.                 particles[i].x=0.0f;  
  226.                 particles[i].y=0.0f;  
  227.                 particles[i].z=0.0f;  
  228.                 particles[i].xi=float((rand()%50)-26.0f)*10.0f;  
  229.                 particles[i].yi=float((rand()%50)-25.0f)*10.0f;  
  230.                 particles[i].zi=float((rand()%50)-25.0f)*10.0f;  
  231.             }  
  232.   
  233.             g_restart = false;  
  234.         } else {  
  235.   
  236.             for (int i = 0; i < ps->numParticles(); ++i)  
  237.             {  
  238.                 float x=particles[i].x;   
  239.                 float y=particles[i].y;  
  240.                 float z=particles[i].z+zoom;  
  241.                 ps->getParticle(i)->setPosition(osg::Vec3(x,y,z));  
  242.                 osg::Vec4 color(particles[i].r,particles[i].g,particles[i].b,particles[i].life);  
  243.                 ps->getParticle(i)->setColorRange(osgParticle::rangev4(color, color));  
  244.   
  245.                 particles[i].x+=particles[i].xi/(slowdown*1000);  
  246.                 particles[i].y+=particles[i].yi/(slowdown*1000);  
  247.                 particles[i].z+=particles[i].zi/(slowdown*1000);  
  248.   
  249.                 particles[i].xi+=particles[i].xg;  
  250.                 particles[i].yi+=particles[i].yg;  
  251.                 particles[i].zi+=particles[i].zg;  
  252.                 particles[i].life-=particles[i].fade;  
  253.   
  254.                 if (particles[i].life<0.0f)  
  255.                 {  
  256.                     particles[i].life=1.0f;  
  257.                     particles[i].fade=float(rand()%100)/1000.0f+0.003f;   
  258.                     particles[i].x=0.0f;  
  259.                     particles[i].y=0.0f;  
  260.                     particles[i].z=0.0f;  
  261.                     particles[i].xi=xspeed+float((rand()%60)-32.0f);  
  262.                     particles[i].yi=yspeed+float((rand()%60)-30.0f);  
  263.                     particles[i].zi=float((rand()%60)-30.0f);  
  264.                     particles[i].r=colors[col][0];  
  265.                     particles[i].g=colors[col][1];  
  266.                     particles[i].b=colors[col][2];  
  267.                 }  
  268.             }  
  269.         }  
  270.     }  
  271.   
  272.     void operate (osgParticle::Particle *P, double dt)  
  273.     {  
  274.           
  275.     }  
  276. };  
  277.   
  278.   
  279. osg::Node*  buildScene()  
  280. {  
  281.   
  282.     //////////////////////////////////////////////////////////////////////////  
  283.     for (int i=0;  i<MaxParticles; i++)  
  284.     {  
  285.         particles[i].active=true;  
  286.         particles[i].life=1.0f;  
  287.         particles[i].fade=float(rand()%100)/1000.0f+0.003f;   
  288.         particles[i].r=colors[int(i*(12.0/MaxParticles))][0];  
  289.         particles[i].g=colors[int(i*(12.0/MaxParticles))][1];  
  290.         particles[i].b=colors[int(i*(12.0/MaxParticles))][2];  
  291.         particles[i].xi=float((rand()%50)-26.0f)*10.0f;  
  292.         particles[i].yi=float((rand()%50)-25.0f)*10.0f;  
  293.         particles[i].zi=float((rand()%50)-25.0f)*10.0f;  
  294.         particles[i].xg=0.0f;     
  295.         particles[i].yg=-0.8f;  
  296.         particles[i].zg=0.0f;     
  297.     }  
  298.   
  299.     //////////////////////////////////////////////////////////////////////////  
  300.   
  301.     //设置粒子模板  
  302.     osgParticle::Particle particleTemplate;  
  303.     particleTemplate.setShape(osgParticle::Particle::QUAD_TRIANGLESTRIP);  
  304.     //负值表示粒子永远不会"死亡"  
  305.     particleTemplate.setLifeTime(-1);  
  306.     particleTemplate.setPosition(osg::Vec3(0.0, 0.0, 0.0));  
  307.     particleTemplate.setRadius(1.0f);  
  308.       
  309.     //设置粒子系统  
  310.     osgParticle::ParticleSystem *particleSystem = new osgParticle::ParticleSystem();  
  311.     particleSystem->setDefaultAttributes("Data/Particle.bmp"falsefalse);  
  312.     osg::BlendFunc *blendFunc = new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE);  
  313.     particleSystem->getOrCreateStateSet()->setAttributeAndModes(blendFunc,osg::StateAttribute::ON);  
  314.     particleSystem->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);  
  315.     particleSystem->setDefaultParticleTemplate(particleTemplate);  
  316.       
  317.     osgParticle::ModularEmitter *emitter = new osgParticle::ModularEmitter;  
  318.     emitter->setParticleSystem(particleSystem);  
  319.   
  320.     osgParticle::PointPlacer *placer = new osgParticle::PointPlacer;  
  321.     placer->setCenter(0, 0, 0);  
  322.     emitter->setPlacer(placer);  
  323.       
  324.     osgParticle::RandomRateCounter *counter = new osgParticle::RandomRateCounter;  
  325.     counter->setRateRange(1000, 1000);  
  326.     emitter->setCounter(counter);  
  327.     g_counter = counter;  
  328.   
  329.     osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter;  
  330.     emitter->setShooter(shooter);  
  331.   
  332.     osgParticle::ModularProgram *program = new osgParticle::ModularProgram;  
  333.     program->setParticleSystem(particleSystem);  
  334.   
  335.     ColorOption *co = new ColorOption;  
  336.     program->addOperator(co);  
  337.   
  338.     osgParticle::ParticleSystemUpdater *psu = new osgParticle::ParticleSystemUpdater;  
  339.     psu->addParticleSystem(particleSystem);  
  340.   
  341.     osg::Geode *particleGeode = new osg::Geode;  
  342.     particleGeode->addDrawable(particleSystem);  
  343.   
  344.     osg::Group *particleEffect = new osg::Group;  
  345.     particleEffect->addChild(emitter);  
  346.     particleEffect->addChild(particleGeode);  
  347.     particleEffect->addChild(program);  
  348.     particleEffect->addChild(psu);  
  349.   
  350.     osg::Group *root = new osg::Group;  
  351.     root->addChild(particleEffect);  
  352.   
  353.     return root;  
  354. }  
  355.   
  356.   
  357.   
  358. int main( int argc, char** argv )  
  359. {  
  360.     QApplication app(argc, argv);  
  361.     ViewerWidget* viewWidget = new ViewerWidget(buildScene());  
  362.     viewWidget->setGeometry( 100, 100, 640, 480 );  
  363.     viewWidget->show();  
  364.     return app.exec();  
  365. }  
0 0
原创粉丝点击