root/OpenSceneGraph/trunk/examples/osgmanipulator/osgmanipulator.cpp @ 6148

Revision 6148, 14.4 kB (checked in by robert, 7 years ago)

Changed osgManipulator::Dragger::handle(..) method to use a nested PointerInfo?
class to encapsulate the pixel coords, SceneView? and picking operations in prep for
making the code more general purpose, and less reliant on classes like osgUtil::SceneView? and osgUtil::IntersectVisitor?.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgDB/ReadFile>
2#include <osgUtil/Optimizer>
3#include <osgProducer/Viewer>
4#include <osg/CoordinateSystemNode>
5#include <osgText/Text>
6
7#include <osgManipulator/CommandManager>
8#include <osgManipulator/TabBoxDragger>
9#include <osgManipulator/TabPlaneDragger>
10#include <osgManipulator/TabPlaneTrackballDragger>
11#include <osgManipulator/TrackballDragger>
12#include <osgManipulator/Translate1DDragger>
13#include <osgManipulator/Translate2DDragger>
14#include <osgManipulator/TranslateAxisDragger>
15
16osgManipulator::Dragger* createDragger(const std::string& name)
17{
18    osgManipulator::Dragger* dragger = 0;
19    if ("TabPlaneDragger" == name)
20    {
21        osgManipulator::TabPlaneDragger* d = new osgManipulator::TabPlaneDragger();
22        d->setupDefaultGeometry();
23        dragger = d;
24    }
25    else if ("TabPlaneTrackballDragger" == name)
26    {
27        osgManipulator::TabPlaneTrackballDragger* d = new osgManipulator::TabPlaneTrackballDragger();
28        d->setupDefaultGeometry();
29        dragger = d;
30    }
31    else if ("TrackballDragger" == name)
32    {
33        osgManipulator::TrackballDragger* d = new osgManipulator::TrackballDragger();
34        d->setupDefaultGeometry();
35        dragger = d;
36    }
37    else if ("Translate1DDragger" == name)
38    {
39        osgManipulator::Translate1DDragger* d = new osgManipulator::Translate1DDragger();
40        d->setupDefaultGeometry();
41        dragger = d;
42    }
43    else if ("Translate2DDragger" == name)
44    {
45        osgManipulator::Translate2DDragger* d = new osgManipulator::Translate2DDragger();
46        d->setupDefaultGeometry();
47        dragger = d;
48    }
49    else if ("TranslateAxisDragger" == name)
50    {
51        osgManipulator::TranslateAxisDragger* d = new osgManipulator::TranslateAxisDragger();
52        d->setupDefaultGeometry();
53        dragger = d;
54    }
55    else
56    {
57        osgManipulator::TabBoxDragger* d = new osgManipulator::TabBoxDragger();
58        d->setupDefaultGeometry();
59        dragger = d;
60    }
61 
62    return dragger;
63}
64
65osg::Node* createHUD()
66{
67    osg::Geode* geode = new osg::Geode();
68   
69    std::string timesFont("fonts/arial.ttf");
70
71    osg::StateSet* stateset = geode->getOrCreateStateSet();
72    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
73
74    osgText::Text* text = new  osgText::Text;
75    geode->addDrawable( text );
76
77    osg::Vec3 position(50.0f,50.0f,0.0f);
78    text->setPosition(position);
79    text->setText("Use the Tab key to switch between the trackball and pick modes.");
80    text->setFont(timesFont);
81
82    osg::Camera* camera = new osg::Camera;
83
84    // set the projection matrix
85    camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
86
87    // set the view matrix   
88    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
89    camera->setViewMatrix(osg::Matrix::identity());
90
91    // only clear the depth buffer
92    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
93
94    // draw subgraph after main camera view.
95    camera->setRenderOrder(osg::Camera::POST_RENDER);
96
97    camera->addChild(geode);
98   
99    return camera;
100}
101
102
103bool computePixelCoords(osgProducer::Viewer* viewer,float x,float y,unsigned int cameraNum,float& pixel_x,float& pixel_y)
104{
105    Producer::KeyboardMouse* km = viewer->getKeyboardMouse();
106    if (!km) return false;
107           
108    if (cameraNum>=viewer->getNumberOfCameras()) return false;
109
110    Producer::Camera* camera=viewer->getCamera(cameraNum);
111    Producer::RenderSurface* rs = camera->getRenderSurface();
112
113    Producer::InputArea* inputArea = km->getInputArea();
114    if( inputArea != NULL )
115    {
116        // first locate which InputRectange is appropriate for specified RenderSurface.
117        unsigned int i;
118        for(i=0;i<inputArea->getNumRenderSurfaces();++i)
119        {
120            if (inputArea->getRenderSurface(i)==rs) break;
121        }
122       
123        // the RenderSurface isn't in the InputArea list.. therefore cannot make mouse coords to it.
124        if (i==inputArea->getNumRenderSurfaces()) return false;
125
126        // we have a valid InputRectangle
127        Producer::RenderSurface::InputRectangle ir = inputArea->getRenderSurface(i)->getInputRectangle();
128
129        float rx = (x-ir.left())/ir.width();
130        float ry = (y-ir.bottom())/ir.height();
131       
132        int wx, wy;
133        unsigned int w, h;
134        rs->getWindowRectangle( wx, wy, w, h );
135
136        pixel_x = ((float)w)* rx;
137        pixel_y = ((float)h)* ry;
138    }
139    else
140    {
141        float rx = (x+1.0f)*0.5f;
142        float ry = (y+1.0f)*0.5f;
143
144        int wx, wy;
145        unsigned int w, h;
146        rs->getWindowRectangle( wx, wy, w, h );
147
148        pixel_x = ((float)w)* rx;
149        pixel_y = ((float)h)* ry;
150    }
151    return true;
152}
153
154osg::Node* addDraggerToScene(osg::Node* scene, osgManipulator::CommandManager* cmdMgr, const std::string& name)
155{
156    scene->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
157
158    osgManipulator::Selection* selection = new osgManipulator::Selection;
159    selection->addChild(scene);
160
161    osgManipulator::Dragger* dragger = createDragger(name);
162
163    osg::Group* root = new osg::Group;
164    root->addChild(dragger);
165    root->addChild(selection);
166    root->addChild(createHUD());
167
168    float scale = scene->getBound().radius() * 1.6;
169    dragger->setMatrix(osg::Matrix::scale(scale, scale, scale) *
170                       osg::Matrix::translate(scene->getBound().center()));
171    cmdMgr->connect(*dragger, *selection);
172
173    return root;
174}
175
176class PickModeHandler : public osgGA::GUIEventHandler
177{
178    public:
179        enum Modes
180        {
181            VIEW = 0,
182            PICK
183        };
184
185        PickModeHandler(osgProducer::Viewer *viewer) : osgGA::GUIEventHandler(),
186                                                       _viewer(viewer), _mode(VIEW), _activeDragger(0)
187        {
188        }       
189       
190        bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa,
191                    osg::Object*, osg::NodeVisitor*)
192        {
193            if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Tab &&
194                ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN &&
195                _activeDragger == 0)
196            {
197                _mode = ! _mode;
198            }
199           
200            if (VIEW == _mode) return false;
201
202            for(unsigned int i=0;i<_viewer->getNumberOfCameras();++i)
203            {
204               
205                if ((ea.getEventType() == osgGA::GUIEventAdapter::PUSH) &&
206                    _viewer->computeIntersections(ea.getX(), ea.getY(), i, _pointer.hitList))
207                {
208                    float pixel_x,pixel_y;
209                    if (computePixelCoords(_viewer,ea.getX(),ea.getY(),i,pixel_x,pixel_y))
210                    {
211                        Producer::Camera* camera=_viewer->getCamera(i);
212
213                        osgProducer::OsgSceneHandler* sh = dynamic_cast<osgProducer::OsgSceneHandler*>(camera->getSceneHandler());
214                        osgUtil::SceneView* sv = sh ? sh->getSceneView() : 0;
215                        if (! sv) continue;
216                       
217                        _pointer.pixel_x = int(pixel_x+0.5);
218                        _pointer.pixel_y = int(pixel_y+0.5);
219                        _pointer.sv = sv;
220                        _pointer.hitIter = _pointer.hitList.begin();
221
222                        for (osg::NodePath::iterator itr = _pointer.hitList.front().getNodePath().begin();
223                             itr != _pointer.hitList.front().getNodePath().end();
224                             ++itr)
225                        {
226                            osgManipulator::Dragger* dragger = dynamic_cast<osgManipulator::Dragger*>(*itr);
227                            if (dragger)
228                            {
229
230                                dragger->handle(_pointer, ea, aa);
231                                _activeDragger = dragger;
232                                break;
233                            }                   
234                        }
235                    }
236                }
237               
238                switch (ea.getEventType())
239                {
240                    case osgGA::GUIEventAdapter::DRAG:
241                    case osgGA::GUIEventAdapter::RELEASE:
242                        if (_activeDragger)
243                        {
244                            float pixel_x,pixel_y;
245                            if (computePixelCoords(_viewer,ea.getX(),ea.getY(),i,pixel_x,pixel_y))
246                            {
247                                Producer::Camera* camera=_viewer->getCamera(i);
248
249                                osgProducer::OsgSceneHandler* sh = dynamic_cast<osgProducer::OsgSceneHandler*>(camera->getSceneHandler());
250                                osgUtil::SceneView* sv = sh ? sh->getSceneView() : 0;
251                                if (_activeDragger && sv)
252                                {
253                                    _pointer.pixel_x = int(pixel_x+0.5);
254                                    _pointer.pixel_y = int(pixel_y+0.5);
255                                    _pointer.sv = sv;
256                                    _pointer.hitIter = _pointer.hitList.begin();
257
258                                    _activeDragger->handle(_pointer, ea, aa);
259                                }
260                            }
261                        }
262                        break;
263
264                    default:
265                        break;
266                }
267                if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
268                {
269                    _activeDragger = 0;
270                    _pointer.hitList.clear();
271                }
272            }
273            return true;
274        }
275       
276    private:
277        osgProducer::Viewer* _viewer;
278        unsigned int _mode;
279        osgManipulator::Dragger* _activeDragger;
280        osgManipulator::Dragger::PointerInfo _pointer;
281};
282
283int main( int argc, char **argv )
284{
285
286    // use an ArgumentParser object to manage the program arguments.
287    osg::ArgumentParser arguments(&argc,argv);
288   
289    // set up the usage document, in case we need to print out how to use this program.
290    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
291    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
292    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
293    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
294    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
295    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
296    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
297    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
298    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");
299
300    arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation");
301   
302
303    // construct the viewer.
304    osgProducer::Viewer viewer(arguments);
305
306    // set up the value with sensible default event handlers.
307    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
308
309    // get details on keyboard and mouse bindings used by the viewer.
310    viewer.getUsage(*arguments.getApplicationUsage());
311
312    // if user request help write it out to cout.
313    bool helpAll = arguments.read("--help-all");
314    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
315                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
316                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
317    if (helpType)
318    {
319        arguments.getApplicationUsage()->write(std::cout, helpType);
320        return 1;
321    }
322
323    // report any errors if they have occurred when parsing the program arguments.
324    if (arguments.errors())
325    {
326        arguments.writeErrorMessages(std::cout);
327        return 1;
328    }
329   
330    if (arguments.argc()<=1)
331    {
332        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
333        return 1;
334    }
335
336    std::string dragger_name = "TabBoxDragger";
337    arguments.read("--dragger", dragger_name);
338
339    osg::Timer_t start_tick = osg::Timer::instance()->tick();
340
341    // read the scene from the list of file specified command line args.
342    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
343
344    // if no model has been successfully loaded report failure.
345    if (!loadedModel)
346    {
347        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
348        return 1;
349    }
350
351    // any option left unread are converted into errors to write out later.
352    arguments.reportRemainingOptionsAsUnrecognized();
353
354    // report any errors if they have occurred when parsing the program arguments.
355    if (arguments.errors())
356    {
357        arguments.writeErrorMessages(std::cout);
358    }
359
360    osg::Timer_t end_tick = osg::Timer::instance()->tick();
361
362    std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;
363
364
365    // optimize the scene graph, remove redundant nodes and state etc.
366    osgUtil::Optimizer optimizer;
367    optimizer.optimize(loadedModel.get());
368
369    osg::ref_ptr<osgManipulator::CommandManager> cmdMgr = new osgManipulator::CommandManager;
370   
371    // pass the loaded scene graph to the viewer.
372    viewer.setSceneData(addDraggerToScene(loadedModel.get(), cmdMgr.get(), dragger_name));
373
374    viewer.getEventHandlerList().push_front(new PickModeHandler(&viewer));
375
376    // create the windows and run the threads.
377    viewer.realize();
378
379    while( !viewer.done() )
380    {
381        // wait for all cull and draw threads to complete.
382        viewer.sync();
383
384        // update the scene by traversing it with the the update visitor which will
385        // call all node update callbacks and animations.
386        viewer.update();
387         
388        // fire off the cull and draw traversals of the scene.
389        viewer.frame();
390       
391    }
392   
393    // wait for all cull and draw threads to complete.
394    viewer.sync();
395
396    // run a clean up frame to delete all OpenGL objects.
397    viewer.cleanup_frame();
398
399    // wait for all the clean up frame to complete.
400    viewer.sync();
401
402    return 0;
403}
Note: See TracBrowser for help on using the browser.