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

Revision 4340, 10.2 kB (checked in by robert, 9 years ago)

Further FBO support work.

  • 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
27// call back which cretes a deformation field to oscilate the model.
28class MyGeometryCallback :
29    public osg::Drawable::UpdateCallback,
30    public osg::Drawable::AttributeFunctor
31{
32    public:
33   
34        MyGeometryCallback(const osg::Vec3& o,
35                           const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
36                           double period,double xphase,double amplitude):
37            _firstCall(true),
38            _startTime(0.0),
39            _time(0.0),
40            _period(period),
41            _xphase(xphase),
42            _amplitude(amplitude),
43            _origin(o),
44            _xAxis(x),
45            _yAxis(y),
46            _zAxis(z) {}
47   
48        virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
49        {
50            const osg::FrameStamp* fs = nv->getFrameStamp();
51            double referenceTime = fs->getReferenceTime();
52            if (_firstCall)
53            {
54                _firstCall = false;
55                _startTime = referenceTime;
56            }
57           
58            _time = referenceTime-_startTime;
59           
60            drawable->accept(*this);
61            drawable->dirtyBound();
62           
63            osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
64            if (geometry)
65            {
66                osgUtil::SmoothingVisitor::smooth(*geometry);
67            }
68           
69        }
70       
71        virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
72        {
73            if (type == osg::Drawable::VERTICES)
74            {
75                const float TwoPI=2.0f*osg::PI;
76                const float phase = -_time/_period;
77               
78                osg::Vec3* end = begin+count;
79                for (osg::Vec3* itr=begin;itr<end;++itr)
80                {
81                    osg::Vec3 dv(*itr-_origin);
82                    osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);
83                   
84                    local.z() = local.x()*_amplitude*
85                                sinf(TwoPI*(phase+local.x()*_xphase));
86                   
87                    (*itr) = _origin +
88                             _xAxis*local.x()+
89                             _yAxis*local.y()+
90                             _zAxis*local.z();
91                }
92            }
93        }
94
95        bool    _firstCall;
96
97        double  _startTime;
98        double  _time;
99       
100        double  _period;
101        double  _xphase;
102        float   _amplitude;
103
104        osg::Vec3   _origin;
105        osg::Vec3   _xAxis;
106        osg::Vec3   _yAxis;
107        osg::Vec3   _zAxis;
108       
109};
110
111osg::Node* createPreRenderSubGraph(osg::Node* subgraph)
112{
113    if (!subgraph) return 0;
114 
115    // create the quad to visualize.
116    osg::Geometry* polyGeom = new osg::Geometry();
117
118    polyGeom->setSupportsDisplayList(false);
119
120    osg::Vec3 origin(0.0f,0.0f,0.0f);
121    osg::Vec3 xAxis(1.0f,0.0f,0.0f);
122    osg::Vec3 yAxis(0.0f,0.0f,1.0f);
123    osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
124    float height = 100.0f;
125    float width = 200.0f;
126    int noSteps = 20;
127   
128    osg::Vec3Array* vertices = new osg::Vec3Array;
129    osg::Vec3 bottom = origin;
130    osg::Vec3 top = origin; top.z()+= height;
131    osg::Vec3 dv = xAxis*(width/((float)(noSteps-1)));
132   
133    osg::Vec2Array* texcoords = new osg::Vec2Array;
134    osg::Vec2 bottom_texcoord(0.0f,0.0f);
135    osg::Vec2 top_texcoord(0.0f,1.0f);
136    osg::Vec2 dv_texcoord(1.0f/(float)(noSteps-1),0.0f);
137
138    for(int i=0;i<noSteps;++i)
139    {
140        vertices->push_back(top);
141        vertices->push_back(bottom);
142        top+=dv;
143        bottom+=dv;
144
145        texcoords->push_back(top_texcoord);
146        texcoords->push_back(bottom_texcoord);
147        top_texcoord+=dv_texcoord;
148        bottom_texcoord+=dv_texcoord;
149    }
150   
151
152    // pass the created vertex array to the points geometry object.
153    polyGeom->setVertexArray(vertices);
154   
155    polyGeom->setTexCoordArray(0,texcoords);
156   
157
158    osg::Vec4Array* colors = new osg::Vec4Array;
159    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
160    polyGeom->setColorArray(colors);
161    polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
162
163    polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
164
165
166
167    unsigned int tex_width = 2048;
168    unsigned int tex_height = 2048;
169
170
171    // new we need to add the texture to the Drawable, we do so by creating a
172    // StateSet to contain the Texture StateAttribute.
173    osg::StateSet* stateset = new osg::StateSet;
174
175    osg::Texture2D* texture = new osg::Texture2D;
176    texture->setTextureSize(tex_width, tex_height);
177    texture->setInternalFormat(GL_RGBA);
178    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
179    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
180    stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
181
182    polyGeom->setStateSet(stateset);
183
184    polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/width,0.2f));
185
186    osg::Geode* geode = new osg::Geode();
187    geode->addDrawable(polyGeom);
188
189
190    osg::CameraNode* camera = new osg::CameraNode;
191   
192    // set up the background color and clear mask.
193    camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
194    camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
195
196    const osg::BoundingSphere& bs = subgraph->getBound();
197    if (!bs.valid())
198    {
199        return subgraph;
200    }
201
202    float znear = 1.0f*bs.radius();
203    float zfar  = 3.0f*bs.radius();
204
205    // 2:1 aspect ratio as per flag geomtry below.
206    float proj_top   = 0.25f*znear;
207    float proj_right = 0.5f*znear;
208
209    znear *= 0.9f;
210    zfar *= 1.1f;
211
212    // set up projection.
213    camera->setProjectionMatrixAsFrustum(-proj_right,proj_right,-proj_top,proj_top,znear,zfar);
214
215    // set view
216    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
217    camera->setViewMatrixAsLookAt(bs.center()+osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
218
219    // set viewport
220    camera->setViewport(0,0,tex_width,tex_height);
221   
222    camera->getOrCreateStateSet()->setAttribute(camera->getViewport());
223   
224    // set the camera to render before the main camera.
225    camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
226   
227    // tell the camera to use OpenGL frame buffer object where supported.
228    camera->setRenderTargetImplmentation(osg::CameraNode::FRAME_BUFFER_OBJECT);
229   
230    // attach the texture and use it as the color buffer.
231    camera->attach(osg::CameraNode::COLOR_BUFFER, texture);
232
233    // add subgraph to render
234    camera->addChild(subgraph);
235   
236   
237    // create a group to contain the flag and the pre rendering camera.
238    osg::Group* parent = new osg::Group;
239   
240    parent->addChild(camera);
241    parent->addChild(geode);
242
243
244    return parent;
245}
246
247int main( int argc, char **argv )
248{
249    // use an ArgumentParser object to manage the program arguments.
250    osg::ArgumentParser arguments(&argc,argv);
251
252    // set up the usage document, in case we need to print out how to use this program.
253    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
254    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
255    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
256   
257    // construct the viewer.
258    osgProducer::Viewer viewer(arguments);
259
260    // set up the value with sensible default event handlers.
261    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
262
263    // get details on keyboard and mouse bindings used by the viewer.
264    viewer.getUsage(*arguments.getApplicationUsage());
265
266    // if user request help write it out to cout.
267    if (arguments.read("-h") || arguments.read("--help"))
268    {
269        arguments.getApplicationUsage()->write(std::cout);
270        return 1;
271    }
272
273    // any option left unread are converted into errors to write out later.
274    arguments.reportRemainingOptionsAsUnrecognized();
275
276    // report any errors if they have occured when parsing the program aguments.
277    if (arguments.errors())
278    {
279        arguments.writeErrorMessages(std::cout);
280        return 1;
281    }
282   
283    if (arguments.argc()<=1)
284    {
285        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
286        return 1;
287    }
288
289   
290    // load the nodes from the commandline arguments.
291    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
292    if (!loadedModel)
293    {
294//        write_usage(osg::notify(osg::NOTICE),argv[0]);
295        return 1;
296    }
297   
298    // create a transform to spin the model.
299    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
300    loadedModelTransform->addChild(loadedModel);
301
302    osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
303    loadedModelTransform->setUpdateCallback(nc);
304
305    osg::Group* rootNode = new osg::Group();
306//    rootNode->addChild(loadedModelTransform);
307    rootNode->addChild(createPreRenderSubGraph(loadedModelTransform));
308
309
310    // add model to the viewer.
311    viewer.setSceneData( rootNode );
312
313
314    // create the windows and run the threads.
315    viewer.realize();
316
317    while( !viewer.done() )
318    {
319        // wait for all cull and draw threads to complete.
320        viewer.sync();
321
322        // update the scene by traversing it with the the update visitor which will
323        // call all node update callbacks and animations.
324        viewer.update();
325         
326        // fire off the cull and draw traversals of the scene.
327        viewer.frame();
328       
329    }
330   
331    // wait for all cull and draw threads to complete before exit.
332    viewer.sync();
333
334    return 0;
335}
Note: See TracBrowser for help on using the browser.