root/OpenSceneGraph/trunk/src/osgViewer/View.cpp @ 12504

Revision 12504, 81.3 kB (checked in by robert, 4 years ago)

Introduced a less conservative near ratio.

  • 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 <osgViewer/Renderer>
15#include <osgViewer/View>
16#include <osgViewer/GraphicsWindow>
17
18#include <osg/io_utils>
19
20#include <osg/TextureCubeMap>
21#include <osg/TextureRectangle>
22#include <osg/Texture1D>
23#include <osg/TexMat>
24
25#include <osgUtil/Optimizer>
26#include <osgUtil/ShaderGen>
27#include <osgUtil/IntersectionVisitor>
28
29#include <iterator>
30
31using namespace osgViewer;
32
33class CollectedCoordinateSystemNodesVisitor : public osg::NodeVisitor
34{
35public:
36
37    CollectedCoordinateSystemNodesVisitor():
38        NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN) {}
39
40    META_NodeVisitor("osgViewer","CollectedCoordinateSystemNodesVisitor")
41
42    virtual void apply(osg::Node& node)
43    {
44        traverse(node);
45    }
46
47    virtual void apply(osg::CoordinateSystemNode& node)
48    {
49        if (_pathToCoordinateSystemNode.empty())
50        {
51            OSG_DEBUG<<"Found CoordinateSystemNode node"<<std::endl;
52            OSG_DEBUG<<"     CoordinateSystem = "<<node.getCoordinateSystem()<<std::endl;
53            _pathToCoordinateSystemNode = getNodePath();
54        }
55        else
56        {
57            OSG_DEBUG<<"Found additional CoordinateSystemNode node, but ignoring"<<std::endl;
58            OSG_DEBUG<<"     CoordinateSystem = "<<node.getCoordinateSystem()<<std::endl;
59        }
60        traverse(node);
61    }
62
63    osg::NodePath _pathToCoordinateSystemNode;
64};
65
66
67/** callback class to use to allow matrix manipulators to query the application for the local coordinate frame.*/
68class ViewerCoordinateFrameCallback : public osgGA::CameraManipulator::CoordinateFrameCallback
69{
70public:
71
72    ViewerCoordinateFrameCallback(osgViewer::View* view):
73        _view(view) {}
74
75    virtual osg::CoordinateFrame getCoordinateFrame(const osg::Vec3d& position) const
76    {
77        OSG_DEBUG<<"getCoordinateFrame("<<position<<")"<<std::endl;
78
79        osg::NodePath tmpPath = _view->getCoordinateSystemNodePath();
80
81        if (!tmpPath.empty())
82        {
83            osg::Matrixd coordinateFrame;
84
85            osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(tmpPath.back());
86            if (csn)
87            {
88                osg::Vec3 local_position = position*osg::computeWorldToLocal(tmpPath);
89
90                // get the coordinate frame in world coords.
91                coordinateFrame = csn->computeLocalCoordinateFrame(local_position)* osg::computeLocalToWorld(tmpPath);
92
93                // keep the position of the coordinate frame to reapply after rescale.
94                osg::Vec3d pos = coordinateFrame.getTrans();
95
96                // compensate for any scaling, so that the coordinate frame is a unit size
97                osg::Vec3d x(1.0,0.0,0.0);
98                osg::Vec3d y(0.0,1.0,0.0);
99                osg::Vec3d z(0.0,0.0,1.0);
100                x = osg::Matrixd::transform3x3(x,coordinateFrame);
101                y = osg::Matrixd::transform3x3(y,coordinateFrame);
102                z = osg::Matrixd::transform3x3(z,coordinateFrame);
103                coordinateFrame.preMultScale(osg::Vec3d(1.0/x.length(),1.0/y.length(),1.0/z.length()));
104
105                // reapply the position.
106                coordinateFrame.setTrans(pos);
107
108                OSG_DEBUG<<"csn->computeLocalCoordinateFrame(position)* osg::computeLocalToWorld(tmpPath)"<<coordinateFrame<<std::endl;
109
110            }
111            else
112            {
113                OSG_DEBUG<<"osg::computeLocalToWorld(tmpPath)"<<std::endl;
114                coordinateFrame =  osg::computeLocalToWorld(tmpPath);
115            }
116            return coordinateFrame;
117        }
118        else
119        {
120            OSG_DEBUG<<"   no coordinate system found, using default orientation"<<std::endl;
121            return osg::Matrixd::translate(position);
122        }
123    }
124
125protected:
126    virtual ~ViewerCoordinateFrameCallback() {}
127
128    osg::observer_ptr<osgViewer::View> _view;
129};
130
131
132View::View():
133    _fusionDistanceMode(osgUtil::SceneView::PROPORTIONAL_TO_SCREEN_DISTANCE),
134    _fusionDistanceValue(1.0f)
135{
136    // OSG_NOTICE<<"Constructing osgViewer::View"<<std::endl;
137
138    _startTick = 0;
139
140    _frameStamp = new osg::FrameStamp;
141    _frameStamp->setFrameNumber(0);
142    _frameStamp->setReferenceTime(0);
143    _frameStamp->setSimulationTime(0);
144
145    _scene = new Scene;
146
147    // make sure View is safe to reference multi-threaded.
148    setThreadSafeRefUnref(true);
149
150    // need to attach a Renderer to the master camera which has been default constructed
151    getCamera()->setRenderer(createRenderer(getCamera()));
152
153    setEventQueue(new osgGA::EventQueue);
154
155    setStats(new osg::Stats("View"));
156}
157
158
159View::View(const osgViewer::View& view, const osg::CopyOp& copyop):
160    osg::View(view,copyop),
161    osgGA::GUIActionAdapter(),
162    _startTick(0),
163    _fusionDistanceMode(view._fusionDistanceMode),
164    _fusionDistanceValue(view._fusionDistanceValue)
165{
166    _scene = new Scene;
167
168    // need to attach a Renderer to the master camera which has been default constructed
169    getCamera()->setRenderer(createRenderer(getCamera()));
170
171    setEventQueue(new osgGA::EventQueue);
172
173    setStats(new osg::Stats("View"));
174}
175
176View::~View()
177{
178    OSG_INFO<<"Destructing osgViewer::View"<<std::endl;
179}
180
181void View::take(osg::View& rhs)
182{
183    osg::View::take(rhs);
184
185#if 1
186    osgViewer::View* rhs_osgViewer = dynamic_cast<osgViewer::View*>(&rhs);
187    if (rhs_osgViewer)
188    {
189
190        // copy across rhs
191        _startTick = rhs_osgViewer->_startTick;
192        _frameStamp = rhs_osgViewer->_frameStamp;
193
194        if (rhs_osgViewer->getSceneData())
195        {
196            _scene = rhs_osgViewer->_scene;
197        }
198
199        if (rhs_osgViewer->_cameraManipulator.valid())
200        {
201            _cameraManipulator = rhs_osgViewer->_cameraManipulator;
202        }
203
204        _eventHandlers.insert(_eventHandlers.end(), rhs_osgViewer->_eventHandlers.begin(), rhs_osgViewer->_eventHandlers.end());
205
206        _coordinateSystemNodePath = rhs_osgViewer->_coordinateSystemNodePath;
207
208        _displaySettings = rhs_osgViewer->_displaySettings;
209        _fusionDistanceMode = rhs_osgViewer->_fusionDistanceMode;
210        _fusionDistanceValue = rhs_osgViewer->_fusionDistanceValue;
211
212
213        // clear rhs
214        rhs_osgViewer->_frameStamp = 0;
215        rhs_osgViewer->_scene = 0;
216        rhs_osgViewer->_cameraManipulator = 0;
217        rhs_osgViewer->_eventHandlers.clear();
218
219        rhs_osgViewer->_coordinateSystemNodePath.clearNodePath();
220
221        rhs_osgViewer->_displaySettings = 0;
222    }
223#endif
224    computeActiveCoordinateSystemNodePath();
225    assignSceneDataToCameras();
226}
227
228osg::GraphicsOperation* View::createRenderer(osg::Camera* camera)
229{
230    Renderer* render = new Renderer(camera);
231    camera->setStats(new osg::Stats("Camera"));
232    return render;
233}
234
235
236void View::init()
237{
238    OSG_INFO<<"View::init()"<<std::endl;
239
240    osg::ref_ptr<osgGA::GUIEventAdapter> initEvent = _eventQueue->createEvent();
241    initEvent->setEventType(osgGA::GUIEventAdapter::FRAME);
242
243    if (_cameraManipulator.valid())
244    {
245        _cameraManipulator->init(*initEvent, *this);
246    }
247}
248
249void View::setStartTick(osg::Timer_t tick)
250{
251    _startTick = tick;
252}
253
254void View::setSceneData(osg::Node* node)
255{
256    if (node==_scene->getSceneData()) return;
257
258    osg::ref_ptr<Scene> scene = Scene::getScene(node);
259
260    if (scene)
261    {
262        OSG_INFO<<"View::setSceneData() Sharing scene "<<scene.get()<<std::endl;
263        _scene = scene;
264    }
265    else
266    {
267        if (_scene->referenceCount()!=1)
268        {
269            // we are not the only reference to the Scene so we cannot reuse it.
270            _scene = new Scene;
271            OSG_INFO<<"View::setSceneData() Allocating new scene"<<_scene.get()<<std::endl;
272        }
273        else
274        {
275            OSG_INFO<<"View::setSceneData() Reusing exisitng scene"<<_scene.get()<<std::endl;
276        }
277
278        _scene->setSceneData(node);
279    }
280
281    if (getSceneData())
282    {
283        #if defined(OSG_GLES2_AVAILABLE)
284            osgUtil::ShaderGenVisitor sgv;
285            getSceneData()->getOrCreateStateSet();
286            getSceneData()->accept(sgv);
287        #endif
288       
289        // now make sure the scene graph is set up with the correct DataVariance to protect the dynamic elements of
290        // the scene graph from being run in parallel.
291        osgUtil::Optimizer::StaticObjectDetectionVisitor sodv;
292        getSceneData()->accept(sodv);
293
294        // make sure that existing scene graph objects are allocated with thread safe ref/unref
295        if (getViewerBase() &&
296            getViewerBase()->getThreadingModel()!=ViewerBase::SingleThreaded)
297        {
298            getSceneData()->setThreadSafeRefUnref(true);
299        }
300
301        // update the scene graph so that it has enough GL object buffer memory for the graphics contexts that will be using it.
302        getSceneData()->resizeGLObjectBuffers(osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts());
303    }
304
305    computeActiveCoordinateSystemNodePath();
306
307    assignSceneDataToCameras();
308}
309
310void View::setDatabasePager(osgDB::DatabasePager* dp)
311{
312    _scene->setDatabasePager(dp);
313}
314
315osgDB::DatabasePager* View::getDatabasePager()
316{
317    return _scene->getDatabasePager();
318}
319
320const osgDB::DatabasePager* View::getDatabasePager() const
321{
322    return _scene->getDatabasePager();
323}
324
325
326void View::setImagePager(osgDB::ImagePager* dp)
327{
328    _scene->setImagePager(dp);
329}
330
331osgDB::ImagePager* View::getImagePager()
332{
333    return _scene->getImagePager();
334}
335
336const osgDB::ImagePager* View::getImagePager() const
337{
338    return _scene->getImagePager();
339}
340
341
342void View::setCameraManipulator(osgGA::CameraManipulator* manipulator, bool resetPosition)
343{
344    _cameraManipulator = manipulator;
345
346    if (_cameraManipulator.valid())
347    {
348        _cameraManipulator->setCoordinateFrameCallback(new ViewerCoordinateFrameCallback(this));
349
350        if (getSceneData()) _cameraManipulator->setNode(getSceneData());
351
352        if (resetPosition)
353        {
354            osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
355            _cameraManipulator->home(*dummyEvent, *this);
356        }
357    }
358}
359
360void View::home()
361{
362    if (_cameraManipulator.valid())
363    {
364        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
365        _cameraManipulator->home(*dummyEvent, *this);
366    }
367}
368
369
370void View::addEventHandler(osgGA::GUIEventHandler* eventHandler)
371{
372    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
373    if (itr == _eventHandlers.end())
374    {
375        _eventHandlers.push_back(eventHandler);
376    }
377}
378
379void View::removeEventHandler(osgGA::GUIEventHandler* eventHandler)
380{
381    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
382    if (itr != _eventHandlers.end())
383    {
384        _eventHandlers.erase(itr);
385    }
386}
387
388void View::setCoordinateSystemNodePath(const osg::NodePath& nodePath)
389{
390    _coordinateSystemNodePath.setNodePath(nodePath);
391}
392
393osg::NodePath View::getCoordinateSystemNodePath() const
394{
395    osg::NodePath nodePath;
396    _coordinateSystemNodePath.getNodePath(nodePath);
397    return nodePath;
398}
399
400void View::computeActiveCoordinateSystemNodePath()
401{
402    // now search for CoordinateSystemNode's for which we want to track.
403    osg::Node* subgraph = getSceneData();
404
405    if (subgraph)
406    {
407
408        CollectedCoordinateSystemNodesVisitor ccsnv;
409        subgraph->accept(ccsnv);
410
411        if (!ccsnv._pathToCoordinateSystemNode.empty())
412        {
413           setCoordinateSystemNodePath(ccsnv._pathToCoordinateSystemNode);
414           return;
415        }
416    }
417
418    // otherwise no node path found so reset to empty.
419    setCoordinateSystemNodePath(osg::NodePath());
420}
421
422void View::setUpViewAcrossAllScreens()
423{
424    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
425    if (!wsi)
426    {
427        OSG_NOTICE<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
428        return;
429    }
430
431    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
432
433    double fovy, aspectRatio, zNear, zFar;
434    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
435
436    osg::GraphicsContext::ScreenIdentifier si;
437    si.readDISPLAY();
438
439    // displayNum has not been set so reset it to 0.
440    if (si.displayNum<0) si.displayNum = 0;
441
442    unsigned int numScreens = wsi->getNumScreens(si);
443    if (numScreens==1)
444    {
445        if (si.screenNum<0) si.screenNum = 0;
446
447        unsigned int width, height;
448        wsi->getScreenResolution(si, width, height);
449
450        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
451        traits->hostName = si.hostName;
452        traits->displayNum = si.displayNum;
453        traits->screenNum = si.screenNum;
454        traits->x = 0;
455        traits->y = 0;
456        traits->width = width;
457        traits->height = height;
458        traits->windowDecoration = false;
459        traits->doubleBuffer = true;
460        traits->sharedContext = 0;
461       
462        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
463
464        _camera->setGraphicsContext(gc.get());
465
466        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
467        if (gw)
468        {
469            OSG_INFO<<"  GraphicsWindow has been created successfully."<<std::endl;
470            gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
471        }
472        else
473        {
474            OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
475        }
476
477        double newAspectRatio = double(traits->width) / double(traits->height);
478        double aspectRatioChange = newAspectRatio / aspectRatio;
479        if (aspectRatioChange != 1.0)
480        {
481            _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
482        }
483
484        _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
485
486        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
487
488        _camera->setDrawBuffer(buffer);
489        _camera->setReadBuffer(buffer);
490
491    }
492    else
493    {
494
495        double translate_x = 0.0;
496
497        for(unsigned int i=0; i<numScreens; ++i)
498        {
499            si.screenNum = i;
500
501            unsigned int width, height;
502            wsi->getScreenResolution(si, width, height);
503            translate_x += double(width) / (double(height) * aspectRatio);
504        }
505
506        bool stereoSlitScreens = numScreens==2 &&
507                                 ds->getStereoMode()==osg::DisplaySettings::HORIZONTAL_SPLIT &&
508                                 ds->getStereo();
509
510        for(unsigned int i=0; i<numScreens; ++i)
511        {
512            si.screenNum = i;
513
514            unsigned int width, height;
515            wsi->getScreenResolution(si, width, height);
516
517            osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
518            traits->hostName = si.hostName;
519            traits->displayNum = si.displayNum;
520            traits->screenNum = si.screenNum;
521            traits->screenNum = i;
522            traits->x = 0;
523            traits->y = 0;
524            traits->width = width;
525            traits->height = height;
526            traits->windowDecoration = false;
527            traits->doubleBuffer = true;
528            traits->sharedContext = 0;
529
530            osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
531
532            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
533            camera->setGraphicsContext(gc.get());
534
535            osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
536            if (gw)
537            {
538                OSG_INFO<<"  GraphicsWindow has been created successfully."<<gw<<std::endl;
539
540                gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(traits->x, traits->y, traits->width, traits->height );
541            }
542            else
543            {
544                OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
545            }
546
547            camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
548
549            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
550            camera->setDrawBuffer(buffer);
551            camera->setReadBuffer(buffer);
552
553            if (stereoSlitScreens)
554            {
555                unsigned int leftCameraNum = (ds->getSplitStereoHorizontalEyeMapping()==osg::DisplaySettings::LEFT_EYE_LEFT_VIEWPORT) ? 0 : 1;
556
557                osg::ref_ptr<osg::DisplaySettings> ds_local = new osg::DisplaySettings(*ds);
558                ds_local->setStereoMode(leftCameraNum==i ? osg::DisplaySettings::LEFT_EYE : osg::DisplaySettings::RIGHT_EYE);
559                camera->setDisplaySettings(ds_local.get());
560
561                addSlave(camera.get(), osg::Matrixd(), osg::Matrixd() );
562            }
563            else
564            {
565                double newAspectRatio = double(traits->width) / double(traits->height);
566                double aspectRatioChange = newAspectRatio / aspectRatio;
567
568                addSlave(camera.get(), osg::Matrixd::translate( translate_x - aspectRatioChange, 0.0, 0.0) * osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0), osg::Matrixd() );
569                translate_x -= aspectRatioChange * 2.0;
570            }
571        }
572    }
573
574    assignSceneDataToCameras();
575}
576
577void View::setUpViewInWindow(int x, int y, int width, int height, unsigned int screenNum)
578{
579    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
580
581    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
582
583    traits->readDISPLAY();
584    if (traits->displayNum<0) traits->displayNum = 0;
585
586    traits->screenNum = screenNum;
587    traits->x = x;
588    traits->y = y;
589    traits->width = width;
590    traits->height = height;
591    traits->windowDecoration = true;
592    traits->doubleBuffer = true;
593    traits->sharedContext = 0;
594
595    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
596
597    _camera->setGraphicsContext(gc.get());
598
599    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
600    if (gw)
601    {
602        OSG_INFO<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
603        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(x, y, width, height );
604    }
605    else
606    {
607        OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
608    }
609
610    double fovy, aspectRatio, zNear, zFar;
611    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
612
613    double newAspectRatio = double(traits->width) / double(traits->height);
614    double aspectRatioChange = newAspectRatio / aspectRatio;
615    if (aspectRatioChange != 1.0)
616    {
617        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
618    }
619
620    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
621
622    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
623
624    _camera->setDrawBuffer(buffer);
625    _camera->setReadBuffer(buffer);
626}
627
628void View::setUpViewOnSingleScreen(unsigned int screenNum)
629{
630    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
631    if (!wsi)
632    {
633        OSG_NOTICE<<"View::setUpViewOnSingleScreen() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
634        return;
635    }
636
637    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
638
639    osg::GraphicsContext::ScreenIdentifier si;
640    si.readDISPLAY();
641
642    // displayNum has not been set so reset it to 0.
643    if (si.displayNum<0) si.displayNum = 0;
644
645    si.screenNum = screenNum;
646
647    unsigned int width, height;
648    wsi->getScreenResolution(si, width, height);
649
650    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
651    traits->hostName = si.hostName;
652    traits->displayNum = si.displayNum;
653    traits->screenNum = si.screenNum;
654    traits->x = 0;
655    traits->y = 0;
656    traits->width = width;
657    traits->height = height;
658    traits->windowDecoration = false;
659    traits->doubleBuffer = true;
660    traits->sharedContext = 0;
661
662    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
663
664    _camera->setGraphicsContext(gc.get());
665
666    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
667    if (gw)
668    {
669        OSG_INFO<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
670        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
671    }
672    else
673    {
674        OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
675    }
676
677    double fovy, aspectRatio, zNear, zFar;
678    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
679
680    double newAspectRatio = double(traits->width) / double(traits->height);
681    double aspectRatioChange = newAspectRatio / aspectRatio;
682    if (aspectRatioChange != 1.0)
683    {
684        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
685    }
686
687    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
688
689    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
690
691    _camera->setDrawBuffer(buffer);
692    _camera->setReadBuffer(buffer);
693}
694
695static osg::Geometry* create3DSphericalDisplayDistortionMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, double sphere_radius, double collar_radius,osg::Image* intensityMap, const osg::Matrix& projectorMatrix)
696{
697    osg::Vec3d center(0.0,0.0,0.0);
698    osg::Vec3d eye(0.0,0.0,0.0);
699
700    double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
701
702    bool centerProjection = false;
703
704    osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
705
706    OSG_INFO<<"create3DSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
707    OSG_INFO<<"create3DSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
708
709
710    // create the quad to visualize.
711    osg::Geometry* geometry = new osg::Geometry();
712
713    geometry->setSupportsDisplayList(false);
714
715    osg::Vec3 xAxis(widthVector);
716    float width = widthVector.length();
717    xAxis /= width;
718
719    osg::Vec3 yAxis(heightVector);
720    float height = heightVector.length();
721    yAxis /= height;
722
723    int noSteps = 50;
724
725    osg::Vec3Array* vertices = new osg::Vec3Array;
726    osg::Vec3Array* texcoords0 = new osg::Vec3Array;
727    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
728    osg::Vec4Array* colors = new osg::Vec4Array;
729
730    osg::Vec3 bottom = origin;
731    osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
732    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
733
734    osg::Vec3d screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
735    float screenRadius = heightVector.length() * 0.5f;
736
737    osg::Vec3 cursor = bottom;
738    int i,j;
739
740    if (centerProjection)
741    {
742        for(i=0;i<noSteps;++i)
743        {
744            osg::Vec3 cursor = bottom+dy*(float)i;
745            for(j=0;j<noSteps;++j)
746            {
747                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
748                double theta = atan2(-delta.y(), delta.x());
749                double phi = osg::PI_2 * delta.length() / screenRadius;
750                if (phi > osg::PI_2) phi = osg::PI_2;
751
752                phi *= 2.0;
753
754                if (theta<0.0) theta += 2.0*osg::PI;
755
756                // OSG_NOTICE<<"theta = "<<theta<< "phi="<<phi<<std::endl;
757
758                osg::Vec3 texcoord(sin(phi) * cos(theta),
759                                   sin(phi) * sin(theta),
760                                   cos(phi));
761
762                vertices->push_back(cursor);
763                texcoords0->push_back(texcoord * projectorMatrix);
764
765                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
766                if (intensityMap)
767                {
768                    colors->push_back(intensityMap->getColor(texcoord1));
769                }
770                else
771                {
772                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
773                    if (texcoords1) texcoords1->push_back( texcoord1 );
774                }
775
776                cursor += dx;
777            }
778            // OSG_NOTICE<<std::endl;
779        }
780    }
781    else
782    {
783        for(i=0;i<noSteps;++i)
784        {
785            osg::Vec3 cursor = bottom+dy*(float)i;
786            for(j=0;j<noSteps;++j)
787            {
788                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
789                double theta = atan2(-delta.y(), delta.x());
790                double phi = osg::PI_2 * delta.length() / screenRadius;
791                if (phi > osg::PI_2) phi = osg::PI_2;
792                if (theta<0.0) theta += 2.0*osg::PI;
793
794                // OSG_NOTICE<<"theta = "<<theta<< "phi="<<phi<<std::endl;
795
796                double f = distance * sin(phi);
797                double e = distance * cos(phi) + sqrt( sphere_radius*sphere_radius - f*f);
798                double l = e * cos(phi);
799                double h = e * sin(phi);
800                double z = l - distance;
801
802                osg::Vec3 texcoord(h * cos(theta) / sphere_radius,
803                                   h * sin(theta) / sphere_radius,
804                                   z / sphere_radius);
805
806                vertices->push_back(cursor);
807                texcoords0->push_back(texcoord * projectorMatrix);
808
809                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
810                if (intensityMap)
811                {
812                    colors->push_back(intensityMap->getColor(texcoord1));
813                }
814                else
815                {
816                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
817                    if (texcoords1) texcoords1->push_back( texcoord1 );
818                }
819
820                cursor += dx;
821            }
822            // OSG_NOTICE<<std::endl;
823        }
824    }
825
826    // pass the created vertex array to the points geometry object.
827    geometry->setVertexArray(vertices);
828
829    geometry->setColorArray(colors);
830    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
831
832    geometry->setTexCoordArray(0,texcoords0);
833    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
834
835    for(i=0;i<noSteps-1;++i)
836    {
837        osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
838        for(j=0;j<noSteps;++j)
839        {
840            elements->push_back(j+(i+1)*noSteps);
841            elements->push_back(j+(i)*noSteps);
842        }
843        geometry->addPrimitiveSet(elements);
844    }
845
846    return geometry;
847}
848
849void View::setUpViewFor3DSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
850{
851    OSG_INFO<<"View::setUpViewFor3DSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
852    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
853    if (!wsi)
854    {
855        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
856        return;
857    }
858
859    osg::GraphicsContext::ScreenIdentifier si;
860    si.readDISPLAY();
861
862    // displayNum has not been set so reset it to 0.
863    if (si.displayNum<0) si.displayNum = 0;
864
865    si.screenNum = screenNum;
866
867    unsigned int width, height;
868    wsi->getScreenResolution(si, width, height);
869
870
871    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
872    traits->hostName = si.hostName;
873    traits->displayNum = si.displayNum;
874    traits->screenNum = si.screenNum;
875    traits->x = 0;
876    traits->y = 0;
877    traits->width = width;
878    traits->height = height;
879    traits->windowDecoration = false;
880    traits->doubleBuffer = true;
881    traits->sharedContext = 0;
882
883
884    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
885    if (!gc)
886    {
887        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
888        return;
889    }
890
891    bool applyIntensityMapAsColours = true;
892
893    int tex_width = 512;
894    int tex_height = 512;
895
896    int camera_width = tex_width;
897    int camera_height = tex_height;
898
899    osg::TextureCubeMap* texture = new osg::TextureCubeMap;
900
901    texture->setTextureSize(tex_width, tex_height);
902    texture->setInternalFormat(GL_RGB);
903    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
904    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
905    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
906    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
907    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::CLAMP_TO_EDGE);
908
909#if 0
910    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
911    GLenum buffer = GL_FRONT;
912#else
913    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
914    GLenum buffer = GL_FRONT;
915#endif
916
917    // front face
918    {
919        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
920        camera->setName("Front face camera");
921        camera->setGraphicsContext(gc.get());
922        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
923        camera->setDrawBuffer(buffer);
924        camera->setReadBuffer(buffer);
925        camera->setAllowEventFocus(false);
926        // tell the camera to use OpenGL frame buffer object where supported.
927        camera->setRenderTargetImplementation(renderTargetImplementation);
928
929        // attach the texture and use it as the color buffer.
930        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_Y);
931
932        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
933    }
934
935
936    // top face
937    {
938        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
939        camera->setName("Top face camera");
940        camera->setGraphicsContext(gc.get());
941        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
942        camera->setDrawBuffer(buffer);
943        camera->setReadBuffer(buffer);
944        camera->setAllowEventFocus(false);
945
946        // tell the camera to use OpenGL frame buffer object where supported.
947        camera->setRenderTargetImplementation(renderTargetImplementation);
948
949        // attach the texture and use it as the color buffer.
950        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_Z);
951
952        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(-90.0f), 1.0,0.0,0.0));
953    }
954
955    // left face
956    {
957        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
958        camera->setName("Left face camera");
959        camera->setGraphicsContext(gc.get());
960        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
961        camera->setDrawBuffer(buffer);
962        camera->setReadBuffer(buffer);
963        camera->setAllowEventFocus(false);
964
965        // tell the camera to use OpenGL frame buffer object where supported.
966        camera->setRenderTargetImplementation(renderTargetImplementation);
967
968        // attach the texture and use it as the color buffer.
969        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_X);
970
971        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(-90.0f), 0.0,1.0,0.0) * osg::Matrixd::rotate(osg::inDegrees(-90.0f), 0.0,0.0,1.0));
972    }
973
974    // right face
975    {
976        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
977        camera->setName("Right face camera");
978        camera->setGraphicsContext(gc.get());
979        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
980        camera->setDrawBuffer(buffer);
981        camera->setReadBuffer(buffer);
982        camera->setAllowEventFocus(false);
983
984        // tell the camera to use OpenGL frame buffer object where supported.
985        camera->setRenderTargetImplementation(renderTargetImplementation);
986
987        // attach the texture and use it as the color buffer.
988        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_X);
989
990        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(90.0f), 0.0,1.0,0.0 ) * osg::Matrixd::rotate(osg::inDegrees(90.0f), 0.0,0.0,1.0));
991    }
992
993    // bottom face
994    {
995        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
996        camera->setGraphicsContext(gc.get());
997        camera->setName("Bottom face camera");
998        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
999        camera->setDrawBuffer(buffer);
1000        camera->setReadBuffer(buffer);
1001        camera->setAllowEventFocus(false);
1002
1003        // tell the camera to use OpenGL frame buffer object where supported.
1004        camera->setRenderTargetImplementation(renderTargetImplementation);
1005
1006        // attach the texture and use it as the color buffer.
1007        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_Z);
1008
1009        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(90.0f), 1.0,0.0,0.0) * osg::Matrixd::rotate(osg::inDegrees(180.0f), 0.0,0.0,1.0));
1010    }
1011
1012    // back face
1013    {
1014        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1015        camera->setName("Back face camera");
1016        camera->setGraphicsContext(gc.get());
1017        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1018        camera->setDrawBuffer(buffer);
1019        camera->setReadBuffer(buffer);
1020        camera->setAllowEventFocus(false);
1021
1022        // tell the camera to use OpenGL frame buffer object where supported.
1023        camera->setRenderTargetImplementation(renderTargetImplementation);
1024
1025        // attach the texture and use it as the color buffer.
1026        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_Y);
1027
1028        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(180.0f), 1.0,0.0,0.0));
1029    }
1030
1031    getCamera()->setProjectionMatrixAsPerspective(90.0f, 1.0, 1, 1000.0);
1032
1033    // distortion correction set up.
1034    {
1035        osg::Geode* geode = new osg::Geode();
1036        geode->addDrawable(create3DSphericalDisplayDistortionMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), radius, collar, applyIntensityMapAsColours ? intensityMap : 0, projectorMatrix));
1037
1038        // new we need to add the texture to the mesh, we do so by creating a
1039        // StateSet to contain the Texture StateAttribute.
1040        osg::StateSet* stateset = geode->getOrCreateStateSet();
1041        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
1042        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1043
1044        if (!applyIntensityMapAsColours && intensityMap)
1045        {
1046            stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
1047        }
1048
1049        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1050        camera->setGraphicsContext(gc.get());
1051        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1052        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1053        camera->setViewport(new osg::Viewport(0, 0, width, height));
1054        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1055        camera->setDrawBuffer(buffer);
1056        camera->setReadBuffer(buffer);
1057        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1058        camera->setAllowEventFocus(false);
1059        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1060        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1061
1062        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1063        camera->setViewMatrix(osg::Matrix::identity());
1064
1065        // add subgraph to render
1066        camera->addChild(geode);
1067
1068        camera->setName("DistortionCorrectionCamera");
1069
1070        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1071    }
1072
1073    getCamera()->setNearFarRatio(0.0001f);
1074
1075    if (getLightingMode()==osg::View::HEADLIGHT)
1076    {
1077        // set a local light source for headlight to ensure that lighting is consistent across sides of cube.
1078        getLight()->setPosition(osg::Vec4(0.0f,0.0f,0.0f,1.0f));
1079    }
1080}
1081
1082static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, double sphere_radius, double collar_radius, osg::Image* intensityMap, const osg::Matrix& projectorMatrix)
1083{
1084    osg::Vec3d center(0.0,0.0,0.0);
1085    osg::Vec3d eye(0.0,0.0,0.0);
1086
1087    double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
1088    bool flip = false;
1089    bool texcoord_flip = false;
1090
1091    osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
1092
1093
1094    OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
1095    OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
1096
1097    // create the quad to visualize.
1098    osg::Geometry* geometry = new osg::Geometry();
1099
1100    geometry->setSupportsDisplayList(false);
1101
1102    osg::Vec3 xAxis(widthVector);
1103    float width = widthVector.length();
1104    xAxis /= width;
1105
1106    osg::Vec3 yAxis(heightVector);
1107    float height = heightVector.length();
1108    yAxis /= height;
1109
1110    int noSteps = 160;
1111
1112    osg::Vec3Array* vertices = new osg::Vec3Array;
1113    osg::Vec2Array* texcoords0 = new osg::Vec2Array;
1114    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
1115    osg::Vec4Array* colors = new osg::Vec4Array;
1116
1117    osg::Vec3 bottom = origin;
1118    osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
1119    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
1120
1121    osg::Vec3 top = origin + yAxis*height;
1122
1123    osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
1124    float screenRadius = heightVector.length() * 0.5f;
1125
1126    geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
1127
1128    for(int i=0;i<noSteps;++i)
1129    {
1130        osg::Vec3 cursor = bottom+dy*(float)i;
1131        for(int j=0;j<noSteps;++j)
1132        {
1133            osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
1134            double theta = texcoord.x() * 2.0 * osg::PI;
1135            double phi = (1.0-texcoord.y()) * osg::PI;
1136
1137            if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
1138
1139            osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
1140            pos = pos*projectorMatrix;
1141
1142            double alpha = atan2(pos.x(), pos.y());
1143            if (alpha<0.0) alpha += 2.0*osg::PI;
1144
1145            double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
1146            if (beta<0.0) beta += 2.0*osg::PI;
1147
1148            double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
1149            if (gamma<0.0) gamma += 2.0*osg::PI;
1150
1151
1152            osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
1153
1154            if (flip)
1155                vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
1156            else
1157                vertices->push_back(v);
1158
1159            texcoords0->push_back( texcoord );
1160
1161            osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
1162            if (intensityMap)
1163            {
1164                colors->push_back(intensityMap->getColor(texcoord1));
1165            }
1166            else
1167            {
1168                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
1169                if (texcoords1) texcoords1->push_back( texcoord1 );
1170            }
1171
1172
1173        }
1174    }
1175
1176
1177    // pass the created vertex array to the points geometry object.
1178    geometry->setVertexArray(vertices);
1179
1180    geometry->setColorArray(colors);
1181    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
1182
1183    geometry->setTexCoordArray(0,texcoords0);
1184    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
1185
1186    osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
1187    geometry->addPrimitiveSet(elements);
1188
1189    for(int i=0;i<noSteps-1;++i)
1190    {
1191        for(int j=0;j<noSteps-1;++j)
1192        {
1193            int i1 = j+(i+1)*noSteps;
1194            int i2 = j+(i)*noSteps;
1195            int i3 = j+1+(i)*noSteps;
1196            int i4 = j+1+(i+1)*noSteps;
1197
1198            osg::Vec3& v1 = (*vertices)[i1];
1199            osg::Vec3& v2 = (*vertices)[i2];
1200            osg::Vec3& v3 = (*vertices)[i3];
1201            osg::Vec3& v4 = (*vertices)[i4];
1202
1203            if ((v1-screenCenter).length()>screenRadius) continue;
1204            if ((v2-screenCenter).length()>screenRadius) continue;
1205            if ((v3-screenCenter).length()>screenRadius) continue;
1206            if ((v4-screenCenter).length()>screenRadius) continue;
1207
1208            elements->push_back(i1);
1209            elements->push_back(i2);
1210            elements->push_back(i3);
1211
1212            elements->push_back(i1);
1213            elements->push_back(i3);
1214            elements->push_back(i4);
1215        }
1216    }
1217
1218    return geometry;
1219}
1220
1221void View::setUpViewForPanoramicSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
1222{
1223    OSG_INFO<<"View::setUpViewForPanoramicSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
1224
1225    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1226    if (!wsi)
1227    {
1228        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1229        return;
1230    }
1231
1232    osg::GraphicsContext::ScreenIdentifier si;
1233    si.readDISPLAY();
1234
1235    // displayNum has not been set so reset it to 0.
1236    if (si.displayNum<0) si.displayNum = 0;
1237
1238    si.screenNum = screenNum;
1239
1240    unsigned int width, height;
1241    wsi->getScreenResolution(si, width, height);
1242
1243    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1244    traits->hostName = si.hostName;
1245    traits->displayNum = si.displayNum;
1246    traits->screenNum = si.screenNum;
1247    traits->x = 0;
1248    traits->y = 0;
1249    traits->width = width;
1250    traits->height = height;
1251    traits->windowDecoration = false;
1252    traits->doubleBuffer = true;
1253    traits->sharedContext = 0;
1254
1255
1256    bool applyIntensityMapAsColours = true;
1257
1258    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1259    if (!gc)
1260    {
1261        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
1262        return;
1263    }
1264
1265    int tex_width = width;
1266    int tex_height = height;
1267
1268    int camera_width = tex_width;
1269    int camera_height = tex_height;
1270
1271    osg::TextureRectangle* texture = new osg::TextureRectangle;
1272
1273    texture->setTextureSize(tex_width, tex_height);
1274    texture->setInternalFormat(GL_RGB);
1275    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
1276    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
1277    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
1278    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
1279
1280#if 0
1281    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1282    GLenum buffer = GL_FRONT;
1283#else
1284    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1285    GLenum buffer = GL_FRONT;
1286#endif
1287
1288    // front face
1289    {
1290        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1291        camera->setName("Front face camera");
1292        camera->setGraphicsContext(gc.get());
1293        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1294        camera->setDrawBuffer(buffer);
1295        camera->setReadBuffer(buffer);
1296        camera->setAllowEventFocus(false);
1297        // tell the camera to use OpenGL frame buffer object where supported.
1298        camera->setRenderTargetImplementation(renderTargetImplementation);
1299
1300        // attach the texture and use it as the color buffer.
1301        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1302
1303        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1304    }
1305
1306    // distortion correction set up.
1307    {
1308        osg::Geode* geode = new osg::Geode();
1309        geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), radius, collar, applyIntensityMapAsColours ? intensityMap : 0, projectorMatrix));
1310
1311        // new we need to add the texture to the mesh, we do so by creating a
1312        // StateSet to contain the Texture StateAttribute.
1313        osg::StateSet* stateset = geode->getOrCreateStateSet();
1314        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
1315        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1316
1317        osg::TexMat* texmat = new osg::TexMat;
1318        texmat->setScaleByTextureRectangleSize(true);
1319        stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
1320
1321        if (!applyIntensityMapAsColours && intensityMap)
1322        {
1323            stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
1324        }
1325
1326        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1327        camera->setGraphicsContext(gc.get());
1328        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1329        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1330        camera->setViewport(new osg::Viewport(0, 0, width, height));
1331        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1332        camera->setDrawBuffer(buffer);
1333        camera->setReadBuffer(buffer);
1334        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1335        camera->setAllowEventFocus(false);
1336        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1337        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1338
1339        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1340        camera->setViewMatrix(osg::Matrix::identity());
1341
1342        // add subgraph to render
1343        camera->addChild(geode);
1344
1345        camera->setName("DistortionCorrectionCamera");
1346
1347        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1348    }
1349}
1350
1351void View::setUpViewForWoWVxDisplay(unsigned int screenNum, unsigned char wow_content, unsigned char wow_factor, unsigned char wow_offset, float wow_disparity_Zd, float wow_disparity_vz, float wow_disparity_M, float wow_disparity_C)
1352{
1353    OSG_INFO<<"View::setUpViewForWoWVxDisplay(...)"<<std::endl;
1354
1355    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1356    if (!wsi)
1357    {
1358        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1359        return;
1360    }
1361
1362    osg::GraphicsContext::ScreenIdentifier si;
1363    si.readDISPLAY();
1364
1365    // displayNum has not been set so reset it to 0.
1366    if (si.displayNum<0) si.displayNum = 0;
1367
1368    si.screenNum = screenNum;
1369
1370    unsigned int width, height;
1371    wsi->getScreenResolution(si, width, height);
1372
1373    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1374    traits->hostName = si.hostName;
1375    traits->displayNum = si.displayNum;
1376    traits->screenNum = si.screenNum;
1377    traits->x = 0;
1378    traits->y = 0;
1379    traits->width = width;
1380    traits->height = height;
1381    traits->windowDecoration = false;
1382    traits->doubleBuffer = true;
1383    traits->sharedContext = 0;
1384
1385
1386    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1387    if (!gc)
1388    {
1389        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
1390        return;
1391    }
1392
1393    int tex_width = width;
1394    int tex_height = height;
1395
1396    int camera_width = tex_width;
1397    int camera_height = tex_height;
1398
1399    osg::Texture2D* texture = new osg::Texture2D;
1400    texture->setTextureSize(tex_width, tex_height);
1401    texture->setInternalFormat(GL_RGB);
1402    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1403    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1404
1405    osg::Texture2D* textureD = new osg::Texture2D;
1406    textureD->setTextureSize(tex_width, tex_height);
1407    textureD->setInternalFormat(GL_DEPTH_COMPONENT);
1408    textureD->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1409    textureD->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1410
1411#if 0
1412    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1413    GLenum buffer = GL_FRONT;
1414#else
1415    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1416    GLenum buffer = GL_FRONT;
1417#endif
1418
1419    // front face
1420    {
1421        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1422        camera->setName("Front face camera");
1423        camera->setGraphicsContext(gc.get());
1424        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1425        camera->setDrawBuffer(buffer);
1426        camera->setReadBuffer(buffer);
1427        camera->setAllowEventFocus(false);
1428        // tell the camera to use OpenGL frame buffer object where supported.
1429        camera->setRenderTargetImplementation(renderTargetImplementation);
1430
1431        // attach the texture and use it as the color buffer.
1432        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1433        camera->attach(osg::Camera::DEPTH_BUFFER, textureD);
1434
1435        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1436    }
1437
1438    // WoW display set up.
1439    {
1440        osg::Texture1D *textureHeader = new osg::Texture1D();
1441        // Set up the header
1442        {
1443            unsigned char header[]= {0xF1,wow_content,wow_factor,wow_offset,0x00,0x00,0x00,0x00,0x00,0x00};
1444            // Calc the CRC32
1445            {
1446                unsigned long _register = 0;
1447                for(int i = 0; i < 10; ++i) {
1448                    unsigned char mask = 0x80;
1449                    unsigned char byte = header[i];
1450                    for (int j = 0; j < 8; ++j)
1451                    {
1452                        bool topBit = (_register & 0x80000000) != 0;
1453                        _register <<= 1;
1454                        _register ^= ((byte & mask) != 0? 0x1: 0x0);
1455                        if (topBit)
1456                        {
1457                            _register ^= 0x04c11db7;
1458                        }
1459                        mask >>= 1;
1460                    }
1461                }
1462                unsigned char *p = (unsigned char*) &_register;
1463                for(size_t i = 0; i < 4; ++i)
1464                {
1465                    header[i+6] = p[3-i];
1466                }
1467            }
1468
1469            osg::ref_ptr<osg::Image> imageheader = new osg::Image();
1470            imageheader->allocateImage(256,1,1,GL_LUMINANCE,GL_UNSIGNED_BYTE);
1471            {
1472                unsigned char *cheader = imageheader->data();
1473                for (int x=0; x<256; ++x){
1474                    cheader[x] = 0;
1475                }
1476                for (int x=0; x<=9; ++x){
1477                    for (int y=7; y>=0; --y){
1478                        int i = 2*(7-y)+16*x;
1479                        cheader[i] = (((1<<(y))&(header[x])) << (7-(y)));
1480                    }
1481                }
1482            }
1483            textureHeader->setImage(imageheader.get());
1484        }
1485
1486        // Create the Screen Aligned Quad
1487        osg::Geode* geode = new osg::Geode();
1488        {
1489            osg::Geometry* geom = new osg::Geometry;
1490
1491            osg::Vec3Array* vertices = new osg::Vec3Array;
1492            vertices->push_back(osg::Vec3(0,height,0));
1493            vertices->push_back(osg::Vec3(0,0,0));
1494            vertices->push_back(osg::Vec3(width,0,0));
1495            vertices->push_back(osg::Vec3(width,height,0));
1496            geom->setVertexArray(vertices);
1497
1498            osg::Vec2Array* tex = new osg::Vec2Array;
1499            tex->push_back(osg::Vec2(0,1));
1500            tex->push_back(osg::Vec2(0,0));
1501            tex->push_back(osg::Vec2(1,0));
1502            tex->push_back(osg::Vec2(1,1));
1503            geom->setTexCoordArray(0,tex);
1504
1505            geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));
1506            geode->addDrawable(geom);
1507
1508            // new we need to add the textures to the quad, and setting up the shader.
1509            osg::StateSet* stateset = geode->getOrCreateStateSet();
1510            stateset->setTextureAttributeAndModes(0, textureHeader,osg::StateAttribute::ON);
1511            stateset->setTextureAttributeAndModes(1, texture,osg::StateAttribute::ON);
1512            stateset->setTextureAttributeAndModes(2, textureD,osg::StateAttribute::ON);
1513            stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1514
1515            osg::ref_ptr<osg::Program> programShader = new osg::Program();
1516            stateset->setAttribute(programShader.get(), osg::StateAttribute::ON);
1517            stateset->addUniform( new osg::Uniform("wow_width", (int)width));
1518            stateset->addUniform( new osg::Uniform("wow_height", (int)height));
1519            stateset->addUniform( new osg::Uniform("wow_disparity_M", wow_disparity_M));
1520            stateset->addUniform( new osg::Uniform("wow_disparity_Zd", wow_disparity_Zd));
1521            stateset->addUniform( new osg::Uniform("wow_disparity_vz", wow_disparity_vz));
1522            stateset->addUniform( new osg::Uniform("wow_disparity_C", wow_disparity_C));
1523
1524            stateset->addUniform(new osg::Uniform("wow_header", 0));
1525            stateset->addUniform(new osg::Uniform("wow_tcolor", 1));
1526            stateset->addUniform(new osg::Uniform("wow_tdepth", 2));
1527
1528            osg::Shader *frag = new osg::Shader(osg::Shader::FRAGMENT);
1529            frag->setShaderSource(" "\
1530                    " uniform sampler1D wow_header;                                                                                   " \
1531                    " uniform sampler2D wow_tcolor;                                                                                   " \
1532                    " uniform sampler2D wow_tdepth;                                                                                   " \
1533                    "                                                                                                                 " \
1534                    " uniform int wow_width;                                                                                          " \
1535                    " uniform int wow_height;                                                                                         " \
1536                    " uniform float wow_disparity_M;                                                                                  " \
1537                    " uniform float wow_disparity_Zd;                                                                                 " \
1538                    " uniform float wow_disparity_vz;                                                                                 " \
1539                    " uniform float wow_disparity_C;                                                                                  " \
1540                    "                                                                                                                 " \
1541                    " float disparity(float Z)                                                                                        " \
1542                    " {                                                                                                               " \
1543                    "     return (wow_disparity_M*(1.0-(wow_disparity_vz/(Z-wow_disparity_Zd+wow_disparity_vz)))                        " \
1544                    "                   + wow_disparity_C) / 255.0;                                                                   " \
1545                    " }                                                                                                               " \
1546                    "                                                                                                                 " \
1547                    " void main()                                                                                                     " \
1548                    " {                                                                                                               " \
1549                    "       vec2 pos = (gl_FragCoord.xy / vec2(wow_width/2,wow_height) );                                             " \
1550                    "         if (gl_FragCoord.x > float(wow_width/2))                                                                  " \
1551                    "         {                                                                                                         " \
1552                    "             gl_FragColor = vec4(disparity(( texture2D(wow_tdepth, pos - vec2(1,0))).z));                          " \
1553                    "         }                                                                                                         " \
1554                    "         else{                                                                                                     " \
1555                    "             gl_FragColor = texture2D(wow_tcolor, pos);                                                            " \
1556                    "         }                                                                                                         " \
1557                    "     if ( (gl_FragCoord.y >= float(wow_height-1)) && (gl_FragCoord.x < 256.0) )                                    " \
1558                    "     {                                                                                                             " \
1559                    "         float pos = gl_FragCoord.x/256.0;                                                                         " \
1560                    "         float blue = texture1D(wow_header, pos).b;                                                                " \
1561                    "         if ( blue < 0.5)                                                                                          " \
1562                    "             gl_FragColor.b = 0.0;                                                                                 " \
1563                    "         else                                                                                                      " \
1564                    "             gl_FragColor.b = 1.0;                                                                                 " \
1565                    "     }                                                                                                             " \
1566                    " }                                                                                                               " );
1567
1568            programShader->addShader(frag);
1569        }
1570
1571        // Create the Camera
1572        {
1573            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1574            camera->setGraphicsContext(gc.get());
1575            camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1576            camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1577            camera->setViewport(new osg::Viewport(0, 0, width, height));
1578            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1579            camera->setDrawBuffer(buffer);
1580            camera->setReadBuffer(buffer);
1581            camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1582            camera->setAllowEventFocus(false);
1583            camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1584            //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1585
1586            camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1587            camera->setViewMatrix(osg::Matrix::identity());
1588
1589            // add subgraph to render
1590            camera->addChild(geode);
1591
1592            camera->setName("WoWCamera");
1593
1594            addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1595        }
1596    }
1597}
1598
1599DepthPartitionSettings::DepthPartitionSettings(DepthMode mode):
1600    _mode(mode),
1601    _zNear(1.0), _zMid(5.0), _zFar(1000.0)
1602{}
1603
1604bool DepthPartitionSettings::getDepthRange(osg::View& view, unsigned int partition, double& zNear, double& zFar)
1605{
1606    switch(_mode)
1607    {
1608        case(FIXED_RANGE):
1609        {
1610            if (partition==0)
1611            {
1612                zNear = _zNear;
1613                zFar = _zMid;
1614                return true;
1615            }
1616            else if (partition==1)
1617            {
1618                zNear = _zMid;
1619                zFar = _zFar;
1620                return true;
1621            }
1622            return false;
1623        }
1624        case(BOUNDING_VOLUME):
1625        {
1626            osgViewer::View* view_withSceneData = dynamic_cast<osgViewer::View*>(&view);
1627            const osg::Node* node = view_withSceneData ? view_withSceneData->getSceneData() : 0;
1628            if (!node) return false;
1629
1630            const osg::Camera* masterCamera = view.getCamera();
1631            if (!masterCamera) return false;
1632
1633            osg::BoundingSphere bs = node->getBound();
1634            const osg::Matrixd& viewMatrix = masterCamera->getViewMatrix();
1635            //osg::Matrixd& projectionMatrix = masterCamera->getProjectionMatrix();
1636
1637            osg::Vec3d lookVectorInWorldCoords = osg::Matrixd::transform3x3(viewMatrix,osg::Vec3d(0.0,0.0,-1.0));
1638            lookVectorInWorldCoords.normalize();
1639
1640            osg::Vec3d nearPointInWorldCoords = bs.center() - lookVectorInWorldCoords*bs.radius();
1641            osg::Vec3d farPointInWorldCoords = bs.center() + lookVectorInWorldCoords*bs.radius();
1642
1643            osg::Vec3d nearPointInEyeCoords = nearPointInWorldCoords * viewMatrix;
1644            osg::Vec3d farPointInEyeCoords = farPointInWorldCoords * viewMatrix;
1645
1646#if 0
1647            OSG_NOTICE<<std::endl;
1648            OSG_NOTICE<<"viewMatrix = "<<viewMatrix<<std::endl;
1649            OSG_NOTICE<<"lookVectorInWorldCoords = "<<lookVectorInWorldCoords<<std::endl;
1650            OSG_NOTICE<<"nearPointInWorldCoords = "<<nearPointInWorldCoords<<std::endl;
1651            OSG_NOTICE<<"farPointInWorldCoords = "<<farPointInWorldCoords<<std::endl;
1652            OSG_NOTICE<<"nearPointInEyeCoords = "<<nearPointInEyeCoords<<std::endl;
1653            OSG_NOTICE<<"farPointInEyeCoords = "<<farPointInEyeCoords<<std::endl;
1654#endif
1655            double minZNearRatio = 0.00001;
1656
1657
1658            if (masterCamera->getDisplaySettings())
1659            {
1660                OSG_NOTICE<<"Has display settings"<<std::endl;
1661            }
1662
1663            double scene_zNear = -nearPointInEyeCoords.z();
1664            double scene_zFar = -farPointInEyeCoords.z();
1665            if (scene_zNear<=0.0) scene_zNear = minZNearRatio * scene_zFar;
1666
1667            double scene_zMid = sqrt(scene_zFar*scene_zNear);
1668
1669#if 0
1670            OSG_NOTICE<<"scene_zNear = "<<scene_zNear<<std::endl;
1671            OSG_NOTICE<<"scene_zMid = "<<scene_zMid<<std::endl;
1672            OSG_NOTICE<<"scene_zFar = "<<scene_zFar<<std::endl;
1673#endif
1674            if (partition==0)
1675            {
1676                zNear = scene_zNear;
1677                zFar = scene_zMid;
1678                return true;
1679            }
1680            else if (partition==1)
1681            {
1682                zNear = scene_zMid;
1683                zFar = scene_zFar;
1684                return true;
1685            }
1686
1687            return false;
1688        }
1689        default: return false;
1690    }
1691}
1692
1693namespace osgDepthPartition {
1694
1695struct MyUpdateSlaveCallback : public osg::View::Slave::UpdateSlaveCallback
1696{
1697    MyUpdateSlaveCallback(DepthPartitionSettings* dps, unsigned int partition):_dps(dps), _partition(partition) {}
1698
1699    virtual void updateSlave(osg::View& view, osg::View::Slave& slave)
1700    {
1701        slave.updateSlaveImplementation(view);
1702
1703        if (!_dps) return;
1704
1705        osg::Camera* camera = slave._camera.get();
1706
1707        double computed_zNear;
1708        double computed_zFar;
1709        if (!_dps->getDepthRange(view, _partition, computed_zNear, computed_zFar))
1710        {
1711            OSG_NOTICE<<"Switching off Camera "<<camera<<std::endl;
1712            camera->setNodeMask(0x0);
1713            return;
1714        }
1715        else
1716        {
1717            camera->setNodeMask(0xffffff);
1718        }
1719
1720        if (camera->getProjectionMatrix()(0,3)==0.0 &&
1721            camera->getProjectionMatrix()(1,3)==0.0 &&
1722            camera->getProjectionMatrix()(2,3)==0.0)
1723        {
1724            double left, right, bottom, top, zNear, zFar;
1725            camera->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar);
1726            camera->setProjectionMatrixAsOrtho(left, right, bottom, top, computed_zNear, computed_zFar);
1727        }
1728        else
1729        {
1730            double left, right, bottom, top, zNear, zFar;
1731            camera->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
1732
1733            double nr = computed_zNear / zNear;
1734            camera->setProjectionMatrixAsFrustum(left * nr, right * nr, bottom * nr, top * nr, computed_zNear, computed_zFar);
1735        }
1736    }
1737
1738    osg::ref_ptr<DepthPartitionSettings> _dps;
1739    unsigned int _partition;
1740};
1741
1742
1743typedef std::list< osg::ref_ptr<osg::Camera> > Cameras;
1744
1745Cameras getActiveCameras(osg::View& view)
1746{
1747    Cameras activeCameras;
1748
1749    if (view.getCamera() && view.getCamera()->getGraphicsContext())
1750    {
1751        activeCameras.push_back(view.getCamera());
1752    }
1753
1754    for(unsigned int i=0; i<view.getNumSlaves(); ++i)
1755    {
1756        osg::View::Slave& slave = view.getSlave(i);
1757        if (slave._camera.valid() && slave._camera->getGraphicsContext())
1758        {
1759            activeCameras.push_back(slave._camera.get());
1760        }
1761    }
1762    return activeCameras;
1763}
1764
1765}
1766
1767bool View::setUpDepthPartitionForCamera(osg::Camera* cameraToPartition, DepthPartitionSettings* incomming_dps)
1768{
1769    osg::ref_ptr<osg::GraphicsContext> context = cameraToPartition->getGraphicsContext();
1770    if (!context) return false;
1771
1772    osg::ref_ptr<osg::Viewport> viewport = cameraToPartition->getViewport();
1773    if (!viewport) return false;
1774
1775    osg::ref_ptr<DepthPartitionSettings> dps = incomming_dps;
1776    if (!dps) dps = new DepthPartitionSettings;
1777
1778    bool useMastersSceneData = true;
1779    osg::Matrixd projectionOffset;
1780    osg::Matrixd viewOffset;
1781
1782    if (getCamera()==cameraToPartition)
1783    {
1784        // replace main camera with depth partition cameras
1785        OSG_INFO<<"View::setUpDepthPartitionForCamera(..) Replacing main Camera"<<std::endl;
1786    }
1787    else
1788    {
1789        unsigned int i = findSlaveIndexForCamera(cameraToPartition);
1790        if (i>=getNumSlaves()) return false;
1791
1792        osg::View::Slave& slave = getSlave(i);
1793
1794        useMastersSceneData = slave._useMastersSceneData;
1795        projectionOffset = slave._projectionOffset;
1796        viewOffset = slave._viewOffset;
1797
1798        OSG_NOTICE<<"View::setUpDepthPartitionForCamera(..) Replacing slave Camera"<<i<<std::endl;
1799        removeSlave(i);
1800    }
1801
1802    cameraToPartition->setGraphicsContext(0);
1803    cameraToPartition->setViewport(0);
1804
1805    // far camera
1806    {
1807        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1808        camera->setGraphicsContext(context.get());
1809        camera->setViewport(viewport.get());
1810
1811        camera->setDrawBuffer(cameraToPartition->getDrawBuffer());
1812        camera->setReadBuffer(cameraToPartition->getReadBuffer());
1813
1814        camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
1815        camera->setCullingMode(osg::Camera::ENABLE_ALL_CULLING);
1816
1817        addSlave(camera.get());
1818
1819        osg::View::Slave& slave = getSlave(getNumSlaves()-1);
1820
1821        slave._useMastersSceneData = useMastersSceneData;
1822        slave._projectionOffset = projectionOffset;
1823        slave._viewOffset = viewOffset;
1824        slave._updateSlaveCallback =  new osgDepthPartition::MyUpdateSlaveCallback(dps.get(), 1);
1825    }
1826
1827    // near camera
1828    {
1829        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1830        camera->setGraphicsContext(context.get());
1831        camera->setViewport(viewport.get());
1832
1833        camera->setDrawBuffer(cameraToPartition->getDrawBuffer());
1834        camera->setReadBuffer(cameraToPartition->getReadBuffer());
1835
1836        camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
1837        camera->setCullingMode(osg::Camera::ENABLE_ALL_CULLING);
1838        camera->setClearMask(GL_DEPTH_BUFFER_BIT);
1839
1840        addSlave(camera.get());
1841
1842        osg::View::Slave& slave = getSlave(getNumSlaves()-1);
1843        slave._useMastersSceneData = useMastersSceneData;
1844        slave._projectionOffset = projectionOffset;
1845        slave._viewOffset = viewOffset;
1846        slave._updateSlaveCallback =  new osgDepthPartition::MyUpdateSlaveCallback(dps.get(), 0);
1847    }
1848
1849    return true;
1850}
1851
1852
1853
1854bool View::setUpDepthPartition(DepthPartitionSettings* dsp)
1855{
1856    osgDepthPartition::Cameras originalCameras = osgDepthPartition::getActiveCameras(*this);
1857    if (originalCameras.empty())
1858    {
1859        OSG_INFO<<"osgView::View::setUpDepthPartition(,..), no windows assigned, doing view.setUpViewAcrossAllScreens()"<<std::endl;
1860        setUpViewAcrossAllScreens();
1861
1862        originalCameras = osgDepthPartition::getActiveCameras(*this);
1863        if (originalCameras.empty())
1864        {
1865            OSG_NOTICE<<"osgView::View::setUpDepthPartition(View,..) Unable to set up windows for viewer."<<std::endl;
1866            return false;
1867        }
1868    }
1869
1870    bool threadsWereRunning = getViewerBase()->areThreadsRunning();
1871    if (threadsWereRunning) getViewerBase()->stopThreading();
1872
1873    for(osgDepthPartition::Cameras::iterator itr = originalCameras.begin();
1874        itr != originalCameras.end();
1875        ++itr)
1876    {
1877        setUpDepthPartitionForCamera(itr->get(), dsp);
1878    }
1879
1880    if (threadsWereRunning) getViewerBase()->startThreading();
1881
1882    return true;
1883}
1884
1885
1886void View::assignSceneDataToCameras()
1887{
1888    // OSG_NOTICE<<"View::assignSceneDataToCameras()"<<std::endl;
1889
1890    if (_scene.valid() && _scene->getDatabasePager() && getViewerBase())
1891    {
1892        _scene->getDatabasePager()->setIncrementalCompileOperation(getViewerBase()->getIncrementalCompileOperation());
1893    }
1894
1895    osg::Node* sceneData = _scene.valid() ? _scene->getSceneData() : 0;
1896
1897    if (_cameraManipulator.valid())
1898    {
1899        _cameraManipulator->setNode(sceneData);
1900
1901        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
1902
1903        _cameraManipulator->home(*dummyEvent, *this);
1904    }
1905
1906    if (_camera.valid())
1907    {
1908        _camera->removeChildren(0,_camera->getNumChildren());
1909        if (sceneData) _camera->addChild(sceneData);
1910
1911        Renderer* renderer = dynamic_cast<Renderer*>(_camera->getRenderer());
1912        if (renderer) renderer->setCompileOnNextDraw(true);
1913
1914    }
1915
1916    for(unsigned i=0; i<getNumSlaves(); ++i)
1917    {
1918        Slave& slave = getSlave(i);
1919        if (slave._camera.valid() && slave._useMastersSceneData)
1920        {
1921            slave._camera->removeChildren(0,slave._camera->getNumChildren());
1922            if (sceneData) slave._camera->addChild(sceneData);
1923
1924            Renderer* renderer = dynamic_cast<Renderer*>(slave._camera->getRenderer());
1925            if (renderer) renderer->setCompileOnNextDraw(true);
1926        }
1927    }
1928}
1929
1930void View::requestRedraw()
1931{
1932    if (getViewerBase())
1933    {
1934        getViewerBase()->_requestRedraw = true;
1935    }
1936    else
1937    {
1938        OSG_INFO<<"View::requestRedraw(), No viewer base has been assigned yet."<<std::endl;
1939    }
1940}
1941
1942void View::requestContinuousUpdate(bool flag)
1943{
1944    if (getViewerBase())
1945    {
1946        getViewerBase()->_requestContinousUpdate = flag;
1947    }
1948    else
1949    {
1950        OSG_INFO<<"View::requestContinuousUpdate(), No viewer base has been assigned yet."<<std::endl;
1951    }
1952}
1953
1954void View::requestWarpPointer(float x,float y)
1955{
1956    OSG_INFO<<"View::requestWarpPointer("<<x<<","<<y<<")"<<std::endl;
1957
1958    float local_x, local_y;
1959    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
1960    if (camera)
1961    {
1962        const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(camera->getGraphicsContext());
1963        if (gw)
1964        {
1965            getEventQueue()->mouseWarped(x,y);
1966            if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS)
1967            {
1968                local_y = gw->getTraits()->height - local_y;
1969            }
1970            const_cast<osgViewer::GraphicsWindow*>(gw)->getEventQueue()->mouseWarped(local_x,local_y);
1971            const_cast<osgViewer::GraphicsWindow*>(gw)->requestWarpPointer(local_x, local_y);
1972        }
1973    }
1974    else
1975    {
1976        OSG_INFO<<"View::requestWarpPointer failed no camera containing pointer"<<std::endl;
1977    }
1978}
1979
1980bool View::containsCamera(const osg::Camera* camera) const
1981{
1982    if (_camera == camera) return true;
1983
1984    for(unsigned i=0; i<getNumSlaves(); ++i)
1985    {
1986        const Slave& slave = getSlave(i);
1987        if (slave._camera == camera) return true;
1988    }
1989    return false;
1990}
1991
1992const osg::Camera* View::getCameraContainingPosition(float x, float y, float& local_x, float& local_y) const
1993{
1994    const osgGA::GUIEventAdapter* eventState = getEventQueue()->getCurrentEventState();
1995    const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(eventState->getGraphicsContext());
1996
1997    bool view_invert_y = eventState->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS;
1998
1999    double epsilon = 0.5;
2000
2001    if (_camera->getGraphicsContext() &&
2002        (!gw || _camera->getGraphicsContext()==gw) &&
2003        _camera->getViewport())
2004    {
2005        const osg::Viewport* viewport = _camera->getViewport();
2006
2007        double new_x = x;
2008        double new_y = y;
2009
2010        if (!gw)
2011        {
2012            new_x = static_cast<double>(_camera->getGraphicsContext()->getTraits()->width) * (x - eventState->getXmin())/(eventState->getXmax()-eventState->getXmin());
2013            new_y = view_invert_y ?
2014                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (1.0 - (y- eventState->getYmin())/(eventState->getYmax()-eventState->getYmin())) :
2015                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (y - eventState->getYmin())/(eventState->getYmax()-eventState->getXmin());
2016        }
2017
2018        if (viewport &&
2019            new_x >= (viewport->x()-epsilon) && new_y >= (viewport->y()-epsilon) &&
2020            new_x < (viewport->x()+viewport->width()-1.0+epsilon) && new_y <= (viewport->y()+viewport->height()-1.0+epsilon) )
2021        {
2022            local_x = new_x;
2023            local_y = new_y;
2024
2025            OSG_INFO<<"Returning master camera"<<std::endl;
2026
2027            return _camera.get();
2028        }
2029    }
2030
2031    osg::Matrix masterCameraVPW = getCamera()->getViewMatrix() * getCamera()->getProjectionMatrix();
2032
2033    // convert to non dimensional
2034    x = (x - eventState->getXmin()) * 2.0 / (eventState->getXmax()-eventState->getXmin()) - 1.0;
2035    y = (y - eventState->getYmin())* 2.0 / (eventState->getYmax()-eventState->getYmin()) - 1.0;
2036
2037    if (view_invert_y) y = - y;
2038
2039    for(int i=getNumSlaves()-1; i>=0; --i)
2040    {
2041        const Slave& slave = getSlave(i);
2042        if (slave._camera.valid() &&
2043            slave._camera->getAllowEventFocus() &&
2044            slave._camera->getRenderTargetImplementation()==osg::Camera::FRAME_BUFFER)
2045        {
2046            OSG_INFO<<"Testing slave camera "<<slave._camera->getName()<<std::endl;
2047
2048            const osg::Camera* camera = slave._camera.get();
2049            const osg::Viewport* viewport = camera ? camera->getViewport() : 0;
2050
2051            osg::Matrix localCameraVPW = camera->getViewMatrix() * camera->getProjectionMatrix();
2052            if (viewport) localCameraVPW *= viewport->computeWindowMatrix();
2053
2054            osg::Matrix matrix( osg::Matrix::inverse(masterCameraVPW) * localCameraVPW );
2055
2056            osg::Vec3d new_coord = osg::Vec3d(x,y,0.0) * matrix;
2057
2058            //OSG_NOTICE<<"  x="<<x<<" y="<<y<<std::endl;;
2059            //OSG_NOTICE<<"  eventState->getXmin()="<<eventState->getXmin()<<" eventState->getXmax()="<<eventState->getXmax()<<std::endl;;
2060            //OSG_NOTICE<<"  new_coord "<<new_coord<<std::endl;;
2061
2062            if (viewport &&
2063                new_coord.x() >= (viewport->x()-epsilon) && new_coord.y() >= (viewport->y()-epsilon) &&
2064                new_coord.x() < (viewport->x()+viewport->width()-1.0+epsilon) && new_coord.y() <= (viewport->y()+viewport->height()-1.0+epsilon) )
2065            {
2066                // OSG_NOTICE<<"  in viewport "<<std::endl;;
2067
2068                local_x = new_coord.x();
2069                local_y = new_coord.y();
2070
2071                return camera;
2072            }
2073            else
2074            {
2075                // OSG_NOTICE<<"  not in viewport "<<viewport->x()<<" "<<(viewport->x()+viewport->width())<<std::endl;;
2076            }
2077
2078        }
2079    }
2080
2081    local_x = x;
2082    local_y = y;
2083
2084    return 0;
2085}
2086
2087bool View::computeIntersections(float x,float y, osgUtil::LineSegmentIntersector::Intersections& intersections, osg::Node::NodeMask traversalMask)
2088{
2089    if (!_camera.valid()) return false;
2090
2091    float local_x, local_y = 0.0;
2092    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
2093    if (!camera) camera = _camera.get();
2094
2095
2096    osgUtil::LineSegmentIntersector::CoordinateFrame cf = camera->getViewport() ? osgUtil::Intersector::WINDOW : osgUtil::Intersector::PROJECTION;
2097    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(cf, local_x, local_y);
2098
2099#if 0
2100    OSG_NOTICE<<"View::computeIntersections(x="<<x<<", y="<<y<<", local_x="<<local_x<<", local_y="<<local_y<<") "<<cf<<std::endl;
2101    OSG_NOTICE<<"  viewport ("<<camera->getViewport()->x()<<","<<camera->getViewport()->y()<<","<<camera->getViewport()->width()<<","<<camera->getViewport()->height()<<")"<<std::endl;
2102
2103    const osg::GraphicsContext::Traits* traits = camera->getGraphicsContext() ? camera->getGraphicsContext()->getTraits() : 0;
2104    if (traits)
2105    {
2106        OSG_NOTICE<<"  window ("<<traits->x<<","<<traits->y<<","<<traits->width<<","<<traits->height<<")"<<std::endl;
2107    }
2108#endif
2109
2110    osgUtil::IntersectionVisitor iv(picker.get());
2111    iv.setTraversalMask(traversalMask);
2112
2113
2114#if 1
2115    const_cast<osg::Camera*>(camera)->accept(iv);
2116#else
2117
2118    // timing test code paths for comparing KdTree based intersections vs conventional intersections
2119
2120    iv.setUseKdTreeWhenAvailable(true);
2121    iv.setDoDummyTraversal(true);
2122
2123    const_cast<osg::Camera*>(camera)->accept(iv);
2124
2125
2126    osg::Timer_t before = osg::Timer::instance()->tick();
2127    const_cast<osg::Camera*>(camera)->accept(iv);
2128
2129    osg::Timer_t after_dummy = osg::Timer::instance()->tick();
2130
2131    int intersectsBeforeKdTree = picker->getIntersections().size();
2132
2133    iv.setDoDummyTraversal(false);
2134    const_cast<osg::Camera*>(camera)->accept(iv);
2135    osg::Timer_t after_kdTree_2 = osg::Timer::instance()->tick();
2136
2137    int intersectsBeforeConventional = picker->getIntersections().size();
2138
2139    iv.setUseKdTreeWhenAvailable(false);
2140    const_cast<osg::Camera*>(camera)->accept(iv);
2141    osg::Timer_t after = osg::Timer::instance()->tick();
2142
2143    int intersectsAfterConventional = picker->getIntersections().size();
2144
2145    double timeDummy = osg::Timer::instance()->delta_m(before, after_dummy);
2146    double timeKdTree = osg::Timer::instance()->delta_m(after_dummy, after_kdTree_2);
2147    double timeConventional = osg::Timer::instance()->delta_m(after_kdTree_2, after);
2148
2149    OSG_NOTICE<<"Using Dummy                    "<<timeDummy<<std::endl;
2150    OSG_NOTICE<<"      KdTrees                  "<<timeKdTree
2151                            <<"\tNum intersects = "<<intersectsBeforeConventional-intersectsBeforeKdTree<<std::endl;
2152    OSG_NOTICE<<"      KdTrees - Traversal      "<<timeKdTree-timeDummy<<std::endl;
2153    OSG_NOTICE<<"      Conventional             "<<timeConventional
2154                            <<"\tNum intersects = "<<intersectsAfterConventional-intersectsBeforeConventional<<std::endl;
2155    OSG_NOTICE<<"      Conventional - Traversal "<<timeConventional-timeDummy<<std::endl;
2156    OSG_NOTICE<<"      Delta                    "<<timeConventional/timeKdTree<<std::endl;
2157    OSG_NOTICE<<"      Delta sans Traversal     "<<(timeConventional-timeDummy)/(timeKdTree-timeDummy)<<std::endl;
2158    OSG_NOTICE<<std::endl;
2159#endif
2160
2161    if (picker->containsIntersections())
2162    {
2163        intersections = picker->getIntersections();
2164        return true;
2165    }
2166    else
2167    {
2168        intersections.clear();
2169        return false;
2170    }
2171}
2172
2173bool View::computeIntersections(float x,float y, const osg::NodePath& nodePath, osgUtil::LineSegmentIntersector::Intersections& intersections,osg::Node::NodeMask traversalMask)
2174{
2175    if (!_camera.valid() || nodePath.empty()) return false;
2176
2177    float local_x, local_y = 0.0;
2178    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
2179    if (!camera) camera = _camera.get();
2180
2181    osg::Matrixd matrix;
2182    if (nodePath.size()>1)
2183    {
2184        osg::NodePath prunedNodePath(nodePath.begin(),nodePath.end()-1);
2185        matrix = osg::computeLocalToWorld(prunedNodePath);
2186    }
2187
2188    matrix.postMult(camera->getViewMatrix());
2189    matrix.postMult(camera->getProjectionMatrix());
2190
2191    double zNear = -1.0;
2192    double zFar = 1.0;
2193    if (camera->getViewport())
2194    {
2195        matrix.postMult(camera->getViewport()->computeWindowMatrix());
2196        zNear = 0.0;
2197        zFar = 1.0;
2198    }
2199
2200    osg::Matrixd inverse;
2201    inverse.invert(matrix);
2202
2203    osg::Vec3d startVertex = osg::Vec3d(local_x,local_y,zNear) * inverse;
2204    osg::Vec3d endVertex = osg::Vec3d(local_x,local_y,zFar) * inverse;
2205
2206    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL, startVertex, endVertex);
2207
2208    osgUtil::IntersectionVisitor iv(picker.get());
2209    iv.setTraversalMask(traversalMask);
2210    nodePath.back()->accept(iv);
2211
2212    if (picker->containsIntersections())
2213    {
2214        intersections = picker->getIntersections();
2215        return true;
2216    }
2217    else
2218    {
2219        intersections.clear();
2220        return false;
2221    }
2222}
2223
Note: See TracBrowser for help on using the browser.