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

Revision 6941, 11.9 kB (checked in by robert, 8 years ago)

From Martin Lavery and Robert Osfield, Updated examples to use a variation of the MIT License

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