root/OpenSceneGraph/trunk/examples/osgdistortion/osgdistortion.cpp @ 3528

Revision 3528, 10.0 kB (checked in by robert, 9 years ago)

Changed ABSOLUTE and RELATIVE to ABSOLUTE_RF and RELATIVE_RF to avoid stooppid Win32 #define

  • 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#include <osg/Projection>
13
14#include <osgGA/TrackballManipulator>
15#include <osgGA/FlightManipulator>
16#include <osgGA/DriveManipulator>
17
18#include <osgUtil/TransformCallback>
19#include <osgUtil/RenderToTextureStage>
20#include <osgUtil/SmoothingVisitor>
21
22#include <osgDB/Registry>
23#include <osgDB/ReadFile>
24
25#include <osgProducer/Viewer>
26
27using namespace osg;
28
29class DistortionNode : public osg::Group
30{
31public:
32
33    DistortionNode();
34   
35    DistortionNode(const DistortionNode& rhs,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY):
36        osg::Group(rhs,copyop) {}
37
38    META_Node(osgDistortion, DistortionNode);
39
40    virtual void traverse(osg::NodeVisitor& nv);
41
42protected:
43
44    void createHUDSubgraph();
45
46    void preRender(osgUtil::CullVisitor& nv);   
47
48    osg::ref_ptr<osg::Node>         _hudSubgraph;
49    osg::ref_ptr<osg::Texture2D>    _texture;   
50    osg::ref_ptr<osg::StateSet>     _localStateSet;
51   
52};
53
54
55DistortionNode::DistortionNode()
56{
57    setCullingActive(false);
58    createHUDSubgraph();
59}
60
61void DistortionNode::createHUDSubgraph()
62{
63    // create the quad to visualize.
64    osg::Geometry* polyGeom = new osg::Geometry();
65
66    polyGeom->setSupportsDisplayList(false);
67
68    osg::Vec3 origin(0.0f,0.0f,0.0f);
69    osg::Vec3 xAxis(1.0f,0.0f,0.0f);
70    osg::Vec3 yAxis(0.0f,1.0f,0.0f);
71    osg::Vec3 zAxis(0.0f,0.0f,1.0f);
72    float height = 1024.0f;
73    float width = 1280.0f;
74    int noSteps = 50;
75   
76    osg::Vec3Array* vertices = new osg::Vec3Array;
77    osg::Vec2Array* texcoords = new osg::Vec2Array;
78    osg::Vec4Array* colors = new osg::Vec4Array;
79
80    osg::Vec3 bottom = origin;
81    osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
82    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
83   
84    osg::Vec2 bottom_texcoord(0.0f,0.0f);
85    osg::Vec2 dx_texcoord(1.0f/(float)(noSteps-1),0.0f);
86    osg::Vec2 dy_texcoord(0.0f,1.0f/(float)(noSteps-1));
87   
88    osg::Vec3 cursor = bottom;
89    osg::Vec2 texcoord = bottom_texcoord;
90    int i,j;
91    for(i=0;i<noSteps;++i)
92    {
93        osg::Vec3 cursor = bottom+dy*(float)i;
94        osg::Vec2 texcoord = bottom_texcoord+dy_texcoord*(float)i;
95        for(j=0;j<noSteps;++j)
96        {
97            vertices->push_back(cursor);
98            texcoords->push_back(osg::Vec2((sin(texcoord.x()*osg::PI-osg::PI*0.5)+1.0f)*0.5f,(sin(texcoord.y()*osg::PI-osg::PI*0.5)+1.0f)*0.5f));
99            colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
100           
101            cursor += dx;
102            texcoord += dx_texcoord;
103        }
104    }
105
106    // pass the created vertex array to the points geometry object.
107    polyGeom->setVertexArray(vertices);
108
109    polyGeom->setColorArray(colors);
110    polyGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
111
112    polyGeom->setTexCoordArray(0,texcoords);
113   
114
115    for(i=0;i<noSteps-1;++i)
116    {
117        osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
118        for(j=0;j<noSteps;++j)
119        {
120            elements->push_back(j+(i+1)*noSteps);
121            elements->push_back(j+(i)*noSteps);
122        }
123        polyGeom->addPrimitiveSet(elements);
124    }
125
126
127    // new we need to add the texture to the Drawable, we do so by creating a
128    // StateSet to contain the Texture StateAttribute.
129    osg::StateSet* stateset = new osg::StateSet;
130
131    osg::Texture2D* texture = new osg::Texture2D;
132//     texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST);
133//     texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST);
134    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
135    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
136    stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
137    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
138    polyGeom->setStateSet(stateset);
139   
140    _texture = texture;
141
142    osg::Geode* geode = new osg::Geode();
143    geode->addDrawable(polyGeom);
144
145    // create the hud.
146    osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
147    modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
148    modelview_abs->setMatrix(osg::Matrix::identity());
149    modelview_abs->addChild(geode);
150
151    osg::Projection* projection = new osg::Projection;
152    projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
153    projection->addChild(modelview_abs);
154
155    _hudSubgraph = projection;
156   
157    _localStateSet = new osg::StateSet;
158
159
160}
161
162
163void DistortionNode::traverse(osg::NodeVisitor& nv)
164{
165    if (nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR)
166    {
167        osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(&nv);
168        if (cullVisitor && _texture.valid() && _hudSubgraph.valid())
169        {
170            preRender(*cullVisitor);
171           
172            _hudSubgraph->accept(nv);
173           
174            return;
175        }
176    }
177   
178    Group::traverse(nv);
179}
180
181void DistortionNode::preRender(osgUtil::CullVisitor& cv)
182{   
183    // create the render to texture stage.
184    osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage;
185
186    // set up lighting.
187    // currently ignore lights in the scene graph itself..
188    // will do later.
189    osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->getStage();
190
191    // set up the background color and clear mask.
192    rtts->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
193    rtts->setClearMask(previous_stage->getClearMask());
194
195    // set up to charge the same RenderStageLighting is the parent previous stage.
196    rtts->setRenderStageLighting(previous_stage->getRenderStageLighting());
197
198
199    // record the render bin, to be restored after creation
200    // of the render to text
201    osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin();
202
203    // set the current renderbin to be the newly created stage.
204    cv.setCurrentRenderBin(rtts.get());
205
206    cv.pushStateSet(_localStateSet.get());
207
208    {
209
210        // traverse the subgraph
211        Group::traverse(cv);
212
213    }
214
215    cv.popStateSet();
216
217    // restore the previous renderbin.
218    cv.setCurrentRenderBin(previousRenderBin);
219
220    if (rtts->getRenderGraphList().size()==0 && rtts->getRenderBinList().size()==0)
221    {
222        // getting to this point means that all the subgraph has been
223        // culled by small feature culling or is beyond LOD ranges.
224        return;
225    }
226
227    int height = 1024;
228    int width  = 1024;
229
230
231    const osg::Viewport& viewport = *cv.getViewport();
232
233    // offset the impostor viewport from the center of the main window
234    // viewport as often the edges of the viewport might be obscured by
235    // other windows, which can cause image/reading writing problems.
236    int center_x = viewport.x()+viewport.width()/2;
237    int center_y = viewport.y()+viewport.height()/2;
238
239    osg::Viewport* new_viewport = new osg::Viewport;
240    new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height);
241    rtts->setViewport(new_viewport);
242   
243    _localStateSet->setAttribute(new_viewport);
244
245    // and the render to texture stage to the current stages
246    // dependancy list.
247    cv.getCurrentRenderBin()->getStage()->addToDependencyList(rtts.get());
248
249    // if one exist attach texture to the RenderToTextureStage.
250    if (_texture.valid()) rtts->setTexture(_texture.get());
251}
252
253
254int main( int argc, char **argv )
255{
256    // use an ArgumentParser object to manage the program arguments.
257    osg::ArgumentParser arguments(&argc,argv);
258
259    // set up the usage document, in case we need to print out how to use this program.
260    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
261    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
262    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
263   
264    // construct the viewer.
265    osgProducer::Viewer viewer(arguments);
266
267    // set up the value with sensible default event handlers.
268    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
269
270    // get details on keyboard and mouse bindings used by the viewer.
271    viewer.getUsage(*arguments.getApplicationUsage());
272
273    // if user request help write it out to cout.
274    if (arguments.read("-h") || arguments.read("--help"))
275    {
276        arguments.getApplicationUsage()->write(std::cout);
277        return 1;
278    }
279
280    // any option left unread are converted into errors to write out later.
281    arguments.reportRemainingOptionsAsUnrecognized();
282
283    // report any errors if they have occured when parsing the program aguments.
284    if (arguments.errors())
285    {
286        arguments.writeErrorMessages(std::cout);
287        return 1;
288    }
289   
290    if (arguments.argc()<=1)
291    {
292        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
293        return 1;
294    }
295
296   
297    // load the nodes from the commandline arguments.
298    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
299    if (!loadedModel)
300    {
301//        write_usage(osg::notify(osg::NOTICE),argv[0]);
302        return 1;
303    }
304   
305    // create a transform to spin the model.
306    DistortionNode* distortionNode = new DistortionNode;
307    distortionNode->addChild(loadedModel);
308
309    // add model to the viewer.
310    viewer.setSceneData( distortionNode );
311
312    // create the windows and run the threads.
313    viewer.realize();
314
315    while( !viewer.done() )
316    {
317        // wait for all cull and draw threads to complete.
318        viewer.sync();
319
320        // update the scene by traversing it with the the update visitor which will
321        // call all node update callbacks and animations.
322        viewer.update();
323         
324        // fire off the cull and draw traversals of the scene.
325        viewer.frame();
326       
327    }
328   
329    // wait for all cull and draw threads to complete before exit.
330    viewer.sync();
331
332    return 0;
333}
Note: See TracBrowser for help on using the browser.