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

Revision 5954, 15.9 kB (checked in by robert, 7 years ago)

Ported following examples to osgViewer:

osgparticleeffects
osgphotoalbum
osgpick
osgpoints
osgpointsprite
osgprecipitation
osgprerender
osgprerendercubemap
osgreflect
osgscalarbar
osgscribe
osgsequence
osgplanets

  • 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/TextureRectangle>
8#include <osg/Stencil>
9#include <osg/ColorMask>
10#include <osg/Depth>
11#include <osg/Billboard>
12#include <osg/Material>
13#include <osg/AnimationPath>
14
15#include <osgGA/TrackballManipulator>
16#include <osgGA/FlightManipulator>
17#include <osgGA/DriveManipulator>
18
19#include <osgUtil/SmoothingVisitor>
20
21#include <osgDB/Registry>
22#include <osgDB/ReadFile>
23
24#include <osgViewer/Viewer>
25
26#include <iostream>
27
28// call back which cretes a deformation field to oscilate the model.
29class MyGeometryCallback :
30    public osg::Drawable::UpdateCallback,
31    public osg::Drawable::AttributeFunctor
32{
33    public:
34   
35        MyGeometryCallback(const osg::Vec3& o,
36                           const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
37                           double period,double xphase,double amplitude):
38            _firstCall(true),
39            _startTime(0.0),
40            _time(0.0),
41            _period(period),
42            _xphase(xphase),
43            _amplitude(amplitude),
44            _origin(o),
45            _xAxis(x),
46            _yAxis(y),
47            _zAxis(z) {}
48   
49        virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
50        {
51            const osg::FrameStamp* fs = nv->getFrameStamp();
52            double referenceTime = fs->getReferenceTime();
53            if (_firstCall)
54            {
55                _firstCall = false;
56                _startTime = referenceTime;
57            }
58           
59            _time = referenceTime-_startTime;
60           
61            drawable->accept(*this);
62            drawable->dirtyBound();
63           
64            osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
65            if (geometry)
66            {
67                osgUtil::SmoothingVisitor::smooth(*geometry);
68            }
69           
70        }
71       
72        virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
73        {
74            if (type == osg::Drawable::VERTICES)
75            {
76                const float TwoPI=2.0f*osg::PI;
77                const float phase = -_time/_period;
78               
79                osg::Vec3* end = begin+count;
80                for (osg::Vec3* itr=begin;itr<end;++itr)
81                {
82                    osg::Vec3 dv(*itr-_origin);
83                    osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);
84                   
85                    local.z() = local.x()*_amplitude*
86                                sinf(TwoPI*(phase+local.x()*_xphase));
87                   
88                    (*itr) = _origin +
89                             _xAxis*local.x()+
90                             _yAxis*local.y()+
91                             _zAxis*local.z();
92                }
93            }
94        }
95
96        bool    _firstCall;
97
98        double  _startTime;
99        double  _time;
100       
101        double  _period;
102        double  _xphase;
103        float   _amplitude;
104
105        osg::Vec3   _origin;
106        osg::Vec3   _xAxis;
107        osg::Vec3   _yAxis;
108        osg::Vec3   _zAxis;
109       
110};
111
112struct MyCameraPostDrawCallback : public osg::Camera::DrawCallback
113{
114    MyCameraPostDrawCallback(osg::Image* image):
115        _image(image)
116    {
117    }
118
119    virtual void operator () (const osg::Camera& /*camera*/) const
120    {
121        if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_UNSIGNED_BYTE)
122        {
123            // we'll pick out the center 1/2 of the whole image,
124            int column_start = _image->s()/4;
125            int column_end = 3*column_start;
126           
127            int row_start = _image->t()/4;
128            int row_end = 3*row_start;
129           
130
131            // and then invert these pixels
132            for(int r=row_start; r<row_end; ++r)
133            {
134                unsigned char* data = _image->data(column_start, r);
135                for(int c=column_start; c<column_end; ++c)
136                {
137                    (*data) = 255-(*data); ++data;
138                    (*data) = 255-(*data); ++data;
139                    (*data) = 255-(*data); ++data;
140                    (*data) = 255; ++data;
141                }
142            }
143
144
145            // dirty the image (increments the modified count) so that any textures
146            // using the image can be informed that they need to update.
147            _image->dirty();
148        }
149        else if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_FLOAT)
150        {
151            // we'll pick out the center 1/2 of the whole image,
152            int column_start = _image->s()/4;
153            int column_end = 3*column_start;
154           
155            int row_start = _image->t()/4;
156            int row_end = 3*row_start;
157           
158            // and then invert these pixels
159            for(int r=row_start; r<row_end; ++r)
160            {
161                float* data = (float*)_image->data(column_start, r);
162                for(int c=column_start; c<column_end; ++c)
163                {
164                    (*data) = 1.0f-(*data); ++data;
165                    (*data) = 1.0f-(*data); ++data;
166                    (*data) = 1.0f-(*data); ++data;
167                    (*data) = 1.0f; ++data;
168                }
169            }
170
171            // dirty the image (increments the modified count) so that any textures
172            // using the image can be informed that they need to update.
173            _image->dirty();
174        }
175       
176    }
177   
178    osg::Image* _image;
179};
180
181
182osg::Node* createPreRenderSubGraph(osg::Node* subgraph, unsigned tex_width, unsigned tex_height, osg::Camera::RenderTargetImplementation renderImplementation, bool useImage, bool useTextureRectangle, bool useHDR)
183{
184    if (!subgraph) return 0;
185
186    // create a group to contain the flag and the pre rendering camera.
187    osg::Group* parent = new osg::Group;
188
189    // texture to render to and to use for rendering of flag.
190    osg::Texture* texture = 0;
191    if (useTextureRectangle)
192    {
193        osg::TextureRectangle* textureRect = new osg::TextureRectangle;
194        textureRect->setTextureSize(tex_width, tex_height);
195        textureRect->setInternalFormat(GL_RGBA);
196        textureRect->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
197        textureRect->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
198       
199        texture = textureRect;
200    }
201    else
202    {
203        osg::Texture2D* texture2D = new osg::Texture2D;
204        texture2D->setTextureSize(tex_width, tex_height);
205        texture2D->setInternalFormat(GL_RGBA);
206        texture2D->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
207        texture2D->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
208       
209        texture = texture2D;
210    }
211
212    if (useHDR)
213    {
214        texture->setInternalFormat(GL_RGBA16F_ARB);
215        texture->setSourceFormat(GL_RGBA);
216        texture->setSourceType(GL_FLOAT);
217    }
218
219    // first create the geometry of the flag of which to view.
220    {
221        // create the to visualize.
222        osg::Geometry* polyGeom = new osg::Geometry();
223
224        polyGeom->setSupportsDisplayList(false);
225
226        osg::Vec3 origin(0.0f,0.0f,0.0f);
227        osg::Vec3 xAxis(1.0f,0.0f,0.0f);
228        osg::Vec3 yAxis(0.0f,0.0f,1.0f);
229        osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
230        float height = 100.0f;
231        float width = 200.0f;
232        int noSteps = 20;
233
234        osg::Vec3Array* vertices = new osg::Vec3Array;
235        osg::Vec3 bottom = origin;
236        osg::Vec3 top = origin; top.z()+= height;
237        osg::Vec3 dv = xAxis*(width/((float)(noSteps-1)));
238
239        osg::Vec2Array* texcoords = new osg::Vec2Array;
240       
241        // note, when we use TextureRectangle we have to scale the tex coords up to compensate.
242        osg::Vec2 bottom_texcoord(0.0f,0.0f);
243        osg::Vec2 top_texcoord(0.0f, useTextureRectangle ? tex_height : 1.0f);
244        osg::Vec2 dv_texcoord((useTextureRectangle ? tex_width : 1.0f)/(float)(noSteps-1),0.0f);
245
246        for(int i=0;i<noSteps;++i)
247        {
248            vertices->push_back(top);
249            vertices->push_back(bottom);
250            top+=dv;
251            bottom+=dv;
252
253            texcoords->push_back(top_texcoord);
254            texcoords->push_back(bottom_texcoord);
255            top_texcoord+=dv_texcoord;
256            bottom_texcoord+=dv_texcoord;
257        }
258
259
260        // pass the created vertex array to the points geometry object.
261        polyGeom->setVertexArray(vertices);
262
263        polyGeom->setTexCoordArray(0,texcoords);
264
265
266        osg::Vec4Array* colors = new osg::Vec4Array;
267        colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
268        polyGeom->setColorArray(colors);
269        polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
270
271        polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
272
273        // new we need to add the texture to the Drawable, we do so by creating a
274        // StateSet to contain the Texture StateAttribute.
275        osg::StateSet* stateset = new osg::StateSet;
276
277        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
278
279        polyGeom->setStateSet(stateset);
280
281        polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/width,0.2f));
282
283        osg::Geode* geode = new osg::Geode();
284        geode->addDrawable(polyGeom);
285       
286        parent->addChild(geode);
287
288    }
289
290
291    // then create the camera node to do the render to texture
292    {   
293        osg::Camera* camera = new osg::Camera;
294
295        // set up the background color and clear mask.
296        camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
297        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
298
299        const osg::BoundingSphere& bs = subgraph->getBound();
300        if (!bs.valid())
301        {
302            return subgraph;
303        }
304
305        float znear = 1.0f*bs.radius();
306        float zfar  = 3.0f*bs.radius();
307
308        // 2:1 aspect ratio as per flag geomtry below.
309        float proj_top   = 0.25f*znear;
310        float proj_right = 0.5f*znear;
311
312        znear *= 0.9f;
313        zfar *= 1.1f;
314
315        // set up projection.
316        camera->setProjectionMatrixAsFrustum(-proj_right,proj_right,-proj_top,proj_top,znear,zfar);
317
318        // set view
319        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
320        camera->setViewMatrixAsLookAt(bs.center()-osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
321
322        // set viewport
323        camera->setViewport(0,0,tex_width,tex_height);
324
325        // set the camera to render before the main camera.
326        camera->setRenderOrder(osg::Camera::PRE_RENDER);
327
328        // tell the camera to use OpenGL frame buffer object where supported.
329        camera->setRenderTargetImplementation(renderImplementation);
330
331       
332        if (useImage)
333        {
334            osg::Image* image = new osg::Image;
335            //image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
336            image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_FLOAT);
337
338            // attach the image so its copied on each frame.
339            camera->attach(osg::Camera::COLOR_BUFFER, image);
340           
341            camera->setPostDrawCallback(new MyCameraPostDrawCallback(image));
342           
343            // Rather than attach the texture directly to illustrate the texture's ability to
344            // detect an image update and to subload the image onto the texture.  You needn't
345            // do this when using an Image for copying to, as a seperate camera->attach(..)
346            // would suffice as well, but we'll do it the long way round here just for demonstation
347            // purposes (long way round meaning we'll need to copy image to main memory, then
348            // copy it back to the graphics card to the texture in one frame).
349            // The long way round allows us to mannually modify the copied image via the callback
350            // and then let this modified image by reloaded back.
351            texture->setImage(0, image);
352        }
353        else
354        {
355            // attach the texture and use it as the color buffer.
356            camera->attach(osg::Camera::COLOR_BUFFER, texture);
357        }
358
359
360        // add subgraph to render
361        camera->addChild(subgraph);
362
363        parent->addChild(camera);
364
365    }   
366
367    return parent;
368}
369
370int main( int argc, char **argv )
371{
372    // use an ArgumentParser object to manage the program arguments.
373    osg::ArgumentParser arguments(&argc,argv);
374
375    // set up the usage document, in case we need to print out how to use this program.
376    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
377    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
378    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
379    arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
380    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
381    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
382    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
383    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");
384    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");
385    arguments.getApplicationUsage()->addCommandLineOption("--image","Render to an image, then apply a post draw callback to it, and use this image to update a texture.");
386    arguments.getApplicationUsage()->addCommandLineOption("--texture-rectangle","Use osg::TextureRectangle for doing the render to texure to.");
387   
388    // construct the viewer.
389    osgViewer::Viewer viewer;
390
391    // if user request help write it out to cout.
392    if (arguments.read("-h") || arguments.read("--help"))
393    {
394        arguments.getApplicationUsage()->write(std::cout);
395        return 1;
396    }
397
398    unsigned tex_width = 1024;
399    unsigned tex_height = 512;
400    while (arguments.read("--width", tex_width)) {}
401    while (arguments.read("--height", tex_height)) {}
402
403    osg::Camera::RenderTargetImplementation renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
404   
405    while (arguments.read("--fbo")) { renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT; }
406    while (arguments.read("--pbuffer")) { renderImplementation = osg::Camera::PIXEL_BUFFER; }
407    while (arguments.read("--pbuffer-rtt")) { renderImplementation = osg::Camera::PIXEL_BUFFER_RTT; }
408    while (arguments.read("--fb")) { renderImplementation = osg::Camera::FRAME_BUFFER; }
409    while (arguments.read("--window")) { renderImplementation = osg::Camera::SEPERATE_WINDOW; }
410
411    bool useImage = false;
412    while (arguments.read("--image")) { useImage = true; }
413   
414    bool useTextureRectangle = false;
415    while (arguments.read("--texture-rectangle")) { useTextureRectangle = true; }
416   
417    bool useHDR = false;
418    while (arguments.read("--hdr")) { useHDR = true; }
419
420   
421    // load the nodes from the commandline arguments.
422    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
423    if (!loadedModel)
424    {
425        return 1;
426    }
427   
428    // create a transform to spin the model.
429    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
430    loadedModelTransform->addChild(loadedModel);
431
432    osg::NodeCallback* nc = new osg::AnimationPathCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
433    loadedModelTransform->setUpdateCallback(nc);
434
435    osg::Group* rootNode = new osg::Group();
436    rootNode->addChild(createPreRenderSubGraph(loadedModelTransform,tex_width,tex_height, renderImplementation, useImage, useTextureRectangle, useHDR));
437
438    // add model to the viewer.
439    viewer.setSceneData( rootNode );
440
441    return viewer.run();
442}
Note: See TracBrowser for help on using the browser.