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

Revision 2688, 10.0 kB (checked in by robert, 10 years ago)

Attempts to fix compile problems under IRIX due to namespace problems.

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