root/OpenSceneGraph/trunk/examples/osgprerender/osgprerender.cpp @ 4332

Revision 4332, 15.8 kB (checked in by robert, 9 years ago)

Work on the RenderToTexture? usage of the new osg::CameraNode?. Both osghud
and osgprerender now ported across to osg::CameraNode?.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/GLExtensions>
2#include <osg/Node>
3#include <osg/Geometry>
4#include <osg/Notify>
5#include <osg/MatrixTransform>
6#include <osg/Texture2D>
7#include <osg/Stencil>
8#include <osg/ColorMask>
9#include <osg/Depth>
10#include <osg/Billboard>
11#include <osg/Material>
12
13#include <osgGA/TrackballManipulator>
14#include <osgGA/FlightManipulator>
15#include <osgGA/DriveManipulator>
16
17#include <osgUtil/TransformCallback>
18#include <osgUtil/RenderToTextureStage>
19#include <osgUtil/SmoothingVisitor>
20
21#include <osgDB/Registry>
22#include <osgDB/ReadFile>
23
24#include <osgProducer/Viewer>
25
26#define USE_CAMERA_NODE
27
28#ifndef USE_CAMERA_NODE
29
30    class MyUpdateCallback : public osg::NodeCallback
31    {
32        public:
33
34            MyUpdateCallback(osg::Node* subgraph):
35                _subgraph(subgraph) {}
36
37            virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
38            {
39                // traverse the subgraph to update any nodes.
40                if (_subgraph.valid()) _subgraph->accept(*nv);
41
42                // must traverse the Node's subgraph           
43                traverse(node,nv);
44            }
45
46            osg::ref_ptr<osg::Node>     _subgraph;
47    };
48
49
50    class MyCullCallback : public osg::NodeCallback
51    {
52        public:
53
54            MyCullCallback(osg::Node* subgraph,osg::Texture2D* texture):
55                _subgraph(subgraph),
56                _texture(texture),
57                _localState(new osg::StateSet) {}
58
59            MyCullCallback(osg::Node* subgraph,osg::Image* image):
60                _subgraph(subgraph),
61                _image(image),
62                _localState(new osg::StateSet) {}
63
64            virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
65            {
66
67                osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
68                if (cullVisitor && (_texture.valid()|| _image.valid()) && _subgraph.valid())
69                {           
70                    doPreRender(*node,*cullVisitor);
71
72                    // must traverse the subgraph           
73                    traverse(node,nv);
74
75                }
76                else
77                {
78                    // must traverse the subgraph           
79                    traverse(node,nv);
80                }
81            }
82
83            void doPreRender(osg::Node& node, osgUtil::CullVisitor& cv);
84
85            osg::ref_ptr<osg::Node>      _subgraph;
86            osg::ref_ptr<osg::Texture2D> _texture;
87            osg::ref_ptr<osg::Image>     _image;
88            osg::ref_ptr<osg::StateSet>  _localState;
89
90    };
91
92    void MyCullCallback::doPreRender(osg::Node&, osgUtil::CullVisitor& cv)
93    {   
94        const osg::BoundingSphere& bs = _subgraph->getBound();
95        if (!bs.valid())
96        {
97            osg::notify(osg::WARN) << "bb invalid"<<_subgraph.get()<<std::endl;
98            return;
99        }
100
101
102        // create the render to texture stage.
103        osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage;
104
105        // set up lighting.
106        // currently ignore lights in the scene graph itself..
107        // will do later.
108        osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->getStage();
109
110        // set up the background color and clear mask.
111        rtts->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
112        rtts->setClearMask(previous_stage->getClearMask());
113
114        // set up to charge the same RenderStageLighting is the parent previous stage.
115        rtts->setRenderStageLighting(previous_stage->getRenderStageLighting());
116
117
118        // record the render bin, to be restored after creation
119        // of the render to text
120        osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin();
121
122        // set the current renderbin to be the newly created stage.
123        cv.setCurrentRenderBin(rtts.get());
124
125
126        float znear = 1.0f*bs.radius();
127        float zfar  = 3.0f*bs.radius();
128
129        // 2:1 aspect ratio as per flag geomtry below.
130        float top   = 0.25f*znear;
131        float right = 0.5f*znear;
132
133        znear *= 0.9f;
134        zfar *= 1.1f;
135
136        // set up projection.
137        osg::RefMatrix* projection = new osg::RefMatrix;
138        projection->makeFrustum(-right,right,-top,top,znear,zfar);
139
140        cv.pushProjectionMatrix(projection);
141
142        osg::RefMatrix* matrix = new osg::RefMatrix;
143        matrix->makeLookAt(bs.center()+osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
144
145        cv.pushModelViewMatrix(matrix);
146
147        cv.pushStateSet(_localState.get());
148
149        {
150
151            // traverse the subgraph
152            _subgraph->accept(cv);
153
154        }
155
156        cv.popStateSet();
157
158        // restore the previous model view matrix.
159        cv.popModelViewMatrix();
160
161        // restore the previous model view matrix.
162        cv.popProjectionMatrix();
163
164        // restore the previous renderbin.
165        cv.setCurrentRenderBin(previousRenderBin);
166
167        if (rtts->getRenderGraphList().size()==0 && rtts->getRenderBinList().size()==0)
168        {
169            // getting to this point means that all the subgraph has been
170            // culled by small feature culling or is beyond LOD ranges.
171            return;
172        }
173
174
175
176        int height = 256;
177        int width  = 512;
178
179
180        const osg::Viewport& viewport = *cv.getViewport();
181
182        // offset the impostor viewport from the center of the main window
183        // viewport as often the edges of the viewport might be obscured by
184        // other windows, which can cause image/reading writing problems.
185        int center_x = viewport.x()+viewport.width()/2;
186        int center_y = viewport.y()+viewport.height()/2;
187
188        osg::Viewport* new_viewport = new osg::Viewport;
189        new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height);
190        rtts->setViewport(new_viewport);
191
192        _localState->setAttribute(new_viewport);
193
194        // and the render to texture stage to the current stages
195        // dependancy list.
196        cv.getCurrentRenderBin()->getStage()->addToDependencyList(rtts.get());
197
198        // if one exist attach texture to the RenderToTextureStage.
199        if (_texture.valid()) rtts->setTexture(_texture.get());
200
201        // if one exist attach image to the RenderToTextureStage.
202        if (_image.valid()) rtts->setImage(_image.get());
203
204    }
205#endif
206
207// call back which cretes a deformation field to oscilate the model.
208class MyGeometryCallback :
209    public osg::Drawable::UpdateCallback,
210    public osg::Drawable::AttributeFunctor
211{
212    public:
213   
214        MyGeometryCallback(const osg::Vec3& o,
215                           const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
216                           double period,double xphase,double amplitude):
217            _firstCall(true),
218            _startTime(0.0),
219            _time(0.0),
220            _period(period),
221            _xphase(xphase),
222            _amplitude(amplitude),
223            _origin(o),
224            _xAxis(x),
225            _yAxis(y),
226            _zAxis(z) {}
227   
228        virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
229        {
230            const osg::FrameStamp* fs = nv->getFrameStamp();
231            double referenceTime = fs->getReferenceTime();
232            if (_firstCall)
233            {
234                _firstCall = false;
235                _startTime = referenceTime;
236            }
237           
238            _time = referenceTime-_startTime;
239           
240            drawable->accept(*this);
241            drawable->dirtyBound();
242           
243            osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
244            if (geometry)
245            {
246                osgUtil::SmoothingVisitor::smooth(*geometry);
247            }
248           
249        }
250       
251        virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
252        {
253            if (type == osg::Drawable::VERTICES)
254            {
255                const float TwoPI=2.0f*osg::PI;
256                const float phase = -_time/_period;
257               
258                osg::Vec3* end = begin+count;
259                for (osg::Vec3* itr=begin;itr<end;++itr)
260                {
261                    osg::Vec3 dv(*itr-_origin);
262                    osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);
263                   
264                    local.z() = local.x()*_amplitude*
265                                sinf(TwoPI*(phase+local.x()*_xphase));
266                   
267                    (*itr) = _origin +
268                             _xAxis*local.x()+
269                             _yAxis*local.y()+
270                             _zAxis*local.z();
271                }
272            }
273        }
274
275        bool    _firstCall;
276
277        double  _startTime;
278        double  _time;
279       
280        double  _period;
281        double  _xphase;
282        float   _amplitude;
283
284        osg::Vec3   _origin;
285        osg::Vec3   _xAxis;
286        osg::Vec3   _yAxis;
287        osg::Vec3   _zAxis;
288       
289};
290
291osg::Node* createPreRenderSubGraph(osg::Node* subgraph)
292{
293    if (!subgraph) return 0;
294 
295    // create the quad to visualize.
296    osg::Geometry* polyGeom = new osg::Geometry();
297
298    polyGeom->setSupportsDisplayList(false);
299
300    osg::Vec3 origin(0.0f,0.0f,0.0f);
301    osg::Vec3 xAxis(1.0f,0.0f,0.0f);
302    osg::Vec3 yAxis(0.0f,0.0f,1.0f);
303    osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
304    float height = 100.0f;
305    float width = 200.0f;
306    int noSteps = 20;
307   
308    osg::Vec3Array* vertices = new osg::Vec3Array;
309    osg::Vec3 bottom = origin;
310    osg::Vec3 top = origin; top.z()+= height;
311    osg::Vec3 dv = xAxis*(width/((float)(noSteps-1)));
312   
313    osg::Vec2Array* texcoords = new osg::Vec2Array;
314    osg::Vec2 bottom_texcoord(0.0f,0.0f);
315    osg::Vec2 top_texcoord(0.0f,1.0f);
316    osg::Vec2 dv_texcoord(1.0f/(float)(noSteps-1),0.0f);
317
318    for(int i=0;i<noSteps;++i)
319    {
320        vertices->push_back(top);
321        vertices->push_back(bottom);
322        top+=dv;
323        bottom+=dv;
324
325        texcoords->push_back(top_texcoord);
326        texcoords->push_back(bottom_texcoord);
327        top_texcoord+=dv_texcoord;
328        bottom_texcoord+=dv_texcoord;
329    }
330   
331
332    // pass the created vertex array to the points geometry object.
333    polyGeom->setVertexArray(vertices);
334   
335    polyGeom->setTexCoordArray(0,texcoords);
336   
337
338    osg::Vec4Array* colors = new osg::Vec4Array;
339    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
340    polyGeom->setColorArray(colors);
341    polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
342
343    polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
344
345    // new we need to add the texture to the Drawable, we do so by creating a
346    // StateSet to contain the Texture StateAttribute.
347    osg::StateSet* stateset = new osg::StateSet;
348
349    osg::Texture2D* texture = new osg::Texture2D;
350    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
351    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
352    stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
353
354    polyGeom->setStateSet(stateset);
355
356    polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/width,0.2f));
357
358    osg::Geode* geode = new osg::Geode();
359    geode->addDrawable(polyGeom);
360
361#ifndef USE_CAMERA_NODE
362
363    osg::Group* parent = new osg::Group;
364   
365    parent->setUpdateCallback(new MyUpdateCallback(subgraph));
366   
367    parent->setCullCallback(new MyCullCallback(subgraph,texture));
368 
369    parent->addChild(geode);
370   
371    return parent;
372
373#else
374
375
376    osg::CameraNode* camera = new osg::CameraNode;
377   
378    // set up the background color and clear mask.
379    camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
380    camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
381
382    const osg::BoundingSphere& bs = subgraph->getBound();
383    if (!bs.valid())
384    {
385        return subgraph;
386    }
387
388    float znear = 1.0f*bs.radius();
389    float zfar  = 3.0f*bs.radius();
390
391    // 2:1 aspect ratio as per flag geomtry below.
392    float proj_top   = 0.25f*znear;
393    float proj_right = 0.5f*znear;
394
395    znear *= 0.9f;
396    zfar *= 1.1f;
397
398    // set up projection.
399    camera->setProjectionMatrixAsFrustum(-proj_right,proj_right,-proj_top,proj_top,znear,zfar);
400
401    // set view
402    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
403    camera->setViewMatrixAsLookAt(bs.center()+osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
404
405    // set viewport
406    camera->setViewport(0,0,1024,512);
407   
408    camera->getOrCreateStateSet()->setAttribute(camera->getViewport());
409   
410    // set the camera to render before the main camera.
411    camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
412   
413    camera->attach(osg::CameraNode::COLOR_BUFFER,texture);
414
415    // add subgraph to render
416    camera->addChild(subgraph);
417   
418   
419    // create a group to contain the flag and the pre rendering camera.
420    osg::Group* parent = new osg::Group;
421   
422    parent->addChild(camera);
423    parent->addChild(geode);
424
425
426    return parent;
427
428#endif
429}
430
431int main( int argc, char **argv )
432{
433    // use an ArgumentParser object to manage the program arguments.
434    osg::ArgumentParser arguments(&argc,argv);
435
436    // set up the usage document, in case we need to print out how to use this program.
437    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
438    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
439    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
440   
441    // construct the viewer.
442    osgProducer::Viewer viewer(arguments);
443
444    // set up the value with sensible default event handlers.
445    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
446
447    // get details on keyboard and mouse bindings used by the viewer.
448    viewer.getUsage(*arguments.getApplicationUsage());
449
450    // if user request help write it out to cout.
451    if (arguments.read("-h") || arguments.read("--help"))
452    {
453        arguments.getApplicationUsage()->write(std::cout);
454        return 1;
455    }
456
457    // any option left unread are converted into errors to write out later.
458    arguments.reportRemainingOptionsAsUnrecognized();
459
460    // report any errors if they have occured when parsing the program aguments.
461    if (arguments.errors())
462    {
463        arguments.writeErrorMessages(std::cout);
464        return 1;
465    }
466   
467    if (arguments.argc()<=1)
468    {
469        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
470        return 1;
471    }
472
473   
474    // load the nodes from the commandline arguments.
475    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
476    if (!loadedModel)
477    {
478//        write_usage(osg::notify(osg::NOTICE),argv[0]);
479        return 1;
480    }
481   
482    // create a transform to spin the model.
483    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
484    loadedModelTransform->addChild(loadedModel);
485
486    osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
487    loadedModelTransform->setUpdateCallback(nc);
488
489    osg::Group* rootNode = new osg::Group();
490//    rootNode->addChild(loadedModelTransform);
491    rootNode->addChild(createPreRenderSubGraph(loadedModelTransform));
492
493
494    // add model to the viewer.
495    viewer.setSceneData( rootNode );
496
497
498    // create the windows and run the threads.
499    viewer.realize();
500
501    while( !viewer.done() )
502    {
503        // wait for all cull and draw threads to complete.
504        viewer.sync();
505
506        // update the scene by traversing it with the the update visitor which will
507        // call all node update callbacks and animations.
508        viewer.update();
509         
510        // fire off the cull and draw traversals of the scene.
511        viewer.frame();
512       
513    }
514   
515    // wait for all cull and draw threads to complete before exit.
516    viewer.sync();
517
518    return 0;
519}
Note: See TracBrowser for help on using the browser.