bool CompositeViewer::checkNeedToDoFrame()
{
    if (_requestRedraw) return true;
    if (_requestContinousUpdate) return true;

    for(RefViews::iterator itr = _views.begin();
            itr != _views.end();
            ++itr)
    {
        osgViewer::View* view = itr->get();
        if (view)
        {
            // If the database pager is going to update the scene the render flag is
            // set so that the updates show up
            if (view->getDatabasePager()->requiresUpdateSceneGraph() ||
                    view->getDatabasePager()->getRequestsInProgress()) return true;

            // if there update callbacks then we need to do frame.
            if (view->getCamera()->getUpdateCallback()) return true;
            if (view->getSceneData()!=0 && view->getSceneData()->getNumChildrenRequiringUpdateTraversal()>0) return true;
        }
    }

    // check if events are available and need processing
    if (checkEvents()) return true;

    if (_requestRedraw) return true;
    if (_requestContinousUpdate) return true;

    return false;
}
Exemplo n.º 2
0
void CompositeViewer::advance( const uint32_t frameNumber,
        const FrameData& frameData )
{
    _frameStamp->setFrameNumber( frameNumber );
    // reference time has to use osg::Timer because other OSG internals that
    // attempt to compute relative time based on the frame stamp also use it
    // (e.g. IncrementalCompileOperation)
    _frameStamp->setReferenceTime( osg::Timer::instance( )->delta_s( _startTick,
        osg::Timer::instance( )->tick( )));
    _frameStamp->setSimulationTime( frameData.getSimulationTime( ));
    const time_t calendar = frameData.getCalendarTime( );
    struct tm now;
    if( NULL != gmtime_r( &calendar, &now ))
        _frameStamp->setCalendarTime( now );

#if OSG_VERSION_GREATER_OR_EQUAL( 3, 0, 0 )
    for( RefViews::iterator vitr = _views.begin( );
            vitr != _views.end( ); ++vitr )
    {
        osgViewer::View *view = vitr->get( );
        view->getEventQueue( )->frame( _frameStamp->getReferenceTime( ));
    }
#endif

    if( osg::Referenced::getDeleteHandler( ))
    {
        osg::Referenced::getDeleteHandler( )->flush( );
        osg::Referenced::getDeleteHandler( )->setFrameNumber( frameNumber );
    }
}
Exemplo n.º 3
0
bool CompositeViewer::checkNeedToDoFrame()
{
    if (_requestRedraw) return true;
    if (_requestContinousUpdate) return true;

    for(RefViews::iterator itr = _views.begin();
        itr != _views.end();
        ++itr)
    {
        osgViewer::View* view = itr->get();
        if (view)
        {
            // If the database pager is going to update the scene the render flag is
            // set so that the updates show up
            if (view->getDatabasePager()->requiresUpdateSceneGraph() ||
                view->getDatabasePager()->getRequestsInProgress()) return true;
        }
    }

    // now do a eventTraversal to see if any events might require a new frame.
    eventTraversal();

    if (_requestRedraw) return true;
    if (_requestContinousUpdate) return true;

    return false;
}
Exemplo n.º 4
0
void CompositeViewer::getViews(Views& views, bool onlyValid)
{
    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        views.push_back(vitr->get());
    }
}
int CompositeViewer::run()
{
    for(RefViews::iterator itr = _views.begin();
            itr != _views.end();
            ++itr)
    {
        osgViewer::View* view = itr->get();
        if ((view->getCameraManipulator()==0) && view->getCamera()->getAllowEventFocus())
        {
            view->setCameraManipulator(new osgGA::TrackballManipulator());
        }
    }

    setReleaseContextAtEndOfFrameHint(false);

    return ViewerBase::run();
}
void CompositeViewer::setCameraWithFocus(osg::Camera* camera)
{
    _cameraWithFocus = camera;

    if (camera)
    {
        for(RefViews::iterator vitr = _views.begin();
                vitr != _views.end();
                ++vitr)
        {
            View* view = vitr->get();
            if (view->containsCamera(camera))
            {
                _viewWithFocus = view;
                return;
            }
        }
    }

    _viewWithFocus = 0;
}
void CompositeViewer::getScenes(Scenes& scenes, bool onlyValid)
{
    scenes.clear();

    typedef std::set<osgViewer::Scene*> SceneSet;
    SceneSet sceneSet;

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        osgViewer::View* view = vitr->get();
        if (view->getScene() && (!onlyValid || view->getScene()->getSceneData()))
        {
            if (sceneSet.count(view->getScene())==0)
            {
                sceneSet.insert(view->getScene());
                scenes.push_back(view->getScene());
            }
        }
    }
}
void CompositeViewer::getCameras(Cameras& cameras, bool onlyActive)
{
    cameras.clear();

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        View* view = vitr->get();

        if (view->getCamera() &&
                (!onlyActive || (view->getCamera()->getGraphicsContext() && view->getCamera()->getGraphicsContext()->valid())) ) cameras.push_back(view->getCamera());

        for(View::Slaves::iterator itr = view->_slaves.begin();
                itr != view->_slaves.end();
                ++itr)
        {
            if (itr->_camera.valid() &&
                    (!onlyActive || (itr->_camera->getGraphicsContext() && itr->_camera->getGraphicsContext()->valid())) ) cameras.push_back(itr->_camera.get());
        }
    }
}
Exemplo n.º 9
0
void CompositeViewer::getContexts(Contexts& contexts, bool onlyValid)
{
    typedef std::set<osg::GraphicsContext*> ContextSet;
    ContextSet contextSet;

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        osgViewer::View* view = vitr->get();
        if (view->getCamera() &&
                view->getCamera()->getGraphicsContext() &&
                (view->getCamera()->getGraphicsContext()->valid() || !onlyValid))
        {
            contextSet.insert(view->getCamera()->getGraphicsContext());
        }

        for(unsigned int i=0; i<view->getNumSlaves(); ++i)
        {
            View::Slave& slave = view->getSlave(i);
            if (slave._camera.valid() &&
                    slave._camera->getGraphicsContext() &&
                    (slave._camera->getGraphicsContext()->valid() || !onlyValid))
            {
                contextSet.insert(slave._camera->getGraphicsContext());
            }
        }
    }

    contexts.clear();
    contexts.reserve(contextSet.size());

    for(ContextSet::iterator itr = contextSet.begin();
            itr != contextSet.end();
            ++itr)
    {
        contexts.push_back(const_cast<osg::GraphicsContext*>(*itr));
    }
}
Exemplo n.º 10
0
void CompositeViewer::getScenes(Scenes& scenes, bool onlyValid)
{
    typedef std::set<osgViewer::Scene*> SceneSet;
    SceneSet sceneSet;

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        osgViewer::View* view = vitr->get();
        if (view->getScene() && (!onlyValid || view->getScene()->getSceneData()))
        {
            sceneSet.insert(view->getScene());
        }
    }

    for(SceneSet::iterator sitr = sceneSet.begin();
            sitr != sceneSet.end();
            ++sitr)
    {
        scenes.push_back(const_cast<osgViewer::Scene*>(*sitr));
    }
}
void CompositeViewer::getContexts(Contexts& contexts, bool onlyValid)
{
    typedef std::set<osg::GraphicsContext*> ContextSet;
    ContextSet contextSet;

    contexts.clear();

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        osgViewer::View* view = vitr->get();
        osg::GraphicsContext* gc = view->getCamera() ? view->getCamera()->getGraphicsContext() : 0;
        if (gc && (gc->valid() || !onlyValid))
        {
            if (contextSet.count(gc)==0)
            {
                contextSet.insert(gc);
                contexts.push_back(gc);
            }
        }

        for(unsigned int i=0; i<view->getNumSlaves(); ++i)
        {
            View::Slave& slave = view->getSlave(i);
            osg::GraphicsContext* sgc = slave._camera.valid() ? slave._camera->getGraphicsContext() : 0;
            if (sgc && (sgc->valid() || !onlyValid))
            {
                if (contextSet.count(sgc)==0)
                {
                    contextSet.insert(sgc);
                    contexts.push_back(sgc);
                }
            }
        }
    }
}
bool CompositeViewer::checkEvents()
{
    for(RefViews::iterator itr = _views.begin();
            itr != _views.end();
            ++itr)
    {
        osgViewer::View* view = itr->get();
        if (view)
        {
            // check events from any attached sources
            for(View::Devices::iterator eitr = view->getDevices().begin();
                    eitr != view->getDevices().end();
                    ++eitr)
            {
                osgGA::Device* es = eitr->get();
                if (es->getCapabilities() & osgGA::Device::RECEIVE_EVENTS)
                {
                    if (es->checkEvents()) return true;
                }

            }
        }
    }

    // get events from all windows attached to Viewer.
    Windows windows;
    getWindows(windows);
    for(Windows::iterator witr = windows.begin();
            witr != windows.end();
            ++witr)
    {
        if ((*witr)->checkEvents()) return true;
    }

    return false;
}
Exemplo n.º 13
0
bool CompositeViewer::checkNeedToDoFrame()
{
    // check if any event handler has prompted a redraw
    if (_requestRedraw) return true;
    if (_requestContinousUpdate) return true;

    // check if any view needs to update the scene graph
    for(RefViews::iterator itr = _views.begin();
        itr != _views.end();
        ++itr)
    {
        osgViewer::View* view = itr->get();
        if (view && view->requiresUpdateSceneGraph()) return true;
    }

    // check if events are available and need processing
    if (checkEvents()) return true;

    // and check again if any event handler has prompted a redraw
    if (_requestRedraw) return true;
    if (_requestContinousUpdate) return true;

    return false;
}
Exemplo n.º 14
0
void CompositeViewer::eventTraversal()
{
    if (_done) return;

    if (_views.empty()) return;

    double beginEventTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

    // OSG_NOTICE<<"CompositeViewer::frameEventTraversal()."<<std::endl;

    // need to copy events from the GraphicsWindow's into local EventQueue;

    typedef std::map<osgViewer::View*, osgGA::EventQueue::Events> ViewEventsMap;
    ViewEventsMap viewEventsMap;

    Contexts contexts;
    getContexts(contexts);

    Scenes scenes;
    getScenes(scenes);

    osgViewer::View* masterView = getViewWithFocus() ? getViewWithFocus() : _views[0].get();

    osg::Camera* masterCamera = masterView->getCamera();
    osgGA::GUIEventAdapter* eventState = masterView->getEventQueue()->getCurrentEventState();
    osg::Matrix masterCameraVPW = masterCamera->getViewMatrix() * masterCamera->getProjectionMatrix();
    if (masterCamera->getViewport())
    {
        osg::Viewport* viewport = masterCamera->getViewport();
        masterCameraVPW *= viewport->computeWindowMatrix();
    }

    for(Contexts::iterator citr = contexts.begin();
        citr != contexts.end();
        ++citr)
    {
        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(*citr);
        if (gw)
        {
            gw->checkEvents();

            osgGA::EventQueue::Events gw_events;
            gw->getEventQueue()->takeEvents(gw_events);

            osgGA::EventQueue::Events::iterator itr;
            for(itr = gw_events.begin();
                itr != gw_events.end();
                ++itr)
            {
                osgGA::GUIEventAdapter* event = itr->get();

                //OSG_NOTICE<<"event->getGraphicsContext()="<<event->getGraphicsContext()<<std::endl;

                bool pointerEvent = false;

                float x = event->getX();
                float y = event->getY();

                bool invert_y = event->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS;
                if (invert_y && gw->getTraits()) y = gw->getTraits()->height - y;

                switch(event->getEventType())
                {
                    case(osgGA::GUIEventAdapter::RESIZE):
                        setCameraWithFocus(0);
                        break;
                    case(osgGA::GUIEventAdapter::PUSH):
                    case(osgGA::GUIEventAdapter::RELEASE):
                    case(osgGA::GUIEventAdapter::DOUBLECLICK):
                    case(osgGA::GUIEventAdapter::DRAG):
                    case(osgGA::GUIEventAdapter::MOVE):
                    {
                        pointerEvent = true;

                        if (event->getEventType()!=osgGA::GUIEventAdapter::DRAG || !getCameraWithFocus())
                        {
                            osg::GraphicsContext::Cameras& cameras = gw->getCameras();
                            for(osg::GraphicsContext::Cameras::iterator citr = cameras.begin();
                                citr != cameras.end();
                                ++citr)
                            {
                                osg::Camera* camera = *citr;
                                if (camera->getView() &&
                                    camera->getAllowEventFocus() &&
                                    camera->getRenderTargetImplementation()==osg::Camera::FRAME_BUFFER)
                                {
                                    osg::Viewport* viewport = camera ? camera->getViewport() : 0;
                                    if (viewport &&
                                        x >= viewport->x() && y >= viewport->y() &&
                                        x <= (viewport->x()+viewport->width()) && y <= (viewport->y()+viewport->height()) )
                                    {
                                        setCameraWithFocus(camera);

                                        // If this camera is not a slave camera
                                        if (camera->getView()->getCamera() == camera)
                                        {
                                            eventState->setGraphicsContext(gw);
                                            eventState->setInputRange( viewport->x(), viewport->y(),
                                                                    viewport->x()+viewport->width(),
                                                                    viewport->y()+viewport->height());

                                        }
                                        else
                                        {
                                            eventState->setInputRange(-1.0, -1.0, 1.0, 1.0);
                                        }

                                        if (getViewWithFocus()!=masterView)
                                        {
                                            // need to reset the masterView
                                            masterView = getViewWithFocus();
                                            masterCamera = masterView->getCamera();
                                            eventState = masterView->getEventQueue()->getCurrentEventState();
                                            masterCameraVPW = masterCamera->getViewMatrix() * masterCamera->getProjectionMatrix();

                                            if (masterCamera->getViewport())
                                            {
                                                osg::Viewport* viewport = masterCamera->getViewport();
                                                masterCameraVPW *= viewport->computeWindowMatrix();
                                            }
                                        }

                                        // If this camera is not a slave camera
                                        if (camera->getView()->getCamera() == camera)
                                        {
                                            eventState->setGraphicsContext(gw);
                                            eventState->setInputRange( viewport->x(), viewport->y(),
                                                                    viewport->x()+viewport->width(),
                                                                    viewport->y()+viewport->height());

                                        }
                                        else
                                        {
                                            eventState->setInputRange(-1.0, -1.0, 1.0, 1.0);
                                        }
                                    }
                                }
                            }
                        }

                        break;
                    }
                    default:
                        break;
                }

                if (pointerEvent)
                {
                    if (getCameraWithFocus())
                    {
                        osg::Viewport* viewport = getCameraWithFocus()->getViewport();
                        osg::Matrix localCameraVPW = getCameraWithFocus()->getViewMatrix() * getCameraWithFocus()->getProjectionMatrix();
                        if (viewport) localCameraVPW *= viewport->computeWindowMatrix();

                        osg::Matrix matrix( osg::Matrix::inverse(localCameraVPW) * masterCameraVPW );

                        osg::Vec3d new_coord = osg::Vec3d(x,y,0.0) * matrix;

                        x = new_coord.x();
                        y = new_coord.y();

                        event->setInputRange(eventState->getXmin(), eventState->getYmin(), eventState->getXmax(), eventState->getYmax());
                        event->setX(x);
                        event->setY(y);
                        event->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);

                    }
                    // pass along the new pointer events details to the eventState of the viewer
                    eventState->setX(x);
                    eventState->setY(y);
                    eventState->setButtonMask(event->getButtonMask());
                    eventState->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);

                }
                else
                {
                    event->setInputRange(eventState->getXmin(), eventState->getYmin(), eventState->getXmax(), eventState->getYmax());
                    event->setX(eventState->getX());
                    event->setY(eventState->getY());
                    event->setButtonMask(eventState->getButtonMask());
                    event->setMouseYOrientation(eventState->getMouseYOrientation());
                }
            }

            for(itr = gw_events.begin();
                itr != gw_events.end();
                ++itr)
            {
                osgGA::GUIEventAdapter* event = itr->get();
                switch(event->getEventType())
                {
                    case(osgGA::GUIEventAdapter::CLOSE_WINDOW):
                    {
                        bool wasThreading = areThreadsRunning();
                        if (wasThreading) stopThreading();

                        gw->close();

                        if (wasThreading) startThreading();

                        break;
                    }
                    default:
                        break;
                }
            }

            viewEventsMap[masterView].insert( viewEventsMap[masterView].end(), gw_events.begin(), gw_events.end() );

        }
    }


    // OSG_NOTICE<<"mouseEventState Xmin = "<<eventState->getXmin()<<" Ymin="<<eventState->getYmin()<<" xMax="<<eventState->getXmax()<<" Ymax="<<eventState->getYmax()<<std::endl;


    for(RefViews::iterator vitr = _views.begin();
        vitr != _views.end();
        ++vitr)
    {
        View* view = vitr->get();
        view->getEventQueue()->frame( getFrameStamp()->getReferenceTime() );
        view->getEventQueue()->takeEvents(viewEventsMap[view]);
    }


    // OSG_NOTICE<<"Events "<<events.size()<<std::endl;

    if ((_keyEventSetsDone!=0) || _quitEventSetsDone)
    {
        for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
            veitr != viewEventsMap.end();
            ++veitr)
        {
            for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                itr != veitr->second.end();
                ++itr)
            {
                osgGA::GUIEventAdapter* event = itr->get();
                switch(event->getEventType())
                {
                    case(osgGA::GUIEventAdapter::KEYUP):
                        if (_keyEventSetsDone && event->getKey()==_keyEventSetsDone) _done = true;
                        break;

                    case(osgGA::GUIEventAdapter::QUIT_APPLICATION):
                        if (_quitEventSetsDone) _done = true;
                        break;

                    default:
                        break;
                }
            }
        }
    }

    if (_done) return;

    if (_eventVisitor.valid())
    {
        _eventVisitor->setFrameStamp(getFrameStamp());
        _eventVisitor->setTraversalNumber(getFrameStamp()->getFrameNumber());

        for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
            veitr != viewEventsMap.end();
            ++veitr)
        {
            View* view = veitr->first;
            _eventVisitor->setActionAdapter(view);

            if (view->getSceneData())
            {
                for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                    itr != veitr->second.end();
                    ++itr)
                {
                    osgGA::GUIEventAdapter* event = itr->get();

                    _eventVisitor->reset();
                    _eventVisitor->addEvent( event );

                    view->getSceneData()->accept(*_eventVisitor);

                    // Do EventTraversal for slaves with their own subgraph
                    for(unsigned int i=0; i<view->getNumSlaves(); ++i)
                    {
                        osg::View::Slave& slave = view->getSlave(i);
                        osg::Camera* camera = slave._camera.get();
                        if(camera && !slave._useMastersSceneData)
                        {
                            camera->accept(*_eventVisitor);
                        }
                    }

                    // call any camera event callbacks, but only traverse that callback, don't traverse its subgraph
                    // leave that to the scene update traversal.
                    osg::NodeVisitor::TraversalMode tm = _eventVisitor->getTraversalMode();
                    _eventVisitor->setTraversalMode(osg::NodeVisitor::TRAVERSE_NONE);

                    if (view->getCamera() && view->getCamera()->getEventCallback()) view->getCamera()->accept(*_eventVisitor);

                    for(unsigned int i=0; i<view->getNumSlaves(); ++i)
                    {
                        osg::View::Slave& slave = view->getSlave(i);
                        osg::Camera* camera = view->getSlave(i)._camera.get();
                        if (camera && slave._useMastersSceneData && camera->getEventCallback())
                        {
                            camera->accept(*_eventVisitor);
                        }
                    }

                    _eventVisitor->setTraversalMode(tm);

                }
            }
        }

    }

    for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
        veitr != viewEventsMap.end();
        ++veitr)
    {
        View* view = veitr->first;

        for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
            itr != veitr->second.end();
            ++itr)
        {
            osgGA::GUIEventAdapter* event = itr->get();

            for(View::EventHandlers::iterator hitr = view->getEventHandlers().begin();
                hitr != view->getEventHandlers().end();
                ++hitr)
            {
                (*hitr)->handleWithCheckAgainstIgnoreHandledEventsMask( *event, *view, 0, 0);
            }
        }
    }

    for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
        veitr != viewEventsMap.end();
        ++veitr)
    {
        View* view = veitr->first;

        for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
            itr != veitr->second.end();
            ++itr)
        {
            osgGA::GUIEventAdapter* event = itr->get();

            if (view->getCameraManipulator())
            {
                view->getCameraManipulator()->handleWithCheckAgainstIgnoreHandledEventsMask( *event, *view);
            }
        }
    }



    if (getViewerStats() && getViewerStats()->collectStats("event"))
    {
        double endEventTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

        // update current frames stats
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal begin time", beginEventTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal end time", endEventTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal time taken", endEventTraversal-beginEventTraversal);
    }
}
Exemplo n.º 15
0
void CompositeViewer::updateTraversal()
{
    if (_done) return;

    double beginUpdateTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

    _updateVisitor->reset();
    _updateVisitor->setFrameStamp(getFrameStamp());
    _updateVisitor->setTraversalNumber(getFrameStamp()->getFrameNumber());

    Scenes scenes;
    getScenes(scenes);
    for(Scenes::iterator sitr = scenes.begin();
            sitr != scenes.end();
            ++sitr)
    {
        Scene* scene = *sitr;
        if (scene->getSceneData())
        {
            _updateVisitor->setImageRequestHandler(scene->getImagePager());

            scene->getSceneData()->accept(*_updateVisitor);
        }

        if (scene->getDatabasePager())
        {
            // synchronize changes required by the DatabasePager thread to the scene graph
            scene->getDatabasePager()->updateSceneGraph(*_frameStamp);
        }

        if (scene->getImagePager())
        {
            // synchronize changes required by the DatabasePager thread to the scene graph
            scene->getImagePager()->updateSceneGraph(*_frameStamp);
        }

    }

    if (_updateOperations.valid())
    {
        _updateOperations->runOperations(this);
    }

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        View* view = vitr->get();

        Scene* scene = view->getScene();

        {
            // call any camera update callbacks, but only traverse that callback, don't traverse its subgraph
            // leave that to the scene update traversal.
            osg::NodeVisitor::TraversalMode tm = _updateVisitor->getTraversalMode();
            _updateVisitor->setTraversalMode(osg::NodeVisitor::TRAVERSE_NONE);

            if (view->getCamera() && view->getCamera()->getUpdateCallback()) view->getCamera()->accept(*_updateVisitor);

            for(unsigned int i=0; i<view->getNumSlaves(); ++i)
            {
                osg::Camera* camera = view->getSlave(i)._camera.get();
                if (camera && camera->getUpdateCallback()) camera->accept(*_updateVisitor);
            }

            _updateVisitor->setTraversalMode(tm);
        }


        if (view->getCameraManipulator())
        {
            view->setFusionDistance( view->getCameraManipulator()->getFusionDistanceMode(),
                                     view->getCameraManipulator()->getFusionDistanceValue() );

            view->getCamera()->setViewMatrix( view->getCameraManipulator()->getInverseMatrix());
        }
        view->updateSlaves();

    }

    if (getStats() && getStats()->collectStats("update"))
    {
        double endUpdateTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

        // update current frames stats
        getStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal begin time", beginUpdateTraversal);
        getStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal end time", endUpdateTraversal);
        getStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal time taken", endUpdateTraversal-beginUpdateTraversal);
    }

}
void CompositeViewer::eventTraversal()
{
    if (_done) return;

    if (_views.empty()) return;

    double cutOffTime = _frameStamp->getReferenceTime();

    double beginEventTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

    // need to copy events from the GraphicsWindow's into local EventQueue for each view;
    typedef std::map<osgViewer::View*, osgGA::EventQueue::Events> ViewEventsMap;
    ViewEventsMap viewEventsMap;

    Contexts contexts;
    getContexts(contexts);

    // set done if there are no windows
    checkWindowStatus(contexts);
    if (_done) return;

    osgGA::EventQueue::Events all_events;

    for(Contexts::iterator citr = contexts.begin();
            citr != contexts.end();
            ++citr)
    {
        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(*citr);
        if (gw)
        {
            gw->checkEvents();

            osgGA::EventQueue::Events gw_events;
            gw->getEventQueue()->takeEvents(gw_events, cutOffTime);

            for(osgGA::EventQueue::Events::iterator itr = gw_events.begin();
                    itr != gw_events.end();
                    ++itr)
            {
                (*itr)->setGraphicsContext(gw);
            }

            all_events.insert(all_events.end(), gw_events.begin(), gw_events.end());
        }
    }

    // sort all the events in time order so we can make sure we pass them all on in the correct order.
    all_events.sort(SortEvents());

    // pass on pointer data onto non mouse events to keep the position data usable by all recipients of all events.
    for(osgGA::EventQueue::Events::iterator itr = all_events.begin();
            itr != all_events.end();
            ++itr)
    {
        osgGA::GUIEventAdapter* event = itr->get();

        switch(event->getEventType())
        {
        case(osgGA::GUIEventAdapter::PUSH):
        case(osgGA::GUIEventAdapter::RELEASE):
        case(osgGA::GUIEventAdapter::DOUBLECLICK):
        case(osgGA::GUIEventAdapter::MOVE):
        case(osgGA::GUIEventAdapter::DRAG):
        {
            if ((event->getEventType()!=osgGA::GUIEventAdapter::DRAG && event->getEventType()!=osgGA::GUIEventAdapter::RELEASE) ||
                    !_previousEvent ||
                    _previousEvent->getGraphicsContext()!=event->getGraphicsContext() ||
                    _previousEvent->getNumPointerData()<2)
            {
                generatePointerData(*event);
            }
            else
            {
                reprojectPointerData(*_previousEvent, *event);
            }

#if 0
            // assign topmost PointeData settings as the events X,Y and InputRange
            osgGA::PointerData* pd = event->getPointerData(event->getNumPointerData()-1);
            event->setX(pd->x);
            event->setY(pd->y);
            event->setInputRange(pd->xMin, pd->yMin, pd->xMax, pd->yMax);
            event->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
#else
            if (event->getMouseYOrientation()!=osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS)
            {
                event->setY((event->getYmax()-event->getY())+event->getYmin());
                event->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
            }
#endif

            _previousEvent = event;

            break;
        }
        default:
            if (_previousEvent.valid()) event->copyPointerDataFrom(*_previousEvent);
            break;
        }

        osgGA::PointerData* pd = event->getNumPointerData()>0 ? event->getPointerData(event->getNumPointerData()-1) : 0;
        osg::Camera* camera = pd ? dynamic_cast<osg::Camera*>(pd->object.get()) : 0;
        osgViewer::View* view = camera ? dynamic_cast<osgViewer::View*>(camera->getView()) : 0;

        if (!view)
        {
            if (_viewWithFocus.valid())
            {
                // OSG_NOTICE<<"Falling back to using _viewWithFocus"<<std::endl;
                view = _viewWithFocus.get();
            }
            else if (!_views.empty())
            {
                // OSG_NOTICE<<"Falling back to using first view as one with focus"<<std::endl;
                view = _views[0].get();
            }
        }

        // reassign view with focus
        if (_viewWithFocus != view)  _viewWithFocus = view;

        if (view)
        {
            viewEventsMap[view].push_back( event );

            osgGA::GUIEventAdapter* eventState = view->getEventQueue()->getCurrentEventState();
            eventState->copyPointerDataFrom(*event);
        }

        _previousEvent = event;
    }

    // handle any close windows
    for(osgGA::EventQueue::Events::iterator itr = all_events.begin();
            itr != all_events.end();
            ++itr)
    {
        osgGA::GUIEventAdapter* event = itr->get();
        switch(event->getEventType())
        {
        case(osgGA::GUIEventAdapter::CLOSE_WINDOW):
        {
            bool wasThreading = areThreadsRunning();
            if (wasThreading) stopThreading();

            if (event->getGraphicsContext())
            {
                event->getGraphicsContext()->close();
            }

            if (wasThreading) startThreading();

            break;
        }
        default:
            break;
        }
    }


    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        View* view = vitr->get();

        // get events from user Devices attached to Viewer.
        for(osgViewer::View::Devices::iterator eitr = view->getDevices().begin();
                eitr != view->getDevices().end();
                ++eitr)
        {
            osgGA::Device* es = eitr->get();
            if (es->getCapabilities() & osgGA::Device::RECEIVE_EVENTS)
                es->checkEvents();

            // open question, will we need to reproject mouse coordinates into current view's coordinate frame as is down for GraphicsWindow provided events?
            // for now assume now and just get the events directly without any reprojection.
            es->getEventQueue()->takeEvents(viewEventsMap[view], cutOffTime);
        }

        // generate frame event
        view->getEventQueue()->frame( getFrameStamp()->getReferenceTime() );

        view->getEventQueue()->takeEvents(viewEventsMap[view], cutOffTime);
    }

    if ((_keyEventSetsDone!=0) || _quitEventSetsDone)
    {
        for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
                veitr != viewEventsMap.end();
                ++veitr)
        {
            for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                    itr != veitr->second.end();
                    ++itr)
            {
                osgGA::GUIEventAdapter* event = itr->get();
                switch(event->getEventType())
                {
                case(osgGA::GUIEventAdapter::KEYUP):
                    if (_keyEventSetsDone && event->getKey()==_keyEventSetsDone) _done = true;
                    break;

                case(osgGA::GUIEventAdapter::QUIT_APPLICATION):
                    if (_quitEventSetsDone) _done = true;
                    break;

                default:
                    break;
                }
            }
        }
    }

    if (_done) return;

    if (_eventVisitor.valid())
    {
        _eventVisitor->setFrameStamp(getFrameStamp());
        _eventVisitor->setTraversalNumber(getFrameStamp()->getFrameNumber());

        for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
                veitr != viewEventsMap.end();
                ++veitr)
        {
            View* view = veitr->first;

            if (view && view->getSceneData())
            {
                _eventVisitor->setActionAdapter(view);

                for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                        itr != veitr->second.end();
                        ++itr)
                {
                    osgGA::GUIEventAdapter* event = itr->get();

                    _eventVisitor->reset();
                    _eventVisitor->addEvent( event );

                    view->getSceneData()->accept(*_eventVisitor);

                    // Do EventTraversal for slaves with their own subgraph
                    for(unsigned int i=0; i<view->getNumSlaves(); ++i)
                    {
                        osg::View::Slave& slave = view->getSlave(i);
                        osg::Camera* camera = slave._camera.get();
                        if(camera && !slave._useMastersSceneData)
                        {
                            camera->accept(*_eventVisitor);
                        }
                    }

                    // call any camera event callbacks, but only traverse that callback, don't traverse its subgraph
                    // leave that to the scene update traversal.
                    osg::NodeVisitor::TraversalMode tm = _eventVisitor->getTraversalMode();
                    _eventVisitor->setTraversalMode(osg::NodeVisitor::TRAVERSE_NONE);

                    if (view->getCamera() && view->getCamera()->getEventCallback()) view->getCamera()->accept(*_eventVisitor);

                    for(unsigned int i=0; i<view->getNumSlaves(); ++i)
                    {
                        osg::View::Slave& slave = view->getSlave(i);
                        osg::Camera* camera = view->getSlave(i)._camera.get();
                        if (camera && slave._useMastersSceneData && camera->getEventCallback())
                        {
                            camera->accept(*_eventVisitor);
                        }
                    }

                    _eventVisitor->setTraversalMode(tm);

                }
            }
        }

    }

    for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
            veitr != viewEventsMap.end();
            ++veitr)
    {
        View* view = veitr->first;

        for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                itr != veitr->second.end();
                ++itr)
        {
            osgGA::GUIEventAdapter* event = itr->get();

            for(View::EventHandlers::iterator hitr = view->getEventHandlers().begin();
                    hitr != view->getEventHandlers().end();
                    ++hitr)
            {
                (*hitr)->handleWithCheckAgainstIgnoreHandledEventsMask( *event, *view, 0, _eventVisitor.get());
            }
        }
    }

    for(ViewEventsMap::iterator veitr = viewEventsMap.begin();
            veitr != viewEventsMap.end();
            ++veitr)
    {
        View* view = veitr->first;

        for(osgGA::EventQueue::Events::iterator itr = veitr->second.begin();
                itr != veitr->second.end();
                ++itr)
        {
            osgGA::GUIEventAdapter* event = itr->get();

            if (view->getCameraManipulator())
            {
                view->getCameraManipulator()->handleWithCheckAgainstIgnoreHandledEventsMask( *event, *view);
            }
        }
    }

    if (getViewerStats() && getViewerStats()->collectStats("event"))
    {
        double endEventTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

        // update current frames stats
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal begin time", beginEventTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal end time", endEventTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Event traversal time taken", endEventTraversal-beginEventTraversal);
    }
}
void CompositeViewer::updateTraversal()
{
    if (_done) return;

    double beginUpdateTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

    _updateVisitor->reset();
    _updateVisitor->setFrameStamp(getFrameStamp());
    _updateVisitor->setTraversalNumber(getFrameStamp()->getFrameNumber());

    Scenes scenes;
    getScenes(scenes);
    for(Scenes::iterator sitr = scenes.begin();
            sitr != scenes.end();
            ++sitr)
    {
        Scene* scene = *sitr;
        scene->updateSceneGraph(*_updateVisitor);
    }

    // if we have a shared state manager prune any unused entries
    if (osgDB::Registry::instance()->getSharedStateManager())
        osgDB::Registry::instance()->getSharedStateManager()->prune();

    // update the Registry object cache.
    osgDB::Registry::instance()->updateTimeStampOfObjectsInCacheWithExternalReferences(*getFrameStamp());
    osgDB::Registry::instance()->removeExpiredObjectsInCache(*getFrameStamp());


    if (_incrementalCompileOperation.valid())
    {
        // merge subgraphs that have been compiled by the incremental compiler operation.
        _incrementalCompileOperation->mergeCompiledSubgraphs(getFrameStamp());
    }

    if (_updateOperations.valid())
    {
        _updateOperations->runOperations(this);
    }

    for(RefViews::iterator vitr = _views.begin();
            vitr != _views.end();
            ++vitr)
    {
        View* view = vitr->get();

        {
            // Do UpdateTraversal for slaves with their own subgraph
            for(unsigned int i=0; i<view->getNumSlaves(); ++i)
            {
                osg::View::Slave& slave = view->getSlave(i);
                osg::Camera* camera = slave._camera.get();
                if(camera && !slave._useMastersSceneData)
                {
                    camera->accept(*_updateVisitor);
                }
            }

            // call any camera update callbacks, but only traverse that callback, don't traverse its subgraph
            // leave that to the scene update traversal.
            osg::NodeVisitor::TraversalMode tm = _updateVisitor->getTraversalMode();
            _updateVisitor->setTraversalMode(osg::NodeVisitor::TRAVERSE_NONE);

            if (view->getCamera() && view->getCamera()->getUpdateCallback()) view->getCamera()->accept(*_updateVisitor);

            for(unsigned int i=0; i<view->getNumSlaves(); ++i)
            {
                osg::View::Slave& slave = view->getSlave(i);
                osg::Camera* camera = slave._camera.get();
                if (camera && slave._useMastersSceneData && camera->getUpdateCallback())
                {
                    camera->accept(*_updateVisitor);
                }
            }

            _updateVisitor->setTraversalMode(tm);
        }


        if (view->getCameraManipulator())
        {
            view->setFusionDistance( view->getCameraManipulator()->getFusionDistanceMode(),
                                     view->getCameraManipulator()->getFusionDistanceValue() );

            view->getCameraManipulator()->updateCamera(*(view->getCamera()));

        }
        view->updateSlaves();

    }

    if (getViewerStats() && getViewerStats()->collectStats("update"))
    {
        double endUpdateTraversal = osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick());

        // update current frames stats
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal begin time", beginUpdateTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal end time", endUpdateTraversal);
        getViewerStats()->setAttribute(_frameStamp->getFrameNumber(), "Update traversal time taken", endUpdateTraversal-beginUpdateTraversal);
    }

}