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

Revision 4647, 15.5 kB (checked in by robert, 8 years ago)

Added usage of image copy and modification.

  • 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
14#include <osgGA/TrackballManipulator>
15#include <osgGA/FlightManipulator>
16#include <osgGA/DriveManipulator>
17
18#include <osgUtil/TransformCallback>
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
111struct MyCameraPostDrawCallback : public osg::CameraNode::DrawCallback
112{
113    MyCameraPostDrawCallback(osg::Image* image):
114        _image(image)
115    {
116    }
117
118    virtual void operator () (const osg::CameraNode& /*camera*/) const
119    {
120        if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_UNSIGNED_BYTE)
121        {
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;
138                    (*data) = (*data); ++data;
139                    (*data) = (*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       
150    }
151   
152    osg::Image* _image;
153};
154
155
156osg::Node* createPreRenderSubGraph(osg::Node* subgraph, unsigned tex_width, unsigned tex_height, osg::CameraNode::RenderTargetImplementation renderImplementation, bool useImage, bool useTextureRectangle)
157{
158    if (!subgraph) return 0;
159
160    // create a group to contain the flag and the pre rendering camera.
161    osg::Group* parent = new osg::Group;
162
163    // texture to render to and to use for rendering of flag.
164    osg::Texture* texture = 0;
165    if (useTextureRectangle)
166    {
167        osg::TextureRectangle* textureRect = new osg::TextureRectangle;
168        textureRect->setTextureSize(tex_width, tex_height);
169        textureRect->setInternalFormat(GL_RGBA);
170        textureRect->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
171        textureRect->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
172       
173        texture = textureRect;
174    }
175    else
176    {
177        osg::Texture2D* texture2D = new osg::Texture2D;
178        texture2D->setTextureSize(tex_width, tex_height);
179        texture2D->setInternalFormat(GL_RGBA);
180        texture2D->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
181        texture2D->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
182       
183        texture = texture2D;
184    }
185
186    // first create the geometry of the flag of which to view.
187    {
188        // create the to visualize.
189        osg::Geometry* polyGeom = new osg::Geometry();
190
191        polyGeom->setSupportsDisplayList(false);
192
193        osg::Vec3 origin(0.0f,0.0f,0.0f);
194        osg::Vec3 xAxis(1.0f,0.0f,0.0f);
195        osg::Vec3 yAxis(0.0f,0.0f,1.0f);
196        osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
197        float height = 100.0f;
198        float width = 200.0f;
199        int noSteps = 20;
200
201        osg::Vec3Array* vertices = new osg::Vec3Array;
202        osg::Vec3 bottom = origin;
203        osg::Vec3 top = origin; top.z()+= height;
204        osg::Vec3 dv = xAxis*(width/((float)(noSteps-1)));
205
206        osg::Vec2Array* texcoords = new osg::Vec2Array;
207       
208        // note, when we use TextureRectangle we have to scale the tex coords up to compensate.
209        osg::Vec2 bottom_texcoord(0.0f,0.0f);
210        osg::Vec2 top_texcoord(0.0f, useTextureRectangle ? tex_height : 1.0f);
211        osg::Vec2 dv_texcoord((useTextureRectangle ? tex_width : 1.0f)/(float)(noSteps-1),0.0f);
212
213        for(int i=0;i<noSteps;++i)
214        {
215            vertices->push_back(top);
216            vertices->push_back(bottom);
217            top+=dv;
218            bottom+=dv;
219
220            texcoords->push_back(top_texcoord);
221            texcoords->push_back(bottom_texcoord);
222            top_texcoord+=dv_texcoord;
223            bottom_texcoord+=dv_texcoord;
224        }
225
226
227        // pass the created vertex array to the points geometry object.
228        polyGeom->setVertexArray(vertices);
229
230        polyGeom->setTexCoordArray(0,texcoords);
231
232
233        osg::Vec4Array* colors = new osg::Vec4Array;
234        colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
235        polyGeom->setColorArray(colors);
236        polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
237
238        polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
239
240        // new we need to add the texture to the Drawable, we do so by creating a
241        // StateSet to contain the Texture StateAttribute.
242        osg::StateSet* stateset = new osg::StateSet;
243
244        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
245
246        polyGeom->setStateSet(stateset);
247
248        polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/width,0.2f));
249
250        osg::Geode* geode = new osg::Geode();
251        geode->addDrawable(polyGeom);
252       
253        parent->addChild(geode);
254
255    }
256
257
258    // then create the camera node to do the render to texture
259    {   
260        osg::CameraNode* camera = new osg::CameraNode;
261
262        // set up the background color and clear mask.
263        camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
264        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
265
266        const osg::BoundingSphere& bs = subgraph->getBound();
267        if (!bs.valid())
268        {
269            return subgraph;
270        }
271
272        float znear = 1.0f*bs.radius();
273        float zfar  = 3.0f*bs.radius();
274
275        // 2:1 aspect ratio as per flag geomtry below.
276        float proj_top   = 0.25f*znear;
277        float proj_right = 0.5f*znear;
278
279        znear *= 0.9f;
280        zfar *= 1.1f;
281
282        // set up projection.
283        camera->setProjectionMatrixAsFrustum(-proj_right,proj_right,-proj_top,proj_top,znear,zfar);
284
285        // set view
286        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
287        camera->setViewMatrixAsLookAt(bs.center()-osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
288
289        // set viewport
290        camera->setViewport(0,0,tex_width,tex_height);
291
292        // set the camera to render before the main camera.
293        camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
294
295        // tell the camera to use OpenGL frame buffer object where supported.
296        camera->setRenderTargetImplementation(renderImplementation);
297
298       
299        if (useImage)
300        {
301            osg::Image* image = new osg::Image;
302            image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
303
304            // attach the image so its copied on each frame.
305            camera->attach(osg::CameraNode::COLOR_BUFFER, image);
306           
307            camera->setPostDrawCallback(new MyCameraPostDrawCallback(image));
308           
309            // Rather than attach the texture directly to illustrate the texture's ability to
310            // detect an image update and to subload the image onto the texture.  You needn't
311            // do this when using an Image for copying to, as a seperate camera->attach(..)
312            // would suffice as well, but we'll do it the long way round here just for demonstation
313            // purposes (long way round meaning we'll need to copy image to main memory, then
314            // copy it back to the graphics card to the texture in one frame).
315            // The long way round allows us to mannually modify the copied image via the callback
316            // and then let this modified image by reloaded back.
317            texture->setImage(0, image);
318        }
319        else
320        {
321            // attach the texture and use it as the color buffer.
322            camera->attach(osg::CameraNode::COLOR_BUFFER, texture);
323        }
324
325
326        // add subgraph to render
327        camera->addChild(subgraph);
328
329        parent->addChild(camera);
330
331    }   
332
333    return parent;
334}
335
336int main( int argc, char **argv )
337{
338    // use an ArgumentParser object to manage the program arguments.
339    osg::ArgumentParser arguments(&argc,argv);
340
341    // set up the usage document, in case we need to print out how to use this program.
342    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
343    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
344    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
345    arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
346    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
347    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
348    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
349    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture");
350    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture");
351   
352    // construct the viewer.
353    osgProducer::Viewer viewer(arguments);
354
355    // set up the value with sensible default event handlers.
356    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
357
358    // get details on keyboard and mouse bindings used by the viewer.
359    viewer.getUsage(*arguments.getApplicationUsage());
360
361    // if user request help write it out to cout.
362    if (arguments.read("-h") || arguments.read("--help"))
363    {
364        arguments.getApplicationUsage()->write(std::cout);
365        return 1;
366    }
367
368    unsigned tex_width = 1024;
369    unsigned tex_height = 512;
370    while (arguments.read("--width", tex_width)) {}
371    while (arguments.read("--height", tex_height)) {}
372
373    osg::CameraNode::RenderTargetImplementation renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT;
374   
375    while (arguments.read("--fbo")) { renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; }
376    while (arguments.read("--pbuffer")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER; }
377    while (arguments.read("--pbuffer-rtt")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER_RTT; }
378    while (arguments.read("--fb")) { renderImplementation = osg::CameraNode::FRAME_BUFFER; }
379    while (arguments.read("--window")) { renderImplementation = osg::CameraNode::SEPERATE_WINDOW; }
380
381    bool useImage = false;
382    while (arguments.read("--image")) { useImage = true; }
383   
384    bool useTextureRectangle = false;
385    while (arguments.read("--texture-rectangle")) { useTextureRectangle = true; }
386   
387
388    // any option left unread are converted into errors to write out later.
389    arguments.reportRemainingOptionsAsUnrecognized();
390
391    // report any errors if they have occured when parsing the program aguments.
392    if (arguments.errors())
393    {
394        arguments.writeErrorMessages(std::cout);
395        return 1;
396    }
397   
398    if (arguments.argc()<=1)
399    {
400        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
401        return 1;
402    }
403
404   
405    // load the nodes from the commandline arguments.
406    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
407    if (!loadedModel)
408    {
409        return 1;
410    }
411   
412    // create a transform to spin the model.
413    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
414    loadedModelTransform->addChild(loadedModel);
415
416    osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
417    loadedModelTransform->setUpdateCallback(nc);
418
419    osg::Group* rootNode = new osg::Group();
420    rootNode->addChild(createPreRenderSubGraph(loadedModelTransform,tex_width,tex_height, renderImplementation, useImage, useTextureRectangle));
421
422
423    // add model to the viewer.
424    viewer.setSceneData( rootNode );
425
426
427    // create the windows and run the threads.
428    viewer.realize();
429
430    while( !viewer.done() )
431    {
432        // wait for all cull and draw threads to complete.
433        viewer.sync();
434
435        // update the scene by traversing it with the the update visitor which will
436        // call all node update callbacks and animations.
437        viewer.update();
438         
439        // fire off the cull and draw traversals of the scene.
440        viewer.frame();
441       
442    }
443   
444    // wait for all cull and draw threads to complete before exit.
445    viewer.sync();
446
447    return 0;
448}
Note: See TracBrowser for help on using the browser.