root/OpenSceneGraph/trunk/examples/osgstereoimage/osgstereoimage.cpp @ 5636

Revision 5636, 17.6 kB (checked in by robert, 8 years ago)

Removed deprecated GUIEventHandler method

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under 
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#include <osgProducer/Viewer>
15#include <osgDB/ReadFile>
16#include <osgDB/WriteFile>
17#include <osgUtil/Optimizer>
18
19#include <osg/Geode>
20#include <osg/Notify>
21#include <osg/MatrixTransform>
22#include <osg/Switch>
23#include <osg/TexMat>
24#include <osg/Texture2D>
25
26typedef std::vector<std::string> FileList;
27
28class SlideEventHandler : public osgGA::GUIEventHandler
29{
30public:
31
32    SlideEventHandler();
33   
34    META_Object(osgStereImageApp,SlideEventHandler);
35
36
37    void set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive);
38
39    virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
40   
41    virtual void getUsage(osg::ApplicationUsage& usage) const;
42
43    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
44   
45    void nextSlide();
46   
47    void previousSlide();
48   
49    void scaleImage(float s);
50   
51    void offsetImage(float ds,float dt);
52
53    void rotateImage(float rx,float ry);
54
55    void initTexMatrices();
56
57protected:
58
59    ~SlideEventHandler() {}
60    SlideEventHandler(const SlideEventHandler&,const osg::CopyOp&) {}
61
62    osg::ref_ptr<osg::Switch>   _switch;
63    osg::ref_ptr<osg::TexMat>   _texmatLeft;
64    osg::ref_ptr<osg::TexMat>   _texmatRight;
65    bool                        _firstTraversal;
66    unsigned int                _activeSlide;
67    double                      _previousTime;
68    double                      _timePerSlide;
69    bool                        _autoSteppingActive;
70    float                       _initSeperationX;
71    float                       _currentSeperationX;
72    float                       _initSeperationY;
73    float                       _currentSeperationY;
74       
75};
76
77SlideEventHandler::SlideEventHandler():
78    _switch(0),
79    _texmatLeft(0),
80    _texmatRight(0),
81    _firstTraversal(true),
82    _activeSlide(0),
83    _previousTime(-1.0f),
84    _timePerSlide(5.0),
85    _autoSteppingActive(false)
86{
87}
88
89void SlideEventHandler::set(osg::Switch* sw, float offsetX, float offsetY, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float timePerSlide, bool autoSteppingActive)
90{
91    _switch = sw;
92    _switch->setUpdateCallback(this);
93
94    _texmatLeft = texmatLeft;
95    _texmatRight = texmatRight;
96
97    _timePerSlide = timePerSlide;
98    _autoSteppingActive = autoSteppingActive;   
99   
100    _initSeperationX = offsetX;
101    _currentSeperationX = _initSeperationX;
102
103    _initSeperationY = offsetY;
104    _currentSeperationY = _initSeperationY;
105
106    initTexMatrices();
107
108}
109
110bool SlideEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
111{
112    switch(ea.getEventType())
113    {
114        case(osgGA::GUIEventAdapter::KEYDOWN):
115        {
116            if (ea.getKey()=='a')
117            {
118                _autoSteppingActive = !_autoSteppingActive;
119                _previousTime = ea.getTime();
120                return true;
121            }
122            else if (ea.getKey()=='n')
123            {
124                nextSlide();
125                return true;
126            }
127            else if (ea.getKey()=='p')
128            {
129                previousSlide();
130                return true;
131            }
132            else if (ea.getKey()=='w')
133            {
134                scaleImage(0.99f);
135                return true;
136            }
137            else if (ea.getKey()=='s')
138            {
139                scaleImage(1.01f);
140                return true;
141            }
142            else if (ea.getKey()=='j')
143            {
144                offsetImage(-0.001f,0.0f);
145                return true;
146            }
147            else if (ea.getKey()=='k')
148            {
149                offsetImage(0.001f,0.0f);
150                return true;
151            }
152            else if (ea.getKey()=='i')
153            {
154                offsetImage(0.0f,-0.001f);
155                return true;
156            }
157            else if (ea.getKey()=='m')
158            {
159                offsetImage(0.0f,0.001f);
160                return true;
161            }
162            else if (ea.getKey()==' ')
163            {
164                initTexMatrices();
165                return true;
166            }
167            return false;
168        }
169        case(osgGA::GUIEventAdapter::DRAG):
170        case(osgGA::GUIEventAdapter::MOVE):
171        {
172            static float px = ea.getXnormalized();
173            static float py = ea.getYnormalized();
174           
175            float dx = ea.getXnormalized()-px;
176            float dy = ea.getYnormalized()-py;
177           
178            px = ea.getXnormalized();
179            py = ea.getYnormalized();
180           
181            rotateImage(dx,dy);
182           
183            return true;
184        }
185
186        default:
187            return false;
188    }
189}
190
191void SlideEventHandler::getUsage(osg::ApplicationUsage& usage) const
192{
193    usage.addKeyboardMouseBinding("Space","Reset the image position to center");
194    usage.addKeyboardMouseBinding("a","Toggle on/off the automatic advancement for image to image");
195    usage.addKeyboardMouseBinding("n","Advance to next image");
196    usage.addKeyboardMouseBinding("p","Move to previous image");
197    usage.addKeyboardMouseBinding("q","Zoom into the image");
198    usage.addKeyboardMouseBinding("a","Zoom out of the image");
199    usage.addKeyboardMouseBinding("j","Reduce horizontal offset");
200    usage.addKeyboardMouseBinding("k","Increase horizontal offset");
201    usage.addKeyboardMouseBinding("m","Reduce vertical offset");
202    usage.addKeyboardMouseBinding("i","Increase vertical offset");
203}
204
205void SlideEventHandler::operator()(osg::Node* node, osg::NodeVisitor* nv)
206{
207    if (_autoSteppingActive && nv->getFrameStamp())
208    {
209        double time = nv->getFrameStamp()->getReferenceTime();
210       
211        if (_firstTraversal)
212        {
213            _firstTraversal = false;
214            _previousTime = time;
215        }
216        else if (time-_previousTime>_timePerSlide)
217        {
218            _previousTime = time;
219           
220            nextSlide();
221        }
222       
223    }
224
225    traverse(node,nv);
226}
227
228void SlideEventHandler::nextSlide()
229{
230    if (_switch->getNumChildren()==0) return;
231
232    ++_activeSlide;
233    if (_activeSlide>=_switch->getNumChildren()) _activeSlide = 0;
234
235    _switch->setSingleChildOn(_activeSlide);
236}
237
238void SlideEventHandler::previousSlide()
239{
240    if (_switch->getNumChildren()==0) return;
241
242    if (_activeSlide==0) _activeSlide = _switch->getNumChildren()-1;
243    else --_activeSlide;
244
245    _switch->setSingleChildOn(_activeSlide);
246}
247
248void SlideEventHandler::scaleImage(float s)
249{
250    _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f));
251    _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f));
252}
253
254void SlideEventHandler::offsetImage(float ds,float dt)
255{
256    _currentSeperationX+=ds;
257    _currentSeperationY+=dt;
258    osg::notify(osg::NOTICE)<<"image offset x = "<<_currentSeperationX<<"  y ="<<_currentSeperationY<<std::endl;
259    _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(ds,dt,0.0f));
260    _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-ds,-dt,0.0f));
261}
262
263void SlideEventHandler::rotateImage(float rx,float ry)
264{
265    const float scale = 0.5f;
266    _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f));
267    _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f));
268}
269
270void SlideEventHandler::initTexMatrices()
271{
272    _texmatLeft->setMatrix(osg::Matrix::translate(_initSeperationX,_initSeperationY,0.0f));
273    _texmatRight->setMatrix(osg::Matrix::translate(-_initSeperationX,-_initSeperationY,0.0f));
274}
275
276
277osg::Geode* createSectorForImage(osg::Image* image, osg::TexMat* texmat, float s,float t, float radius, float height, float length)
278{
279
280    int numSegments = 20;
281    float Theta = length/radius;
282    float dTheta = Theta/(float)(numSegments-1);
283   
284    float ThetaZero = height*s/(t*radius);
285   
286    // set up the texture.
287    osg::Texture2D* texture = new osg::Texture2D;
288    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
289    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
290    texture->setImage(image);
291
292    // set up the drawstate.
293    osg::StateSet* dstate = new osg::StateSet;
294    dstate->setMode(GL_CULL_FACE,osg::StateAttribute::OFF);
295    dstate->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
296    dstate->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
297    dstate->setTextureAttribute(0, texmat);
298
299    // set up the geoset.
300    osg::Geometry* geom = new osg::Geometry;
301    geom->setStateSet(dstate);
302
303    osg::Vec3Array* coords = new osg::Vec3Array();
304    osg::Vec2Array* tcoords = new osg::Vec2Array();
305   
306    int i;
307    float angle = -Theta/2.0f;
308    for(i=0;
309        i<numSegments;
310        ++i, angle+=dTheta)
311    {
312        coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,height*0.5f)); // top
313        coords->push_back(osg::Vec3(sinf(angle)*radius,cosf(angle)*radius,-height*0.5f)); // bottom.
314       
315        tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,1.0f)); // top
316        tcoords->push_back(osg::Vec2(angle/ThetaZero+0.5f,0.0f)); // bottom.
317
318    }
319
320    osg::Vec4Array* colors = new osg::Vec4Array();
321    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
322
323    osg::DrawArrays* elements = new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,coords->size());
324
325   
326
327    geom->setVertexArray(coords);
328    geom->setTexCoordArray(0,tcoords);
329    geom->setColorArray(colors);
330    geom->setColorBinding(osg::Geometry::BIND_OVERALL);
331
332    geom->addPrimitiveSet(elements);
333
334    // set up the geode.
335    osg::Geode* geode = new osg::Geode;
336    geode->addDrawable(geom);
337
338    return geode;
339
340}
341
342// create a switch containing a set of child each containing a
343// stereo image pair.
344osg::Switch* createScene(const FileList& fileList, osg::TexMat* texmatLeft, osg::TexMat* texmatRight, float radius, float height, float length)
345{
346    osg::Switch* sw = new osg::Switch;
347
348    // load the images.
349    for(unsigned int i=0;i+1<fileList.size();i+=2)
350    {
351        osg::ref_ptr<osg::Image> imageLeft = osgDB::readImageFile(fileList[i]);
352        osg::ref_ptr<osg::Image> imageRight = osgDB::readImageFile(fileList[i+1]);
353        if (imageLeft.valid() && imageRight.valid())
354        {
355            float average_s = (imageLeft->s()+imageRight->s())*0.5f;
356            float average_t = (imageLeft->t()+imageRight->t())*0.5f;
357
358            osg::Geode* geodeLeft = createSectorForImage(imageLeft.get(),texmatLeft,average_s,average_t, radius, height, length);
359            geodeLeft->setNodeMask(0x01);
360
361            osg::Geode* geodeRight = createSectorForImage(imageRight.get(),texmatRight,average_s,average_t, radius, height, length);
362            geodeRight->setNodeMask(0x02);
363
364            osg::ref_ptr<osg::Group> imageGroup = new osg::Group;
365           
366            imageGroup->addChild(geodeLeft);
367            imageGroup->addChild(geodeRight);
368           
369            sw->addChild(imageGroup.get());
370        }
371        else
372        {
373            std::cout << "Warning: Unable to load both image files, '"<<fileList[i]<<"' & '"<<fileList[i+1]<<"', required for stereo imaging."<<std::endl;
374        }
375    }
376
377
378    if (sw->getNumChildren()>0)
379    {
380        // select first child.
381        sw->setSingleChildOn(0);
382    }
383
384    return sw;
385}
386
387int main( int argc, char **argv )
388{
389
390    // use an ArgumentParser object to manage the program arguments.
391    osg::ArgumentParser arguments(&argc,argv);
392   
393    // set up the usage document, in case we need to print out how to use this program.
394    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use node masks to create stereo images.");
395    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
396    arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time delay in sceonds between the display of successive image pairs when in auto advance mode.");
397    arguments.getApplicationUsage()->addCommandLineOption("-a","Enter auto advance of image pairs on start up.");
398    arguments.getApplicationUsage()->addCommandLineOption("-x <float>","Horizontal offset of left and right images.");
399    arguments.getApplicationUsage()->addCommandLineOption("-y <float>","Vertical offset of left and right images.");
400    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
401   
402
403    // construct the viewer.
404    osgProducer::Viewer viewer(arguments);
405
406    // set up the value with sensible default event handlers.
407    viewer.setUpViewer(osgProducer::Viewer::ESCAPE_SETS_DONE);
408
409    // register the handler to add keyboard and mosue handling.
410    SlideEventHandler* seh = new SlideEventHandler();
411    viewer.getEventHandlerList().push_front(seh);
412
413
414    // get details on keyboard and mouse bindings used by the viewer.
415    viewer.getUsage(*arguments.getApplicationUsage());
416
417    // read any time delay argument.
418    float timeDelayBetweenSlides = 5.0f;
419    while (arguments.read("-d",timeDelayBetweenSlides)) {}
420
421    bool autoSteppingActive = false;
422    while (arguments.read("-a")) autoSteppingActive = true;
423
424    float offsetX=0.0f;
425    while (arguments.read("-x",offsetX)) {}
426
427    float offsetY=0.0f;
428    while (arguments.read("-y",offsetY)) {}
429
430    // if user request help write it out to cout.
431    if (arguments.read("-h") || arguments.read("--help"))
432    {
433        arguments.getApplicationUsage()->write(std::cout);
434        return 1;
435    }
436
437    // any option left unread are converted into errors to write out later.
438    arguments.reportRemainingOptionsAsUnrecognized();
439
440    // report any errors if they have occured when parsing the program aguments.
441    if (arguments.errors())
442    {
443        arguments.writeErrorMessages(std::cout);
444        return 1;
445    }
446   
447    if (arguments.argc()<=1)
448    {
449        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
450        return 1;
451    }
452
453    // extract the filenames from the arguments list.
454    FileList fileList;
455    for(int pos=1;pos<arguments.argc();++pos)
456    {
457        if (arguments.isString(pos)) fileList.push_back(arguments[pos]);
458    }
459
460    if (fileList.size()<2)
461    {
462        return 1;
463    }
464
465    // set up the use of stereo by default.
466    osg::DisplaySettings* ds = viewer.getDisplaySettings();
467    if (!ds) ds = osg::DisplaySettings::instance();
468    if (ds) ds->setStereo(true);
469
470    // create the windows and run the threads.
471    viewer.realize();
472
473    // now the windows have been realized we switch off the cursor to prevent it
474    // distracting the people seeing the stereo images.
475    float fovy = 1.0f;
476    for( unsigned int i = 0; i < viewer.getNumberOfCameras(); i++ )
477    {
478        Producer::Camera* cam = viewer.getCamera(i);
479        Producer::RenderSurface* rs = cam->getRenderSurface();
480        rs->useCursor(false);
481        fovy = osg::DegreesToRadians(cam->getLensVerticalFov());
482    }
483
484    float radius = 1.0f;
485    float height = 2*radius*tan(fovy*0.5f);
486    float length = osg::PI*radius;  // half a cylinder.
487
488    // use a texure matrix to control the placement of the image.
489    osg::TexMat* texmatLeft = new osg::TexMat;
490    osg::TexMat* texmatRight = new osg::TexMat;
491
492    // creat the scene from the file list.
493    osg::ref_ptr<osg::Switch> rootNode = createScene(fileList,texmatLeft,texmatRight,radius,height,length);
494
495
496    //osgDB::writeNodeFile(*rootNode,"test.osg");
497
498    // set the scene to render
499    viewer.setSceneData(rootNode.get());
500
501
502    viewer.getCullSettings().setCullMask(0xffffffff);
503    viewer.getCullSettings().setCullMaskLeft(0x00000001);
504    viewer.getCullSettings().setCullMaskRight(0x00000002);
505
506    // set all the sceneview's up so that their left and right add cull masks are set up.
507    for(osgProducer::OsgCameraGroup::SceneHandlerList::iterator itr=viewer.getSceneHandlerList().begin();
508        itr!=viewer.getSceneHandlerList().end();
509        ++itr)
510    {
511        osgUtil::SceneView* sceneview = (*itr)->getSceneView();
512        sceneview->setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius);
513    }
514
515
516    // set up the SlideEventHandler.
517    seh->set(rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,timeDelayBetweenSlides,autoSteppingActive);
518   
519   
520    osg::Matrix homePosition;
521    homePosition.makeLookAt(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(0.0f,1.0f,0.0f),osg::Vec3(0.0f,0.0f,1.0f));
522       
523    while( !viewer.done() )
524    {
525        // wait for all cull and draw threads to complete.
526        viewer.sync();
527
528        // update the scene by traversing it with the the update visitor which will
529        // call all node update callbacks and animations.
530        viewer.update();
531         
532        viewer.setView(homePosition);
533
534        // fire off the cull and draw traversals of the scene.
535        viewer.frame();
536       
537    }
538   
539    // wait for all cull and draw threads to complete.
540    viewer.sync();
541
542    // run a clean up frame to delete all OpenGL objects.
543    viewer.cleanup_frame();
544
545    // wait for all the clean up frame to complete.
546    viewer.sync();
547   
548    return 0;
549}
Note: See TracBrowser for help on using the browser.