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

Revision 5684, 12.4 kB (checked in by robert, 8 years ago)

Added convinience constructors to help support picking with the new osgUtil::Intersector classes.

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