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

Revision 6281, 11.0 kB (checked in by robert, 8 years ago)

Moved osgProducer and osgproducerviewer out into their own repository.

Clean up the source for remaining references to osgProducer/Producer.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1// --c++--
2#include <osgDB/ReadFile>
3#include <osgUtil/Optimizer>
4#include <osgViewer/Viewer>
5#include <osg/CoordinateSystemNode>
6#include <osgText/Text>
7
8#include <osgManipulator/CommandManager>
9#include <osgManipulator/TabBoxDragger>
10#include <osgManipulator/TabPlaneDragger>
11#include <osgManipulator/TabPlaneTrackballDragger>
12#include <osgManipulator/TrackballDragger>
13#include <osgManipulator/Translate1DDragger>
14#include <osgManipulator/Translate2DDragger>
15#include <osgManipulator/TranslateAxisDragger>
16
17#include <iostream>
18
19osgManipulator::Dragger* createDragger(const std::string& name)
20{
21    osgManipulator::Dragger* dragger = 0;
22    if ("TabPlaneDragger" == name)
23    {
24        osgManipulator::TabPlaneDragger* d = new osgManipulator::TabPlaneDragger();
25        d->setupDefaultGeometry();
26        dragger = d;
27    }
28    else if ("TabPlaneTrackballDragger" == name)
29    {
30        osgManipulator::TabPlaneTrackballDragger* d = new osgManipulator::TabPlaneTrackballDragger();
31        d->setupDefaultGeometry();
32        dragger = d;
33    }
34    else if ("TrackballDragger" == name)
35    {
36        osgManipulator::TrackballDragger* d = new osgManipulator::TrackballDragger();
37        d->setupDefaultGeometry();
38        dragger = d;
39    }
40    else if ("Translate1DDragger" == name)
41    {
42        osgManipulator::Translate1DDragger* d = new osgManipulator::Translate1DDragger();
43        d->setupDefaultGeometry();
44        dragger = d;
45    }
46    else if ("Translate2DDragger" == name)
47    {
48        osgManipulator::Translate2DDragger* d = new osgManipulator::Translate2DDragger();
49        d->setupDefaultGeometry();
50        dragger = d;
51    }
52    else if ("TranslateAxisDragger" == name)
53    {
54        osgManipulator::TranslateAxisDragger* d = new osgManipulator::TranslateAxisDragger();
55        d->setupDefaultGeometry();
56        dragger = d;
57    }
58    else
59    {
60        osgManipulator::TabBoxDragger* d = new osgManipulator::TabBoxDragger();
61        d->setupDefaultGeometry();
62        dragger = d;
63    }
64 
65    return dragger;
66}
67
68osg::Node* createHUD()
69{
70    osg::Geode* geode = new osg::Geode();
71   
72    std::string timesFont("fonts/arial.ttf");
73
74    osg::StateSet* stateset = geode->getOrCreateStateSet();
75    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
76
77    osgText::Text* text = new  osgText::Text;
78    geode->addDrawable( text );
79
80    osg::Vec3 position(50.0f,50.0f,0.0f);
81    text->setPosition(position);
82    text->setText("Use the Tab key to switch between the trackball and pick modes.");
83    text->setFont(timesFont);
84
85    osg::Camera* camera = new osg::Camera;
86
87    // set the projection matrix
88    camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
89
90    // set the view matrix   
91    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
92    camera->setViewMatrix(osg::Matrix::identity());
93
94    // only clear the depth buffer
95    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
96
97    // draw subgraph after main camera view.
98    camera->setRenderOrder(osg::Camera::POST_RENDER);
99
100    camera->addChild(geode);
101   
102    return camera;
103}
104
105osg::Node* addDraggerToScene(osg::Node* scene, osgManipulator::CommandManager* cmdMgr, const std::string& name)
106{
107    scene->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
108
109    osgManipulator::Selection* selection = new osgManipulator::Selection;
110    selection->addChild(scene);
111
112    osgManipulator::Dragger* dragger = createDragger(name);
113
114    osg::Group* root = new osg::Group;
115    root->addChild(dragger);
116    root->addChild(selection);
117    root->addChild(createHUD());
118
119    float scale = scene->getBound().radius() * 1.6;
120    dragger->setMatrix(osg::Matrix::scale(scale, scale, scale) *
121                       osg::Matrix::translate(scene->getBound().center()));
122    cmdMgr->connect(*dragger, *selection);
123
124    return root;
125}
126
127class PickModeHandler : public osgGA::GUIEventHandler
128{
129    public:
130        enum Modes
131        {
132            VIEW = 0,
133            PICK
134        };
135
136        PickModeHandler():
137            _mode(VIEW),
138            _activeDragger(0)
139        {
140        }       
141       
142        bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa,
143                    osg::Object*, osg::NodeVisitor*)
144        {
145            osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
146            if (!view) return false;
147
148            if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Tab &&
149                ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN &&
150                _activeDragger == 0)
151            {
152                _mode = ! _mode;
153            }
154           
155            if (VIEW == _mode) return false;
156
157            switch (ea.getEventType())
158            {
159                case osgGA::GUIEventAdapter::PUSH:
160                {
161                    osgUtil::LineSegmentIntersector::Intersections intersections;
162
163                    _pointer.reset();
164
165                    if (view->computeIntersections(ea.getX(),ea.getY(),intersections))
166                    {
167                        _pointer.setCamera(view->getCamera());
168                        _pointer.setMousePosition(ea.getX(), ea.getY());
169
170                        for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
171                            hitr != intersections.end();
172                            ++hitr)
173                        {
174                            _pointer.addIntersection(hitr->nodePath, hitr->getLocalIntersectPoint());
175                        }
176                        for (osg::NodePath::iterator itr = _pointer._hitList.front().first.begin();
177                             itr != _pointer._hitList.front().first.end();
178                             ++itr)
179                        {
180                            osgManipulator::Dragger* dragger = dynamic_cast<osgManipulator::Dragger*>(*itr);
181                            if (dragger)
182                            {
183
184                                dragger->handle(_pointer, ea, aa);
185                                _activeDragger = dragger;
186                                break;
187                            }                   
188                        }
189                    }
190                }
191                case osgGA::GUIEventAdapter::DRAG:
192                case osgGA::GUIEventAdapter::RELEASE:
193                {
194                    if (_activeDragger)
195                    {
196                        _pointer._hitIter = _pointer._hitList.begin();
197                        _pointer.setCamera(view->getCamera());
198                        _pointer.setMousePosition(ea.getX(), ea.getY());
199
200                        _activeDragger->handle(_pointer, ea, aa);
201                    }
202                    break;
203                }
204                default:
205                    break;
206            }
207
208            if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
209            {
210                _activeDragger = 0;
211                _pointer.reset();
212            }
213
214            return true;
215        }
216       
217    private:
218        unsigned int _mode;
219        osgManipulator::Dragger* _activeDragger;
220        osgManipulator::PointerInfo _pointer;
221};
222
223int main( int argc, char **argv )
224{
225
226    // use an ArgumentParser object to manage the program arguments.
227    osg::ArgumentParser arguments(&argc,argv);
228   
229    // set up the usage document, in case we need to print out how to use this program.
230    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
231    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
232    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
233    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
234    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
235    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
236    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
237    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
238    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");
239
240    arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation");
241   
242
243    // construct the viewer.
244    osgViewer::Viewer viewer;
245
246    // get details on keyboard and mouse bindings used by the viewer.
247    viewer.getUsage(*arguments.getApplicationUsage());
248
249    // if user request help write it out to cout.
250    bool helpAll = arguments.read("--help-all");
251    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
252                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
253                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
254    if (helpType)
255    {
256        arguments.getApplicationUsage()->write(std::cout, helpType);
257        return 1;
258    }
259
260    // report any errors if they have occurred when parsing the program arguments.
261    if (arguments.errors())
262    {
263        arguments.writeErrorMessages(std::cout);
264        return 1;
265    }
266   
267    if (arguments.argc()<=1)
268    {
269        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
270        return 1;
271    }
272
273    std::string dragger_name = "TabBoxDragger";
274    arguments.read("--dragger", dragger_name);
275
276    osg::Timer_t start_tick = osg::Timer::instance()->tick();
277
278    // read the scene from the list of file specified command line args.
279    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
280
281    // if no model has been successfully loaded report failure.
282    if (!loadedModel)
283    {
284        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
285        return 1;
286    }
287
288    // any option left unread are converted into errors to write out later.
289    arguments.reportRemainingOptionsAsUnrecognized();
290
291    // report any errors if they have occurred when parsing the program arguments.
292    if (arguments.errors())
293    {
294        arguments.writeErrorMessages(std::cout);
295    }
296
297    osg::Timer_t end_tick = osg::Timer::instance()->tick();
298
299    std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;
300
301
302    // optimize the scene graph, remove redundant nodes and state etc.
303    osgUtil::Optimizer optimizer;
304    optimizer.optimize(loadedModel.get());
305
306    osg::ref_ptr<osgManipulator::CommandManager> cmdMgr = new osgManipulator::CommandManager;
307   
308    // pass the loaded scene graph to the viewer.
309    viewer.setSceneData(addDraggerToScene(loadedModel.get(), cmdMgr.get(), dragger_name));
310
311    viewer.addEventHandler(new PickModeHandler());
312
313    return viewer.run();
314}
Note: See TracBrowser for help on using the browser.