WQtGLWidget.cpp 17.9 KB
Newer Older
wiebel's avatar
wiebel committed
1 2
//---------------------------------------------------------------------------
//
3
// Project: OpenWalnut ( http://www.openwalnut.org )
wiebel's avatar
wiebel committed
4
//
5 6
// Copyright 2009 OpenWalnut Community, BSV@Uni-Leipzig and CNCF@MPI-CBS
// For more information see http://www.openwalnut.org/copying
wiebel's avatar
wiebel committed
7
//
wiebel's avatar
wiebel committed
8
// This file is part of OpenWalnut.
wiebel's avatar
wiebel committed
9
//
wiebel's avatar
wiebel committed
10
// OpenWalnut is free software: you can redistribute it and/or modify
wiebel's avatar
wiebel committed
11 12 13 14
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
wiebel's avatar
wiebel committed
15
// OpenWalnut is distributed in the hope that it will be useful,
wiebel's avatar
wiebel committed
16 17 18 19 20
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
wiebel's avatar
wiebel committed
21
// along with OpenWalnut. If not, see <http://www.gnu.org/licenses/>.
wiebel's avatar
wiebel committed
22
//
wiebel's avatar
wiebel committed
23 24
//---------------------------------------------------------------------------

25 26 27
#include <string>
#include <iostream>

28
#include <QtGui/QApplication>
29
#include <QtGui/QColorDialog>
30 31 32
#include <QtGui/QFileDialog>
#include <QtGui/QKeyEvent>
#include <QtGui/QPixmap>
33

34
#include "WQtGLWidget.h"
35
#include "WQtGLWidget.moc"
36 37 38 39

#include "core/common/WConditionOneShot.h"
#include "core/common/WFlag.h"
#include "core/common/WLogger.h"
40
#include "core/common/WColor.h"
41
#include "core/graphicsEngine/WGE2DManipulator.h"
42
#include "core/graphicsEngine/WGENoOpManipulator.h"
43 44 45
#include "core/graphicsEngine/WGEViewer.h"
#include "core/graphicsEngine/WGEZoomTrackballManipulator.h"
#include "core/graphicsEngine/WGraphicsEngine.h"
46
#include "core/graphicsEngine/WGraphicsEngineMode.h"
47 48
#include "core/kernel/WKernel.h"

49
#include "WQt4Gui.h"
50
#include "WQtGLScreenCapture.h"
51 52
#include "events/WRenderedFrameEvent.h"
#include "events/WEventTypes.h"
53
#include "WSettingAction.h"
54 55
#include "WMainWindow.h"

56
#ifdef WGEMODE_MULTITHREADED
57 58 59
    #ifndef _WIN32
        #include <osgViewer/api/X11/GraphicsWindowX11>
        typedef osgViewer::GraphicsWindowX11::WindowData WindowData;
Sebastian Eichelbaum's avatar
[STYLE]  
Sebastian Eichelbaum committed
60 61 62 63
    #else
        #include <osgViewer/api/Win32/GraphicsWindowWin32>
        typedef osgViewer::GraphicsWindowWin32::WindowData WindowData;
    #endif
64 65
#endif

66
#ifndef _WIN32
Sebastian Eichelbaum's avatar
[STYLE]  
Sebastian Eichelbaum committed
67 68
WQtGLWidget::WQtGLWidget( std::string nameOfViewer, QWidget* parent, WGECamera::ProjectionMode projectionMode, const QWidget* shareWidget ):
    QGLWidget( getDefaultFormat(), parent, dynamic_cast< const QGLWidget* >( shareWidget ) ),
69
#else
Sebastian Eichelbaum's avatar
[STYLE]  
Sebastian Eichelbaum committed
70 71
WQtGLWidget::WQtGLWidget( std::string nameOfViewer, QWidget* parent, WGECamera::ProjectionMode projectionMode, const QWidget* ):
    QWidget( parent ),
72 73
#endif
      m_nameOfViewer( nameOfViewer ),
74 75
      m_recommendedSize(),
      m_firstPaint( true )
