root/OpenSceneGraph/trunk/examples/osgkeyboardmouse/osgkeyboardmouse.cpp @ 5676

Revision 5676, 12.8 kB (checked in by robert, 8 years ago)

Added support for osgUtil::Intersectors being in WINDOW, PROJECTION, VIEW or MODEL coordinates

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
2//
3// Simple example of use of Producer::RenderSurface + KeyboardMouseCallback + SceneView
4// example that provides the user with control over view position with basic picking.
5
6#include <Producer/RenderSurface>
7#include <Producer/KeyboardMouse>
8#include <Producer/Trackball>
9
10#include <osg/Timer>
11#include <osg/io_utils>
12#include <osg/observer_ptr>
13
14#include <osgUtil/SceneView>
15#include <osgUtil/IntersectVisitor>
16#include <osgUtil/IntersectionVisitor>
17
18#include <osgDB/ReadFile>
19#include <osgDB/WriteFile>
20
21#include <osgGA/SimpleViewer>
22#include <osgGA/TrackballManipulator>
23#include <osgGA/StateSetManipulator>
24
25#include <osgFX/Scribe>
26
27// ----------- Begining of glue classes to adapter Producer's keyboard mouse events to osgGA's abstraction events.
28class MyKeyboardMouseCallback : public Producer::KeyboardMouseCallback
29{
30public:
31
32    MyKeyboardMouseCallback(osgGA::EventQueue* eventQueue) :
33        _done(false),
34        _eventQueue(eventQueue)
35    {
36    }
37
38    virtual void shutdown()
39    {
40        _done = true;
41    }
42
43    virtual void specialKeyPress( Producer::KeyCharacter key )
44    {
45        if (key==Producer::KeyChar_Escape)
46                    shutdown();
47
48        _eventQueue->keyPress( (osgGA::GUIEventAdapter::KeySymbol) key );
49    }
50
51    virtual void specialKeyRelease( Producer::KeyCharacter key )
52    {
53        _eventQueue->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) key );
54    }
55
56    virtual void keyPress( Producer::KeyCharacter key)
57    {
58        _eventQueue->keyPress( (osgGA::GUIEventAdapter::KeySymbol) key );
59    }
60
61    virtual void keyRelease( Producer::KeyCharacter key)
62    {
63        _eventQueue->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) key );
64    }
65
66    virtual void mouseMotion( float mx, float my )
67    {
68        _eventQueue->mouseMotion( mx, my );
69    }
70
71    virtual void buttonPress( float mx, float my, unsigned int mbutton )
72    {
73        _eventQueue->mouseButtonPress(mx, my, mbutton);
74    }
75   
76    virtual void buttonRelease( float mx, float my, unsigned int mbutton )
77    {
78        _eventQueue->mouseButtonRelease(mx, my, mbutton);
79    }
80
81    bool done() { return _done; }
82
83private:
84
85    bool                                _done;
86    osg::ref_ptr<osgGA::EventQueue>     _eventQueue;
87};
88
89class MyActionAdapter : public osgGA::GUIActionAdapter, public osg::Referenced
90{
91public:
92    // Override from GUIActionAdapter
93    virtual void requestRedraw() {}
94
95    // Override from GUIActionAdapter
96    virtual void requestContinuousUpdate(bool =true) {}
97
98    // Override from GUIActionAdapter
99    virtual void requestWarpPointer(float ,float ) {}
100   
101};
102
103// ----------- End of glue classes to adapter Producer's keyboard mouse events to osgGA's abstraction events.
104
105
106class CreateModelToSaveVisitor : public osg::NodeVisitor
107{
108public:
109
110    CreateModelToSaveVisitor():
111        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)       
112    {
113        _group = new osg::Group;
114        _addToModel = false;
115    }
116   
117    virtual void apply(osg::Node& node)
118    {
119        osgFX::Scribe* scribe = dynamic_cast<osgFX::Scribe*>(&node);
120        if (scribe)
121        {
122            for(unsigned int i=0; i<scribe->getNumChildren(); ++i)
123            {
124                _group->addChild(scribe->getChild(i));
125            }
126        }
127        else
128        {
129            traverse(node);
130        }
131    }
132   
133    osg::ref_ptr<osg::Group> _group;
134    bool _addToModel;
135};
136
137// class to handle events with a pick
138class PickHandler : public osgGA::GUIEventHandler {
139public:
140
141    PickHandler(osgUtil::SceneView* sceneView):
142        _sceneView(sceneView),
143        _mx(0.0),_my(0.0) {}
144
145    ~PickHandler() {}
146
147    bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
148    {
149        switch(ea.getEventType())
150        {
151            case(osgGA::GUIEventAdapter::KEYUP):
152            {
153                if (ea.getKey()=='s')
154                {
155                    saveSelectedModel();
156                }
157                return false;
158            }
159            case(osgGA::GUIEventAdapter::PUSH):
160            case(osgGA::GUIEventAdapter::MOVE):
161            {
162                _mx = ea.getX();
163                _my = ea.getY();
164                return false;
165            }
166            case(osgGA::GUIEventAdapter::RELEASE):
167            {
168                if (_mx == ea.getX() && _my == ea.getY())
169                {
170                    // only do a pick if the mouse hasn't moved
171                    pick(ea);
172                }
173                return true;
174            }   
175
176            default:
177                return false;
178        }
179    }
180
181    void pick(const osgGA::GUIEventAdapter& ea)
182    {
183
184        osg::Node* scene = _sceneView.valid() ? _sceneView->getSceneData() : 0;
185        if (!scene) return;
186
187        // remap the mouse x,y into viewport coordinates.
188       
189        float mx = _sceneView->getViewport()->x() + (int)((float)_sceneView->getViewport()->width()*(ea.getXnormalized()*0.5f+0.5f));
190        float my = _sceneView->getViewport()->y() + (int)((float)_sceneView->getViewport()->height()*(ea.getYnormalized()*0.5f+0.5f));
191
192#if 1
193
194        osgUtil::LineSegmentIntersector* picker = new osgUtil::LineSegmentIntersector(osg::Vec3d(mx,my,0.0), osg::Vec3d(mx,my,1.0) );
195        picker->setCoordinateFrame(osgUtil::Intersector::WINDOW);
196
197        osgUtil::IntersectionVisitor iv(picker);
198       
199        _sceneView->getCamera()->accept(iv);
200       
201        osg::notify(osg::NOTICE)<<"Done pick, "<<picker->containsIntersections()<<std::endl;
202       
203        if (picker->containsIntersections())
204        {
205            osgUtil::LineSegmentIntersector::Intersection intersection = picker->getFirstIntersection();
206            osg::notify(osg::NOTICE)<<"Picking "<<intersection.localIntersectionPoint<<std::endl;
207
208
209            osg::NodePath& nodePath = intersection.nodePath;
210            osg::Node* node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0;
211            osg::Group* parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*>(nodePath[nodePath.size()-2]):0;
212
213            if (node) std::cout<<"  Hits "<<node->className()<<" nodePath size"<<nodePath.size()<<std::endl;
214
215            // now we try to decorate the hit node by the osgFX::Scribe to show that its been "picked"
216            if (parent && node)
217            {
218
219                std::cout<<"  parent "<<parent->className()<<std::endl;
220
221                osgFX::Scribe* parentAsScribe = dynamic_cast<osgFX::Scribe*>(parent);
222                if (!parentAsScribe)
223                {
224                    // node not already picked, so highlight it with an osgFX::Scribe
225                    osgFX::Scribe* scribe = new osgFX::Scribe();
226                    scribe->addChild(node);
227                    parent->replaceChild(node,scribe);
228                }
229                else
230                {
231                    // node already picked so we want to remove scribe to unpick it.
232                    osg::Node::ParentList parentList = parentAsScribe->getParents();
233                    for(osg::Node::ParentList::iterator itr=parentList.begin();
234                        itr!=parentList.end();
235                        ++itr)
236                    {
237                        (*itr)->replaceChild(parentAsScribe,node);
238                    }
239                }
240            }
241
242        }
243       
244
245#else
246
247        // do the pick traversal.
248        osgUtil::PickVisitor pick(_sceneView->getViewport(),
249                                  _sceneView->getProjectionMatrix(),
250                                  _sceneView->getViewMatrix(), mx, my);
251        scene->accept(pick);
252
253        osgUtil::PickVisitor::LineSegmentHitListMap& segHitList = pick.getSegHitList();
254        if (!segHitList.empty() && !segHitList.begin()->second.empty())
255        {
256            std::cout<<"Got hits"<<std::endl;
257
258            // get the hits for the first segment
259            osgUtil::PickVisitor::HitList& hits = segHitList.begin()->second;
260
261            // just take the first hit - nearest the eye point.
262            osgUtil::Hit& hit = hits.front();
263
264            osg::NodePath& nodePath = hit._nodePath;
265            osg::Node* node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0;
266            osg::Group* parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*>(nodePath[nodePath.size()-2]):0;
267
268            if (node) std::cout<<"  Hits "<<node->className()<<" nodePath size"<<nodePath.size()<<std::endl;
269
270            // now we try to decorate the hit node by the osgFX::Scribe to show that its been "picked"
271            if (parent && node)
272            {
273
274                std::cout<<"  parent "<<parent->className()<<std::endl;
275
276                osgFX::Scribe* parentAsScribe = dynamic_cast<osgFX::Scribe*>(parent);
277                if (!parentAsScribe)
278                {
279                    // node not already picked, so highlight it with an osgFX::Scribe
280                    osgFX::Scribe* scribe = new osgFX::Scribe();
281                    scribe->addChild(node);
282                    parent->replaceChild(node,scribe);
283                }
284                else
285                {
286                    // node already picked so we want to remove scribe to unpick it.
287                    osg::Node::ParentList parentList = parentAsScribe->getParents();
288                    for(osg::Node::ParentList::iterator itr=parentList.begin();
289                        itr!=parentList.end();
290                        ++itr)
291                    {
292                        (*itr)->replaceChild(parentAsScribe,node);
293                    }
294                }
295            }
296
297        }
298#endif
299
300    }
301
302    void saveSelectedModel()
303    {
304        CreateModelToSaveVisitor cmtsv;
305        _sceneView->getSceneData()->accept(cmtsv);
306       
307        if (cmtsv._group->getNumChildren()>0)
308        {
309            std::cout<<"Writing selected compoents to 'selected_model.osg'"<<std::endl;
310            osgDB::writeNodeFile(*cmtsv._group, "selected_model.osg");
311        }
312    }
313
314protected:
315
316    osg::observer_ptr<osgUtil::SceneView> _sceneView;
317    float _mx,_my;
318};
319
320int main( int argc, char **argv )
321{
322    if (argc<2)
323    {
324        std::cout << argv[0] <<": requires filename argument." << std::endl;
325        return 1;
326    }
327
328    // load the scene.
329    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
330    if (!loadedModel)
331    {
332        std::cout << argv[0] <<": No data loaded." << std::endl;
333        return 1;
334    }
335   
336    // create the window to draw to.
337    osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
338    renderSurface->setWindowName("osgkeyboardmouse");
339    renderSurface->setWindowRectangle(100,100,800,600);
340    renderSurface->useBorder(true);
341    renderSurface->realize();
342   
343
344    // create the view of the scene.
345    osgGA::SimpleViewer viewer;
346    viewer.setSceneData(loadedModel.get());
347   
348    // set up a KeyboardMouse to manage the events comming in from the RenderSurface
349    osg::ref_ptr<Producer::KeyboardMouse>  kbm = new Producer::KeyboardMouse(renderSurface.get());
350
351    // create a KeyboardMouseCallback to handle the mouse events within this applications
352    osg::ref_ptr<MyKeyboardMouseCallback> kbmcb = new MyKeyboardMouseCallback(viewer.getEventQueue());
353
354    // create a tracball manipulator to move the camera around in response to keyboard/mouse events
355    viewer.setCameraManipulator( new osgGA::TrackballManipulator );
356
357    osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator;
358    statesetManipulator->setStateSet(viewer.getSceneView()->getGlobalStateSet());
359    viewer.addEventHandler(statesetManipulator.get());
360
361    // add the pick handler
362    viewer.addEventHandler(new PickHandler(viewer.getSceneView()));
363   
364    // set the window dimensions
365    viewer.getEventQueue()->getCurrentEventState()->setWindowRectangle(100,100,800,600);
366
367    // set the mouse input range.
368    // Producer defaults to using non-dimensional units, so we pass this onto osgGA, most windowing toolkits use pixel coords so use the window size instead.
369    viewer.getEventQueue()->getCurrentEventState()->setInputRange(-1.0, -1.0, 1.0, 1.0);
370
371    // Producer has the y axis increase upwards, like OpenGL, and contary to most Windowing toolkits.
372    // we need to construct the event queue so that it knows about this convention.
373    viewer.getEventQueue()->getCurrentEventState()->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
374
375    viewer.init();
376
377    // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
378    while( renderSurface->isRealized() && !kbmcb->done())
379    {
380        // update the window dimensions, in case the window has been resized.
381         viewer.getEventQueue()->windowResize(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight(), false);
382
383        // pass any keyboard mouse events onto the local keyboard mouse callback.
384        kbm->update( *kbmcb );
385       
386        viewer.frame();
387
388        // Swap Buffers
389        renderSurface->swapBuffers();
390    }
391
392    return 0;
393}
Note: See TracBrowser for help on using the browser.