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

Revision 5679, 10.9 kB (checked in by robert, 7 years ago)

Moved SimpleViewer? and GraphicsWindow? into their own osgViewer library, updated simpleviewer examples to reflect this change

  • 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       
187
188       osg::notify(osg::NOTICE)<<std::endl;
189
190#if 0
191        // use non dimension coordinates - in projection/clip space
192        osgUtil::LineSegmentIntersector* picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::PROJECTION, osg::Vec3d(ea.getXnormalized(),ea.getYnormalized(),-1.0), osg::Vec3d(ea.getXnormalized(),ea.getYnormalized(),1.0) );
193#else
194        // use window coordinates
195        // remap the mouse x,y into viewport coordinates.
196        osg::Viewport* viewport = viewer->getCamera()->getViewport();
197        float mx = viewport->x() + (int)((float)viewport->width()*(ea.getXnormalized()*0.5f+0.5f));
198        float my = viewport->y() + (int)((float)viewport->height()*(ea.getYnormalized()*0.5f+0.5f));
199        osgUtil::LineSegmentIntersector* picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::WINDOW, osg::Vec3d(mx,my,0.0), osg::Vec3d(mx,my,1.0) );
200
201#endif
202
203        osgUtil::IntersectionVisitor iv(picker);
204       
205        viewer->getCamera()->accept(iv);
206       
207
208        if (picker->containsIntersections())
209        {
210            osgUtil::LineSegmentIntersector::Intersection intersection = picker->getFirstIntersection();
211            osg::notify(osg::NOTICE)<<"Picked "<<intersection.localIntersectionPoint<<std::endl;
212
213#if 1
214            osg::NodePath& nodePath = intersection.nodePath;
215            osg::Node* node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0;
216            osg::Group* parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*>(nodePath[nodePath.size()-2]):0;
217
218            if (node) std::cout<<"  Hits "<<node->className()<<" nodePath size"<<nodePath.size()<<std::endl;
219
220            // now we try to decorate the hit node by the osgFX::Scribe to show that its been "picked"
221            if (parent && node)
222            {
223
224                std::cout<<"  parent "<<parent->className()<<std::endl;
225
226                osgFX::Scribe* parentAsScribe = dynamic_cast<osgFX::Scribe*>(parent);
227                if (!parentAsScribe)
228                {
229                    // node not already picked, so highlight it with an osgFX::Scribe
230                    osgFX::Scribe* scribe = new osgFX::Scribe();
231                    scribe->addChild(node);
232                    parent->replaceChild(node,scribe);
233                }
234                else
235                {
236                    // node already picked so we want to remove scribe to unpick it.
237                    osg::Node::ParentList parentList = parentAsScribe->getParents();
238                    for(osg::Node::ParentList::iterator itr=parentList.begin();
239                        itr!=parentList.end();
240                        ++itr)
241                    {
242                        (*itr)->replaceChild(parentAsScribe,node);
243                    }
244                }
245            }
246#endif
247
248        }
249       
250    }
251
252    void saveSelectedModel(osg::Node* scene)
253    {
254        if (!scene) return;
255   
256        CreateModelToSaveVisitor cmtsv;
257        scene->accept(cmtsv);
258       
259        if (cmtsv._group->getNumChildren()>0)
260        {
261            std::cout<<"Writing selected compoents to 'selected_model.osg'"<<std::endl;
262            osgDB::writeNodeFile(*cmtsv._group, "selected_model.osg");
263        }
264    }
265
266protected:
267
268    float _mx,_my;
269};
270
271int main( int argc, char **argv )
272{
273    if (argc<2)
274    {
275        std::cout << argv[0] <<": requires filename argument." << std::endl;
276        return 1;
277    }
278
279    // load the scene.
280    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
281    if (!loadedModel)
282    {
283        std::cout << argv[0] <<": No data loaded." << std::endl;
284        return 1;
285    }
286   
287    // create the window to draw to.
288    osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
289    renderSurface->setWindowName("osgkeyboardmouse");
290    renderSurface->setWindowRectangle(100,100,800,600);
291    renderSurface->useBorder(true);
292    renderSurface->realize();
293   
294
295    // create the view of the scene.
296    osgViewer::SimpleViewer viewer;
297    viewer.setSceneData(loadedModel.get());
298   
299    // set up a KeyboardMouse to manage the events comming in from the RenderSurface
300    osg::ref_ptr<Producer::KeyboardMouse>  kbm = new Producer::KeyboardMouse(renderSurface.get());
301
302    // create a KeyboardMouseCallback to handle the mouse events within this applications
303    osg::ref_ptr<MyKeyboardMouseCallback> kbmcb = new MyKeyboardMouseCallback(viewer.getEventQueue());
304
305    // create a tracball manipulator to move the camera around in response to keyboard/mouse events
306    viewer.setCameraManipulator( new osgGA::TrackballManipulator );
307
308    osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator;
309    statesetManipulator->setStateSet(viewer.getSceneView()->getGlobalStateSet());
310    viewer.addEventHandler(statesetManipulator.get());
311
312    // add the pick handler
313    viewer.addEventHandler(new PickHandler());
314   
315    // set the window dimensions
316    viewer.getEventQueue()->getCurrentEventState()->setWindowRectangle(100,100,800,600);
317
318    // set the mouse input range.
319    // 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.
320    viewer.getEventQueue()->getCurrentEventState()->setInputRange(-1.0, -1.0, 1.0, 1.0);
321
322    // Producer has the y axis increase upwards, like OpenGL, and contary to most Windowing toolkits.
323    // we need to construct the event queue so that it knows about this convention.
324    viewer.getEventQueue()->getCurrentEventState()->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
325
326    viewer.init();
327
328    // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
329    while( renderSurface->isRealized() && !kbmcb->done())
330    {
331        // update the window dimensions, in case the window has been resized.
332         viewer.getEventQueue()->windowResize(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight(), false);
333
334        // pass any keyboard mouse events onto the local keyboard mouse callback.
335        kbm->update( *kbmcb );
336       
337        viewer.frame();
338
339        // Swap Buffers
340        renderSurface->swapBuffers();
341    }
342
343    return 0;
344}
Note: See TracBrowser for help on using the browser.