76 77 78 79 80 81 82 83 84 85 86 87
{
    m_recommendedSize.setWidth( 200 );
    m_recommendedSize.setHeight( 200 );

    m_initialProjectionMode = projectionMode;

    // required
    setAttribute( Qt::WA_PaintOnScreen );
    setAttribute( Qt::WA_NoSystemBackground );
    setFocusPolicy( Qt::ClickFocus );

    // initialize OpenGL context and OpenSceneGraph
88
#ifdef WGEMODE_MULTITHREADED
89 90 91 92 93 94
    osg::ref_ptr<osg::Referenced> wdata = new WindowData( winId() );

    // create viewer
    m_Viewer = WKernel::getRunningKernel()->getGraphicsEngine()->createViewer(
        m_nameOfViewer, wdata, x(), y(), width(), height(), m_initialProjectionMode );
#else
95 96
    osg::ref_ptr<osg::Referenced> wdata; // NULL pointer since not used on Mac

97 98
    // create viewer
    m_Viewer = WKernel::getRunningKernel()->getGraphicsEngine()->createViewer(
99
        m_nameOfViewer, wdata, x(), y(), width(), height(), m_initialProjectionMode );
100 101 102 103

    connect( &m_Timer, SIGNAL( timeout() ), this, SLOT( updateGL() ) );
    m_Timer.start( 10 );
#endif
104

105 106
    m_Viewer->isFrameRendered()->getCondition()->subscribeSignal( boost::bind( &WQtGLWidget::notifyFirstRenderedFrame, this ) );

107
    // set bg color
108 109
    updateViewerBackground();
    // this action manages the above settings
110
    m_changeBGColorAction = new QAction( WQt4Gui::getIconManager()->getIcon( "colorwheel" ), "Change Background Color", parent );
111
    connect( m_changeBGColorAction, SIGNAL( triggered( bool ) ), this, SLOT( changeBGColor() ) );
Sebastian Eichelbaum's avatar
[MERGE]  
Sebastian Eichelbaum committed
112

113
    // enable throwing of wanted
114 115
    m_allowThrowSetting = new WSettingAction( parent, std::string( "qt4gui/" ) + nameOfViewer + std::string( "/allowThrow" ),
                                                      "Camera Throwing",
Sebastian Eichelbaum's avatar
[STYLE]  
Sebastian Eichelbaum committed
116 117
                                                      "If enabled, the camera can be thrown. Try it by dragging the camera. "
                                                      "The camera then continues the movement.",
118 119 120
                                                      false );
    connect( m_allowThrowSetting, SIGNAL( change( bool ) ), this, SLOT( updateThrowing() ) );
    updateThrowing();
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

    // a separate menu for some presets
    m_cameraPresetMenu = new QMenu( "Camera Presets" );
    // NOTE: the shortcuts for these view presets should be chosen carefully. Most keysequences have another meaning in the most applications
    // so the user may get confused. It is also not a good idea to take letters as they might be used by OpenSceneGraph widget ( like "S" for
    // statistics ).
    // By additionally adding the action to the main window, we ensure the action can be triggered even if the menu bar is hidden.
    QAction* tmpAction = m_cameraPresetMenu->addAction( WQt4Gui::getIconManager()->getIcon( "sagittal icon" ), "Left", this, SLOT( setPresetViewLeft() ),
                                             QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_L ) );
    tmpAction->setIconVisibleInMenu( true );
    tmpAction = m_cameraPresetMenu->addAction( WQt4Gui::getIconManager()->getIcon( "sagittal icon" ), "Right", this, SLOT( setPresetViewRight() ),
                                       QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_R ) );
    tmpAction->setIconVisibleInMenu( true );
    tmpAction = m_cameraPresetMenu->addAction( WQt4Gui::getIconManager()->getIcon( "axial icon" ), "Superior", this, SLOT( setPresetViewSuperior() ),
                                       QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_S ) );
    tmpAction->setIconVisibleInMenu( true );
    tmpAction = m_cameraPresetMenu->addAction( WQt4Gui::getIconManager()->getIcon( "axial icon" ), "Inferior", this, SLOT( setPresetViewInferior() ),
                                       QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) );
    tmpAction->setIconVisibleInMenu( true );
    tmpAction = m_cameraPresetMenu->addAction( WQt4Gui::getIconManager()->getIcon( "coronal icon" ), "Anterior", this, SLOT( setPresetViewAnterior() ),
                                       QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_A ) );
    tmpAction->setIconVisibleInMenu( true );
    tmpAction = m_cameraPresetMenu->addAction( WQt4Gui::getIconManager()->getIcon( "coronal icon" ), "Posterior", this, SLOT( setPresetViewPosterior() ),
                                       QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_P ) );
    tmpAction->setIconVisibleInMenu( true );
146 147 148 149

    m_cameraResetAction = new QAction( WQt4Gui::getIconManager()->getIcon( "view" ), "Reset", this );
    connect( m_cameraResetAction, SIGNAL(  triggered( bool ) ), this, SLOT( reset() ) );
    m_cameraResetAction->setToolTip( "Reset view" );
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
}

