root/OpenSceneGraph/trunk/examples/osgoccluder/osgoccluder.cpp @ 1904

Revision 1904, 10.9 kB (checked in by robert, 11 years ago)

Changed the ordering of the picking intersections.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgProducer/Viewer>
2
3#include <osg/MatrixTransform>
4#include <osg/Billboard>
5#include <osg/Geode>
6#include <osg/Group>
7#include <osg/Notify>
8#include <osg/LineSegment>
9
10#include <osgDB/Registry>
11#include <osgDB/ReadFile>
12#include <osgDB/WriteFile>
13
14#include <osgGA/TrackballManipulator>
15#include <osgGA/FlightManipulator>
16#include <osgGA/DriveManipulator>
17
18#include <osgUtil/Optimizer>
19#include <osgUtil/IntersectVisitor>
20
21#include <osg/OccluderNode>
22#include <osg/Geometry>
23#include <osg/ShapeDrawable>
24
25
26class OccluderEventHandler : public osgGA::GUIEventHandler
27{
28    public:
29   
30        OccluderEventHandler(osgProducer::Viewer* viewer):_viewer(viewer) {}
31   
32        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
33
34        virtual void accept(osgGA::GUIEventHandlerVisitor& v)
35        {
36            v.visit(*this);
37        }
38       
39        void addPoint(const osg::Vec3& pos);
40               
41        void endOccluder();
42       
43        osg::Group* rootNode() { return dynamic_cast<osg::Group*>(_viewer->getSceneData()); }
44       
45       
46        osgProducer::Viewer*                    _viewer;
47        osg::ref_ptr<osg::Group>                _occluders;
48        osg::ref_ptr<osg::ConvexPlanarOccluder> _convexPlanarOccluder;
49};
50
51bool OccluderEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
52{
53    switch(ea.getEventType())
54    {
55        case(osgGA::GUIEventAdapter::KEYDOWN):
56        {
57            if (ea.getKey()=='a')
58            {
59
60                float x = ea.getXnormalized();
61                float y = ea.getYnormalized();
62 
63                osgUtil::IntersectVisitor::HitList hitList;
64                if (!_viewer->computeIntersections(x,y,hitList))
65                {
66                     return true;
67                }
68
69                if (!hitList.empty())
70                {
71
72                    osgUtil::Hit& hit = hitList.front();
73                    addPoint(hit.getWorldIntersectPoint());
74                }
75
76                return true;
77            }
78            else if (ea.getKey()=='e')
79            {
80                endOccluder();
81                return true;
82            }
83            else if (ea.getKey()=='O')
84            {
85                if (_occluders.valid())
86                {
87                   
88                    if (osgDB::writeNodeFile(*_occluders,"saved_occluders.osg"))
89                        std::cout<<"saved occluders to 'saved_occluders.osg'"<<std::endl;
90                }
91                else
92                {
93                    std::cout<<"no occluders to save"<<std::endl;
94                }
95                return true;
96            }
97            return false;
98        }
99
100        default:
101            return false;
102    }
103}
104
105void OccluderEventHandler::addPoint(const osg::Vec3& pos)
106{
107    std::cout<<"add point "<<pos<<std::endl;
108   
109    if (!_convexPlanarOccluder.valid()) _convexPlanarOccluder = new osg::ConvexPlanarOccluder;
110   
111    osg::ConvexPlanarPolygon& occluder = _convexPlanarOccluder->getOccluder();
112    occluder.add(pos);
113
114//     
115//     osg::BoundingSphere bs = rootNode()->getBound();
116//
117//     osg::ShapeDrawable* sd = new osg::ShapeDrawable(new osg::Sphere(pos,bs.radius()*0.001f));
118//     osg::Geode* geode = new osg::Geode;
119//     geode->addDrawable(sd);
120//
121//     rootNode()->addChild(geode);
122//
123   
124}
125               
126void OccluderEventHandler::endOccluder()
127{
128    if (_convexPlanarOccluder.valid())
129    {
130        if (_convexPlanarOccluder->getOccluder().getVertexList().size()>=3)
131        {
132            osg::OccluderNode* occluderNode = new osg::OccluderNode;
133            occluderNode->setOccluder(_convexPlanarOccluder.get());
134
135            if (!_occluders.valid())
136            {
137                _occluders = new osg::Group;
138                if (rootNode()) rootNode()->addChild(_occluders.get());
139            }
140            _occluders->addChild(occluderNode);
141
142            std::cout<<"created occluder"<<std::endl;
143        }
144        else
145        {
146            std::cout<<"Occluder requires at least 3 points to create occluder."<<std::endl;
147        }
148    }
149    else
150    {
151        std::cout<<"No occluder points to create occluder with."<<std::endl;
152    }
153   
154    // reset current occluder.
155    _convexPlanarOccluder = NULL;
156}
157
158
159osg::Node* createOccluder(const osg::Vec3& v1,const osg::Vec3& v2,const osg::Vec3& v3,const osg::Vec3& v4,float holeRatio=-1.0f)
160{
161   // create and occluder which will site along side the loadmodel model.
162    osg::OccluderNode* occluderNode = new osg::OccluderNode;
163
164    // create the convex planer occluder
165    osg::ConvexPlanarOccluder* cpo = new osg::ConvexPlanarOccluder;
166
167    // attach it to the occluder node.
168    occluderNode->setOccluder(cpo);
169    occluderNode->setName("occluder");
170   
171    // set the occluder up for the front face of the bounding box.
172    osg::ConvexPlanarPolygon& occluder = cpo->getOccluder();
173    occluder.add(v1);
174    occluder.add(v2);
175    occluder.add(v3);
176    occluder.add(v4);
177
178    // create a whole at the center of the occluder if needed.
179    if (holeRatio>0.0f)
180    {
181        // create hole.
182        float ratio = holeRatio;
183        float one_minus_ratio = 1-ratio;
184        osg::Vec3 center = (v1+v2+v3+v4)*0.25f;
185        osg::Vec3 v1dash = v1*ratio + center*one_minus_ratio;
186        osg::Vec3 v2dash = v2*ratio + center*one_minus_ratio;
187        osg::Vec3 v3dash = v3*ratio + center*one_minus_ratio;
188        osg::Vec3 v4dash = v4*ratio + center*one_minus_ratio;
189
190        osg::ConvexPlanarPolygon hole;
191        hole.add(v1dash);
192        hole.add(v2dash);
193        hole.add(v3dash);
194        hole.add(v4dash);
195
196        cpo->addHole(hole);
197    }   
198   
199
200   // create a drawable for occluder.
201    osg::Geometry* geom = new osg::Geometry;
202   
203    osg::Vec3Array* coords = new osg::Vec3Array(occluder.getVertexList().begin(),occluder.getVertexList().end());
204    geom->setVertexArray(coords);
205   
206    osg::Vec4Array* colors = new osg::Vec4Array(1);
207    (*colors)[0].set(1.0f,1.0f,1.0f,0.5f);
208    geom->setColorArray(colors);
209    geom->setColorBinding(osg::Geometry::BIND_OVERALL);
210   
211    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
212   
213    osg::Geode* geode = new osg::Geode;
214    geode->addDrawable(geom);
215   
216    osg::StateSet* stateset = new osg::StateSet;
217    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
218    stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
219    stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
220   
221    geom->setStateSet(stateset);
222   
223    // add the occluder geode as a child of the occluder,
224    // as the occluder can't self occlude its subgraph the
225    // geode will never be occluder by this occluder.
226    occluderNode->addChild(geode);   
227   
228    return occluderNode;
229 
230 }
231
232osg::Group* createOccludersAroundModel(osg::Node* model)
233{
234    osg::Group* scene = new osg::Group;
235    scene->setName("rootgroup");
236
237
238    // add the loaded model into a the scene group.
239    scene->addChild(model);
240    model->setName("model");
241
242    // get the bounding volume of the model.
243    const osg::BoundingSphere bs = model->getBound();
244   
245    // create a bounding box around the sphere.
246    osg::BoundingBox bb;
247    bb.expandBy(bs);
248
249   // front
250   scene->addChild(createOccluder(bb.corner(0),
251                                  bb.corner(1),
252                                  bb.corner(5),
253                                  bb.corner(4)));
254
255   // right side
256   scene->addChild(createOccluder(bb.corner(1),
257                                  bb.corner(3),
258                                  bb.corner(7),
259                                  bb.corner(5)));
260
261   // left side
262   scene->addChild(createOccluder(bb.corner(2),
263                                  bb.corner(0),
264                                  bb.corner(4),
265                                  bb.corner(6)));
266
267   // back side
268   scene->addChild(createOccluder(bb.corner(3),
269                                  bb.corner(2),
270                                  bb.corner(6),
271                                  bb.corner(7),
272                                  0.5f)); // create a hole half the size of the occluder.
273
274    return scene;
275}
276
277
278int main( int argc, char **argv )
279{
280
281    // use an ArgumentParser object to manage the program arguments.
282    osg::ArgumentParser arguments(&argc,argv);
283
284    // set up the usage document, in case we need to print out how to use this program.
285    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of convex planer occluders.");
286    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
287    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
288    arguments.getApplicationUsage()->addCommandLineOption("-m","Mannually create occluders");
289   
290    // initialize the viewer.
291    osgProducer::Viewer viewer(arguments);
292
293    // set up the value with sensible default event handlers.
294    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
295
296    bool manuallyCreateOccluders = false;
297    while (arguments.read("-m")) { manuallyCreateOccluders = true; }
298
299    if (manuallyCreateOccluders)
300    {
301        viewer.getEventHandlerList().push_front(new OccluderEventHandler(&viewer));
302    }
303
304    // get details on keyboard and mouse bindings used by the viewer.
305    viewer.getUsage(*arguments.getApplicationUsage());
306
307    // if user request help write it out to cout.
308    if (arguments.read("-h") || arguments.read("--help"))
309    {
310        arguments.getApplicationUsage()->write(std::cout);
311        return 1;
312    }
313
314    // any option left unread are converted into errors to write out later.
315    arguments.reportRemainingOptionsAsUnrecognized();
316
317    // report any errors if they have occured when parsing the program aguments.
318    if (arguments.errors())
319    {
320        arguments.writeErrorMessages(std::cout);
321        return 1;
322    }
323
324    // load the nodes from the commandline arguments.
325    osg::Node* loadedmodel = osgDB::readNodeFiles(arguments);
326    if (!loadedmodel)
327    {
328        return 1;
329    }
330   
331    // run optimization over the scene graph
332    osgUtil::Optimizer optimzer;
333    optimzer.optimize(loadedmodel);
334
335    // add the occluders to the loaded model.
336    osg::ref_ptr<osg::Group> rootnode;
337   
338    if (manuallyCreateOccluders)
339    {
340        rootnode = new osg::Group;
341        rootnode->addChild(loadedmodel);
342    }
343    else   
344    {
345        rootnode = createOccludersAroundModel(loadedmodel);
346    }
347   
348     
349    // add a viewport to the viewer and attach the scene graph.
350    viewer.setSceneData( rootnode.get() );
351
352
353    // create the windows and run the threads.
354    viewer.realize();
355
356
357    while( !viewer.done() )
358    {
359        // wait for all cull and draw threads to complete.
360        viewer.sync();
361
362        // update the scene by traversing it with the the update visitor which will
363        // call all node update callbacks and animations.
364        viewer.update();
365         
366        // fire off the cull and draw traversals of the scene.
367        viewer.frame();
368       
369    }
370
371    viewer.sync();
372
373    return 0;
374}
Note: See TracBrowser for help on using the browser.