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

Revision 5764, 12.5 kB (checked in by robert, 7 years ago)

Moved osgUtil::PolytopeIntersector?, osgUtil::PlaneIntersector? and osgUtil::LineSegmentIntersector? out from include/osgUtil/IntersecionVisitor into their own seperate files.

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