WQtGLWidget::~WQtGLWidget()
{
    WKernel::getRunningKernel()->getGraphicsEngine()->closeViewer( m_nameOfViewer );
    m_Viewer.reset();
}

QSize WQtGLWidget::sizeHint() const
{
    return m_recommendedSize;
}

void WQtGLWidget::setCameraManipulator( WQtGLWidget::CameraManipulators manipulator )
{
    m_CurrentManipulator = manipulator;
166
    switch( manipulator )
167 168 169 170 171 172 173 174
    {
        case TWO_D:
            WLogger::getLogger()->addLogMessage( "Switched to OSG manipulator \"WGE2D\".",
                                                 "WQtGLWidget(" + m_Viewer->getName() + ")",
                                                 LL_DEBUG );

            m_Viewer->setCameraManipulator( new( WGE2DManipulator ) );
            break;
175 176 177 178 179 180 181
        case NO_OP:
            WLogger::getLogger()->addLogMessage( "Switched to OSG manipulator \"WGENoOp\".",
                                                 "WQtGLWidget(" + m_Viewer->getName() + ")",
                                                 LL_DEBUG );

            m_Viewer->setCameraManipulator( new( WGENoOpManipulator ) );
            break;
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        case TRACKBALL:
        default:
            WLogger::getLogger()->addLogMessage( "Switched to OSG manipulator \"WGETrackball\".",
                                                 "WQtGLWidget(" + m_Viewer->getName() + ")",
                                                 LL_DEBUG );

            m_Viewer->setCameraManipulator( new( WGEZoomTrackballManipulator ) );
            break;
    }
}

WQtGLWidget::CameraManipulators WQtGLWidget::getCameraManipulators()
{
    return m_CurrentManipulator;
}

boost::shared_ptr< WGEViewer > WQtGLWidget::getViewer() const
{
    return m_Viewer;
}

void WQtGLWidget::paintEvent( QPaintEvent* /*event*/ )
{
205
    if( m_firstPaint )
206 207 208 209 210 211
    {
        // it is important to let the GE know that there now is an completely initialized widget -> allowing GE startup to complete
        // This is needed as on some machines, the OSG crashes if the GL widget is not fully initialized.
        m_firstPaint = false;
        WKernel::getRunningKernel()->getGraphicsEngine()->finalizeStartup();
    }
212 213
}

214
#ifdef WGEMODE_SINGLETHREADED
215 216 217 218 219 220

void WQtGLWidget::paintGL()
{
    m_Viewer->paint();
}

221
void WQtGLWidget::resizeEvent( QResizeEvent* event )
222
{
223 224 225
    // we must hand over the event to our base class because that one takes care
    // that resizeGL is eventually called
    WQtGLWidgetParent::resizeEvent( event );
226 227 228 229 230 231 232 233 234 235 236 237
}

void WQtGLWidget::resizeGL( int width, int height )
{
    m_Viewer->resize( width, height );
}

#else

void WQtGLWidget::paintGL()
{
    // m_Viewer->paint();
238 239
#ifdef IS_A_QGLWIDGET
    // if the parent is a GL widget, issue parent method.
240
    WQtGLWidgetParent::paintGL();
241
#endif
242 243 244 245 246
}

void WQtGLWidget::resizeEvent( QResizeEvent* event )
{
    m_Viewer->resize( event->size().width(), event->size().height() );
247 248

    WQtGLWidgetParent::resizeEvent( event );
249 250
}

251
void WQtGLWidget::resizeGL( int width, int height )
252 253
{
    // m_Viewer->resize( width, height );
254 255
#ifdef IS_A_QGLWIDGET
    // if the parent is a GL widget, issue parent method.
256
    WQtGLWidgetParent::resizeGL( width, height );
257
#endif
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
}
#endif

int WQtGLWidget::translateButton( QMouseEvent* event )
{
    switch( event->button() )
    {
        case( Qt::LeftButton ):
            return 1;
        case( Qt::MidButton ):
            return 2;
        case( Qt::RightButton ):
            return 3;
        default:
            return 0;
    }
}

void WQtGLWidget::keyPressEvent( QKeyEvent* event )
{
    if(  event->text() != "" )
    {
        m_Viewer->keyEvent( WGEViewer::KEYPRESS, *event->text().toAscii().data() );
    }
    else
    {
        switch( event->modifiers() )
        {
            case Qt::ShiftModifier :
                m_Viewer->keyEvent( WGEViewer::KEYPRESS, osgGA::GUIEventAdapter::KEY_Shift_L );
                break;
            case Qt::ControlModifier :
                m_Viewer->keyEvent( WGEViewer::KEYPRESS, osgGA::GUIEventAdapter::KEY_Control_L );
                break;
            default :
                break;
        }
    }
}

void WQtGLWidget::keyReleaseEvent( QKeyEvent* event )
{
    switch( event->key() )
    {
        case Qt::Key_Period:
            WGraphicsEngine::getGraphicsEngine()->requestShaderReload();
            break;
        case Qt::Key_1:
            setCameraManipulator( TRACKBALL );
            break;
        case Qt::Key_2:
            setCameraManipulator( TWO_D );
            break;
    }

    switch( event->modifiers() )
    {
        case Qt::ShiftModifier :
            m_Viewer->keyEvent( WGEViewer::KEYRELEASE, osgGA::GUIEventAdapter::KEY_Shift_L );
            break;
        case Qt::ControlModifier :
            m_Viewer->keyEvent( WGEViewer::KEYRELEASE, osgGA::GUIEventAdapter::KEY_Control_L );
            break;
    }

    m_Viewer->keyEvent( WGEViewer::KEYRELEASE, *event->text().toAscii().data() );
}


void WQtGLWidget::mousePressEvent( QMouseEvent* event )
{
    m_Viewer->mouseEvent( WGEViewer::MOUSEPRESS, event->x(), event->y(), translateButton( event ) );
}

void WQtGLWidget::mouseDoubleClickEvent( QMouseEvent* event )
{
    m_Viewer->mouseEvent( WGEViewer::MOUSEDOUBLECLICK, event->x(), event->y(), translateButton( event ) );
}

void WQtGLWidget::mouseReleaseEvent( QMouseEvent* event )
{
    m_Viewer->mouseEvent( WGEViewer::MOUSERELEASE, event->x(), event->y(), translateButton( event ) );
}

void WQtGLWidget::mouseMoveEvent( QMouseEvent* event )
{
    m_Viewer->mouseEvent( WGEViewer::MOUSEMOVE, event->x(), event->y(), 0 );
}

void WQtGLWidget::wheelEvent( QWheelEvent* event )
{
    int x, y;
    if( event->orientation() == Qt::Vertical )
    {
        x = 0;
        y = event->delta();
    }
    else
    {
        x = event->delta();
        y = 0;
    }
    m_Viewer->mouseEvent( WGEViewer::MOUSESCROLL, x, y, 0 );
}

363 364 365 366 367 368 369 370 371 372 373
bool WQtGLWidget::event( QEvent* event )
{
    if( event->type() == WQT_RENDERED_FRAME_EVENT )
    {
        emit renderedFirstFrame();
        return true;
    }

    return WQtGLWidgetParent::event( event );
}

374 375 376 377 378 379 380 381 382 383 384 385
void WQtGLWidget::reset()
{
    m_Viewer->reset();
}

const QGLFormat WQtGLWidget::getDefaultFormat()
{
    QGLFormat format;
    format.setSwapInterval( 1 );    // according to Qt Doc, this should enable VSync. But it doesn't.
    return format;
}

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
void WQtGLWidget::updateThrowing()
{
    WGEZoomTrackballManipulator* manipulator = dynamic_cast< WGEZoomTrackballManipulator* >( m_Viewer->getCameraManipulator().get() );
    if( manipulator )
    {
        manipulator->setThrow( m_allowThrowSetting->get() );
    }
}

WSettingAction* WQtGLWidget::getThrowingSetting() const
{
    return m_allowThrowSetting;
}

QAction* WQtGLWidget::getBackgroundColorAction() const
{
    return m_changeBGColorAction;
}

void WQtGLWidget::updateViewerBackground()
{
    QColor bg = WMainWindow::getSettings().value( QString( "qt4gui/" ) + QString::fromStdString( m_nameOfViewer ) + QString( "/BGColor" ),
                                                  QColor( 255, 255, 255, 255 ) ).value< QColor >();
    m_Viewer->setBgColor( WColor( bg.redF(), bg.greenF(), bg.blueF(), 1.0 ) );
}

void WQtGLWidget::changeBGColor()
{
    QColor bgOld = WMainWindow::getSettings().value( QString( "qt4gui/" ) + QString::fromStdString( m_nameOfViewer ) + QString( "/BGColor" ),
                                                  QColor( 255, 255, 255, 255 ) ).value< QColor >();
    QColor bg = QColorDialog::getColor( bgOld, this );
    WMainWindow::getSettings().setValue( QString( "qt4gui/" ) + QString::fromStdString( m_nameOfViewer ) + QString( "/BGColor" ), bg );

    updateViewerBackground();
}

422 423 424 425
void WQtGLWidget::notifyFirstRenderedFrame()
{
    QCoreApplication::postEvent( this, new WRenderedFrameEvent() );
}
426 427 428 429 430 431 432

WQtGLScreenCapture* WQtGLWidget::getScreenCapture( WMainWindow* parent ) const
{
    WQtGLScreenCapture* sc = new WQtGLScreenCapture( getViewer(), parent );
    return sc;
}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
void WQtGLWidget::setPresetViewLeft()
{
    osg::ref_ptr<osgGA::TrackballManipulator>  cm = osg::dynamic_pointer_cast<osgGA::TrackballManipulator>( m_Viewer->getCameraManipulator() );
    osg::Quat q( 0.5, -0.5, -0.5, 0.5 );
    // is it a trackball manipulator?
    if( cm )
    {
        cm->setRotation( q );
    }
    else
    {
        wlog::warn( "WQtGLWidget(" + m_Viewer->getName() + ")" ) << "GL Widget does not use a TrackballManipulator. Preset cannot be used.";
    }
}

void WQtGLWidget::setPresetViewRight()
{
    osg::ref_ptr<osgGA::TrackballManipulator>  cm = osg::dynamic_pointer_cast<osgGA::TrackballManipulator>( m_Viewer->getCameraManipulator() );
    osg::Quat q( -0.5, -0.5, -0.5, -0.5 );
    // is it a trackball manipulator?
    if( cm )
    {
        cm->setRotation( q );
    }
    else
    {
        wlog::warn( "WQtGLWidget(" + m_Viewer->getName() + ")" ) << "GL Widget does not use a TrackballManipulator. Preset cannot be used.";
    }
}

void WQtGLWidget::setPresetViewSuperior()
{
    osg::ref_ptr<osgGA::TrackballManipulator>  cm = osg::dynamic_pointer_cast<osgGA::TrackballManipulator>( m_Viewer->getCameraManipulator() );
    osg::Quat q( 0., 0., 0., 1 );
    // is it a trackball manipulator?
    if( cm )
    {
        cm->setRotation( q );
    }
    else
    {
        wlog::warn( "WQtGLWidget(" + m_Viewer->getName() + ")" ) << "GL Widget does not use a TrackballManipulator. Preset cannot be used.";
    }
}

void WQtGLWidget::setPresetViewInferior()
{
    osg::ref_ptr<osgGA::TrackballManipulator>  cm = osg::dynamic_pointer_cast<osgGA::TrackballManipulator>( m_Viewer->getCameraManipulator() );
    osg::Quat q( 0., -1., 0., 0. );
    // is it a trackball manipulator?
    if( cm )
    {
        cm->setRotation( q );
    }
    else
    {
        wlog::warn( "WQtGLWidget(" + m_Viewer->getName() + ")" ) << "GL Widget does not use a TrackballManipulator. Preset cannot be used.";
    }
}

void WQtGLWidget::setPresetViewAnterior()
{
    osg::ref_ptr<osgGA::TrackballManipulator>  cm = osg::dynamic_pointer_cast<osgGA::TrackballManipulator>( m_Viewer->getCameraManipulator() );
    osg::Quat q( 0., -0.707107, -0.707107, 0. );
    // is it a trackball manipulator?
    if( cm )
    {
        cm->setRotation( q );
    }
    else
    {
        wlog::warn( "WQtGLWidget(" + m_Viewer->getName() + ")" ) << "GL Widget does not use a TrackballManipulator. Preset cannot be used.";
    }
}

void WQtGLWidget::setPresetViewPosterior()
{
    osg::ref_ptr<osgGA::TrackballManipulator>  cm = osg::dynamic_pointer_cast<osgGA::TrackballManipulator>( m_Viewer->getCameraManipulator() );
    osg::Quat q( 0.707107, 0., 0., 0.707107 );
    // is it a trackball manipulator?
    if( cm )
    {
        cm->setRotation( q );
    }
    else
    {
        wlog::warn( "WQtGLWidget(" + m_Viewer->getName() + ")" ) << "GL Widget does not use a TrackballManipulator. Preset cannot be used.";
    }
}

QMenu* WQtGLWidget::getCameraPresetsMenu()
{
    return m_cameraPresetMenu;
}
527 528 529 530 531

QAction* WQtGLWidget::getCameraResetAction()
{
    return m_cameraResetAction;
}