Création d'un compte pour un collaborateur extérieur au laboratoire depuis l'intranet ICube : https://intranet.icube.unistra.fr/fr/labs/member/profile

GLViewer.cpp 77 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 *	(c) LSIIT, UMR CNRS/UdS
 *	Authors: O. Gnevaux, F. Larue.
 *
 *	See licence.txt for additional information.
 */


#include "GLViewer.h"

#include <fstream>
#include <iostream>
#include <sstream>
#include "InfoBarManager.h"

#include <SelectionManager.h>
#include <SelectionToolBox.h>
#include <SelectionToolDisk.h>
#include <SelectionToolLasso.h>




24
void GLViewer::DisplayableInfo::Initialize( DisplayableInterface *displayable,
25
                                            DisplayableList::iterator priorityPos,
26
27
28
29
30
31
32
33
34
35
36
37
                                            UIParamSet &params )
{
    this->displayable = displayable;
    this->posInPriorityList = priorityPos;

    displayable->initialize( params );

    displayable->transformation( this->userTransform );
    this->packingTransform.setToIdentity();
    this->fullTransform = this->userTransform * this->packingTransform;

    displayable->boundingBox( this->boundingBox );
38
39

    this->selectionMgr = displayable->selectionManager();
40
41
42
43
44
}




45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const char* GLViewer::s_PickingVPG =
    "#version 330\n"

    "uniform mat4 projectionMatrix;"
    "uniform mat4 viewMatrix;"

    "in vec3 vertexPosition;"

    "out float depth;"
    "out vec3 vertex;"

    "void main()"
    "{"
    "   depth  = length( (viewMatrix * vec4(vertexPosition,1.0)).xyz );"
    "   vertex = vertexPosition;"

    "   gl_Position = projectionMatrix * viewMatrix * vec4(vertexPosition,1.0);"
    "}";

const char* GLViewer::s_PickingFPG =
    "uniform int u_ObjectId;"

    "in float depth;"
    "in vec3 vertex;"

    "void main()"
    "{"
    "   gl_FragData[0].x = float( u_ObjectId      & 255) / 255.0;"
    "   gl_FragData[0].y = float((u_ObjectId>> 8) & 255) / 255.0;"
    "   gl_FragData[0].z = float((u_ObjectId>>16) & 255) / 255.0;"
    "   gl_FragData[0].w = float((u_ObjectId>>24) & 255) / 255.0;"
    "   gl_FragData[1] = vec4( vertex, depth );"
    "}";


const char* GLViewer::s_ZBufferVPG =
    "#version 330\n"

    "uniform mat4 fullTransformMatrix;"

    "in vec3 vertexPosition;"

    "void main()"
    "{"
    "   gl_Position = fullTransformMatrix * vec4(vertexPosition,1.0);"
    "}";

const char* GLViewer::s_ZBufferFPG =
    "void main()"
    "{"
    "   gl_FragData[0] = vec4( 0.0, 0.0, 0.0, 1.0 );"
    "}";


GLViewer::GLViewer( DisplayDoF dof,
                    QWidget *parent,
Frédéric Larue's avatar
Frédéric Larue committed
101
102
103
104
                    Qt::WindowFlags f ) :
    QOpenGLWidget( parent, f ),
    m_DisplayOptionsLayout( NULL ),
    m_InfoBarManager( NULL )
105
106
107
108
109
110
111
112
{
    init( dof );
}


GLViewer::GLViewer( DisplayDoF dof,
                    const QSurfaceFormat &format,
                    QWidget *parent,
Frédéric Larue's avatar
Frédéric Larue committed
113
114
115
116
                    Qt::WindowFlags f ) :
    QOpenGLWidget( parent, f ),
    m_DisplayOptionsLayout( NULL ),
    m_InfoBarManager( NULL )
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
{
	setFormat( format );
    init( dof );
}


GLViewer::~GLViewer()
{
    for( std::vector<SelectionTool*>::iterator tool=m_SelectionTools.begin(); tool!=m_SelectionTools.end(); ++tool )
        delete *tool;

	delete m_InfoBarManager;
}


void GLViewer::init( DisplayDoF dof )
{
134
135
136
    m_BelowCursor = NULL;


137
138
139
    m_MustUpdateFocal            = true;
    m_MustUpdateProjectionMatrix = true;
    m_MustUpdateViewMatrix       = true;
140

141
142
143
144
    m_SpeedFactor = 1.0;
    m_CtrlSpeedFactor = 4.0;
    m_ShiftSpeedFactor = 0.25;

145
    m_View.focusPoint = QVector3D(-1.0f,-1.0f,-1.0f);
146
    setFocusPoint( QVector3D(0.0f,0.0f,0.0f) );
147

148
    m_View.DoF = dof;
149
    QMatrix4x4 rot;
150
    if( dof == DISPLAY_DOF_2D )
151
        rot.setToIdentity();
152
153
    else
    {
154
155
        rot.rotate(  30.0f, 1,0,0 );
        rot.rotate( -30.0f, 0,1,0 );
156
    }
157
158
    setViewRotationMatrix( rot );

159
    m_View.fovY = 0.0f;
160
161
    setFovY( 65.0f );

162
	m_View.distToFocusPoint = 0.0f;
163
    setDistToFocusPoint( 400.0f );
164

165
166
    m_View.pointSize = 2;
	m_View.isCullingEnabled = false;
167

Frédéric Larue's avatar
Frédéric Larue committed
168
169
170
171
172
    if( !m_InfoBarManager )
    {
        m_InfoBarManager = new InfoBarManager( this );
        m_InfoBarManager->setInfoBar( new InfoBar(), InfoBar::BOTTOM );
    }
173

174
    m_View.isGridDisplayed = true;
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196


    // Initialize selection tools.

    m_SelectionEnabled = false;

    if( m_SelectionTools.empty() )
    {
        m_SelectionTools.resize( SELECTION_TOOL_END );
        m_SelectionTools[SELECTION_TOOL_BOX  ] = new SelectionToolBox  ( *this, m_SelectionContext );
        m_SelectionTools[SELECTION_TOOL_DISK ] = new SelectionToolDisk ( *this, m_SelectionContext );
        m_SelectionTools[SELECTION_TOOL_LASSO] = new SelectionToolLasso( *this, m_SelectionContext );
    }

    m_SelectionCurrentToolName = SELECTION_TOOL_DISK;
    m_SelectionCurrentTool = m_SelectionTools[ m_SelectionCurrentToolName ];



    m_MetricGrid.disableAxis( MetricGrid::ALL );
    m_MetricGrid.disableGrid( MetricGrid::ALL );

197
    m_View.lightRotationMatrix.setToIdentity();
198

199
200
201
    m_View.isLightTrackingEnabled = true;
    m_View.isLightingEnabled      = true;
    m_View.isWireframeEnabled     = false;
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226


    m_AnimationsRunningAtPreviousFrame = false;


    // Initialize the layout that will contains options for all active displayables.

    if( !m_DisplayOptionsLayout )
    {
        m_DisplayOptionsLayout = new QVBoxLayout();
        m_DisplayOptionsLayout->setAlignment( Qt::AlignTop );

        QWidget *w = new QWidget( this );
        w->setLayout( m_DisplayOptionsLayout );

        QGridLayout *viewerLayout = new QGridLayout();
        viewerLayout->setRowStretch( 1, 10 );
        viewerLayout->setColumnStretch( 0, 10 );
        viewerLayout->addWidget( w, 0,1 );

        this->setLayout( viewerLayout );
    }
}


227
228
229
230
231
232
233
234
235
236
237
238
void GLViewer::setRenderState( const RenderState& state )
{
    m_View = state;

    m_MustUpdateFocal            = true;
    m_MustUpdateProjectionMatrix = true;
    m_MustUpdateViewMatrix       = true;

    update();
}


239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
363
364
365
void GLViewer::populateDisplayerFactories( DisplayableFactoryInterface *plugin )
{
    const unsigned int NB_ROWS = 3;

    QVector<QString> types;
    plugin->acceptedDataTypes( types );

    for( auto &type : types )
        if( m_Factories.find(type) == m_Factories.end()  &&  (plugin->viewerDoF() & dof()) )
        {
            m_Factories[type] = plugin;

            QStringList primNames;
            plugin->primitiveNames( primNames );
            foreach( QString name, primNames )
            {
                if( !m_PrimitiveCountMap.contains(name) )
                {
                    PrimitiveInfo pInfo;
                    pInfo.count = 0;
                    pInfo.row = m_PrimitiveCountMap.size() % (NB_ROWS-1);

                    if( !pInfo.row )
                    {
                        pInfo.panel = new Panel(NB_ROWS,2,15,2);
                        pInfo.panel->setColAlignment( 0, Panel::LEFT );
                        pInfo.panel->setColAlignment( 1, Panel::RIGHT );
                        pInfo.panel->hideFrame();
                        pInfo.panel->setColMinWidth( 1, 30 );

                        for( unsigned int i=1; i<NB_ROWS; ++i )
                            pInfo.panel->set( new Label(" "), i,0 );

                        m_InfoBarManager->infoBar( InfoBar::BOTTOM )->append( pInfo.panel );
                    }
                    else
                        pInfo.panel = m_InfoBarManager->infoBar( InfoBar::BOTTOM )->panels().back();

                    pInfo.panel->set( new Label(name+":",QVector4D(1.0f,1.0f,1.0f,1.0f)), pInfo.row, 0 );
                    pInfo.panel->set( new Label("0",QVector4D(1.0f,1.0f,1.0f,1.0f))     , pInfo.row, 1 );

                    m_PrimitiveCountMap[ name ] = pInfo;
                }
            }
        }
}


void GLViewer::populateDisplayerFactories( QList<DisplayableFactoryInterface*> &plugins )
{
    foreach( DisplayableFactoryInterface *plugin, plugins )
        populateDisplayerFactories( plugin );
}


void GLViewer::updatePrimitiveCounts()
{
#if 0
    // Reset all primitive counts to zero.

    for( QMap<QString,PrimitiveInfo>::iterator prim=m_PrimitiveCountMap.begin(); prim!=m_PrimitiveCountMap.end(); ++prim )
        prim->count = 0;


    // Checks every displayable and update primitive counts accordingly.

    for( DisplayableMap::iterator d=m_Displayables.begin(); d!=m_Displayables.end(); ++d )
    {
        // Recovers the factory of the current displayable.
        FactoryMap::iterator factory = m_Factories.find( d->first->TypeString() );
        if( factory == m_Factories.end() )
            continue;

        // Updates the primitive counts.
        QStringList primNames;
        factory->second->primitiveNames( primNames );
        foreach( QString name, primNames )
            m_PrimitiveCountMap[ name ].count += d->second.displayable->primitiveCount( name );
    }


    // Updates the display of primitive counts in the viewer UI.

    for( QMap<QString,PrimitiveInfo>::iterator prim=m_PrimitiveCountMap.begin(); prim!=m_PrimitiveCountMap.end(); ++prim )
    {
        QString countStr;
        if( prim->count )
        {
            countStr = "";
            for( unsigned int c=prim->count; c; c/=1000 )
                countStr.prepend( c<1000? QString().setNum(c) : QString().sprintf(" %03i",c%1000) );
        }
        else
            countStr = "0";

        prim->panel->set( new Label(countStr), prim->row,1 );
        m_InfoBarManager->repackInfoBars();
    }
#endif
}


bool GLViewer::addDisplayable( GenericUIData *m )
{
    // If a displayable already exists for this manageable, remove it before creating a new one.
    removeDisplayable( m );

    // Recovers the displayable factory for the corresponding datatype.
    FactoryMap::iterator factory = m_Factories.find( m->GetTypeString() );
    if( factory == m_Factories.end() )
        return false;

    // Asks the factory to create a displayable of the correct type. It is then
    // initialized and inserted in the list of all displayables.
    DisplayableInterface *displayable = factory->second->newDisplayer( m, this );
    DisplayableInfo *dispInfo = NULL;

    if( displayable )
    {
        makeCurrent();

        if( !m->GetDisplayOptions() )
        {
            UIParamSet *params = new UIParamSet( m->GetBaseName() + " display options:", NULL );
            displayable->declareParameters( *params );

            if( displayable->isAnimated() )
366
                params->Add( new UIParamAnimation() );
367
368
369
370
371

            params->updateChildrenLists( m );

            m->SetDisplayOptions( params );
        }
372

373
374
375
376
377
        connect( m->GetDisplayOptions(), SIGNAL(parameterUpdated(UIParam*)), this, SLOT(update()) );
        connect( m->GetDisplayOptions(), SIGNAL(parameterUpdated(UIParam*)), displayable, SLOT(updateParameter(UIParam*)) );

        if( displayable->isAnimated() )
        {
378
            UIParamAnimation *animCtrl = m->GetDisplayOptions()->GetAnimationCtrl();
379
380
381
382
383
384
385
386
387
388
389
            connect( animCtrl, SIGNAL(animationStartRequired()), displayable, SLOT(startAnimation()) );
            connect( animCtrl, SIGNAL(animationPauseRequired()), displayable, SLOT(pauseAnimation()) );
            connect( animCtrl, SIGNAL(animationStopRequired ()), displayable, SLOT(stopAnimation ()) );
            connect( animCtrl, SIGNAL(animationStepForwardRequired ()), displayable, SLOT(animationStepForward ()) );
            connect( animCtrl, SIGNAL(animationStepBackwardRequired()), displayable, SLOT(animationStepBackward()) );

            connect( displayable, SIGNAL(registerAnimation  (DisplayableInterface*)), this, SLOT(registerAnimation  (DisplayableInterface*)) );
            connect( displayable, SIGNAL(unregisterAnimation(DisplayableInterface*)), this, SLOT(unregisterAnimation(DisplayableInterface*)) );
            connect( displayable, SIGNAL(displayNeedUpdate()), this, SLOT(update()) );
        }

390
391
392
393
394
395
396
397
        DisplayableList &priorityList = m_DisplayablesByPriority[ factory->second->displayPriority() ];

        dispInfo = &m_Displayables[ m ];
        dispInfo->Initialize(
            displayable,
            priorityList.insert( priorityList.end(), dispInfo ),
            *m->GetDisplayOptions()
        );
398

399
        if( !m->GetDisplayOptions()->IsEmpty() )
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
        {
            m_DisplayOptionsLayout->addWidget( m->GetDisplayOptions() );
            m->GetDisplayOptions()->show();
        }

        if( isSelectionEnabled()  &&  dispInfo->selectionMgr )
            dispInfo->selectionMgr->onRecompilingSelectionShader( m_SelectionCurrentTool );

        updatePrimitiveCounts();
        update();
    }


    if( dof() == DISPLAY_DOF_2D  &&  displayable )
    {
        m_AddingOrder.push_back( dispInfo );
        repackDisplayables();
        //frameAll();
    }


	return displayable != NULL;
}


425
426
427
428
429
430
//void GLViewer::setTransform( GenericUIData *m, const QMatrix4x4 &xf )
//{
//    DisplayableMap::iterator d = m_Displayables.find( m );
//    if( d != m_Displayables.end() )
//        d->second.packingTransform = xf;
//}
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445


void GLViewer::updateDisplayable( GenericUIData *m )
{
    DisplayableMap::iterator d = m_Displayables.find( m );
    if( d != m_Displayables.end() )
    {
        // Recovers the info and the factory related to the given manageable.
        DisplayableFactoryInterface *factory = m_Factories[ m->GetTypeString() ];
        DisplayableInfo *dinfo = &d->second;

        // Re-initializes the displayable.
        dinfo->displayable->release( *m->GetDisplayOptions() );
        dinfo->displayable->initialize( *m->GetDisplayOptions() );

Frédéric Larue's avatar
Frédéric Larue committed
446
        if( isSelectionEnabled()  &&  dinfo->selectionMgr )
447
448
449
450
451
452
453
454
455
456
457
458
459
            dinfo->selectionMgr->onRecompilingSelectionShader( m_SelectionCurrentTool );

        updatePrimitiveCounts();
        update();
    }
}


void GLViewer::frameBox( Box3f &box, const QMatrix4x4 *xf )
{
    if( !box.IsNull() )
    {
        double boxHalfDiag = box.Dimensions().length() * 0.5;
460
461
        double depth = ( 2.0*zFar()*zNear() - distToFocusPoint()*(zFar()+zNear()) ) / (zNear()-zFar());
        double projectedRadius = boxHalfDiag * focal() / depth;
462
463
464
465
466
467
468

        if( xf )
            setFocusPoint( xf->map(box.Center()) );
        else
            setFocusPoint( box.Center() );

        if( projectedRadius > 0.000001 )
469
            setDistToFocusPoint( distToFocusPoint() * (width()<height()? projectedRadius*height()/width() : projectedRadius) );
470
471
472
473
474
475
476
477
    }
}


void GLViewer::frameItem( GenericUIData* item )
{
    DisplayableMap::iterator dispInfo = m_Displayables.find( item );
    if( dispInfo != m_Displayables.end() )
478
        frameBox( dispInfo->second.boundingBox, &dispInfo->second.GetTransform() );
479
480
481
482
483
484
485
486
487
488
489
}


void GLViewer::frameItems( std::list<GenericUIData*> &items )
{
    Box3f box;

    for( auto m=items.begin(); m!=items.end(); ++m )
    {
        DisplayableMap::iterator dispInfo = m_Displayables.find( *m );
        if( dispInfo != m_Displayables.end() )
490
            if( !dispInfo->second.boundingBox.IsNull() )
491
492
            {
                Box3f::CornerSet objectBoxCorners;
493
                dispInfo->second.boundingBox.Corners( objectBoxCorners );
494
495

                for( auto c=objectBoxCorners.begin(); c!=objectBoxCorners.end(); ++c )
496
                    box.Add( dispInfo->second.GetTransform().map(*c) );
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
            }
    }

    frameBox( box );
}


void GLViewer::frameAll()
{
    if( !m_Displayables.empty() )
    {
        Box3f box;

        for( DisplayableMap::iterator dispInfo=m_Displayables.begin(); dispInfo!=m_Displayables.end(); ++dispInfo )
        {
            Box3f objectBox;
            dispInfo->second.displayable->boundingBox( objectBox );

            if( !objectBox.IsNull() )
            {
                Box3f::CornerSet objectBoxCorners;
                objectBox.Corners( objectBoxCorners );

                for( auto c=objectBoxCorners.begin(); c!=objectBoxCorners.end(); ++c )
521
                    box.Add( dispInfo->second.GetTransform().map(*c) );
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
            }
        }

        frameBox( box );
    }
}




// All displayables are arranged along a grid layout. All grid row have the same height (displayables are scaled so as to fit it)
// but each column has a different width, that corresponds to the width of its largest element. Displayables are horizontaly centered
// in their respective grid cells.
void GLViewer::repackDisplayables()
{
    if( m_AddingOrder.empty() )
        return;


    // Computes the number of columns of the grid.
    int nCols = (int) std::ceil( std::sqrt( (float)m_AddingOrder.size() ) );


    // Recovers the bounding boxes of all items.
    std::vector<Box3f> boxes( m_AddingOrder.size() );

    auto d = m_AddingOrder.begin();
    for( int i=0; i<boxes.size(); ++i, ++d )
        (*d)->displayable->boundingBox( boxes[i] );


    // Initializes the row height by looking at the bounding box height of the first displayable in the list.
    float rowHeight = boxes[0].Dimensions().y();
    float gridSpacing = 0.05f * rowHeight;


    // The width of each column is determined by looking for the largest rescaled width of all the elements it contains.
    std::vector<int> columnWidth( nCols );
    for( int c=0; c<nCols; ++c )
        columnWidth[c] = 0;

    for( int i=0; i<boxes.size(); ++i )
    {
        int c = i % nCols;
        float rescaledWidth = boxes[i].Dimensions().x() * rowHeight / boxes[i].Dimensions().y();
        if( rescaledWidth > columnWidth[c] )
            columnWidth[c] = rescaledWidth;
    }


    // The scaling factor to be applied to each displayable so as to match the grid row height is computed,
    // and the layout arrangement is finally performed by setting up the translation part of each displayable transform.
    float xRowBeginning = (boxes[0].Min().x() + 0.5f*boxes[0].Dimensions().x()) * rowHeight / boxes[0].Dimensions().y() - 0.5f*columnWidth[0];
    float x = xRowBeginning;
    float y = boxes[0].Min().y() * rowHeight / boxes[0].Dimensions().y();

    d = m_AddingOrder.begin();
    for( int i=0, c=0; i<boxes.size(); ++i, ++d )
    {
        float scalingFactor = rowHeight / boxes[i].Dimensions().y();
        float rescaledWidth = boxes[i].Dimensions().x() * scalingFactor;

584
585
586
587
588
589
590
        QMatrix4x4 packTr;
        packTr.setToIdentity();
        packTr(0,0) = scalingFactor;
        packTr(1,1) = scalingFactor;
        packTr(0,3) = x - boxes[i].Min().x()*scalingFactor + 0.5f*(columnWidth[c]-rescaledWidth);
        packTr(1,3) = y - boxes[i].Min().y()*scalingFactor;
        (*d)->SetPackingTransform( packTr );
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620

        x += columnWidth[c] + gridSpacing;

        if( !(c = (c+1) % nCols) )
        {
            x = xRowBeginning;
            y -= rowHeight + gridSpacing;
        }
    }
}


GLViewer::DisplayableMap::iterator GLViewer::removeDisplayable_Internal( DisplayableMap::iterator &dmapIt )
{
    const GenericUIData *item  = dmapIt->first;
    DisplayableInfo     &dinfo = dmapIt->second;

    if( dinfo.displayable->isAnimated() )
    {
        auto foundAnim = m_ActiveAnimations.find( dinfo.displayable );
        if( foundAnim != m_ActiveAnimations.end() )
        {
            m_ActiveAnimations.erase( foundAnim );
            dinfo.displayable->onAnimationStop();
        }
    }

    disconnect( item->GetDisplayOptions(), SIGNAL(parameterUpdated(UIParam*)), this, SLOT(update()) );
    disconnect( item->GetDisplayOptions(), SIGNAL(parameterUpdated(UIParam*)), dinfo.displayable, SLOT(updateParameter(UIParam*)) );

621
    if( !item->GetDisplayOptions()->IsEmpty() )
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
    {
        item->GetDisplayOptions()->hide();
        m_DisplayOptionsLayout->removeWidget( item->GetDisplayOptions() );
    }

    delete dinfo.selectionMgr;
    dinfo.displayable->release( *item->GetDisplayOptions() );
    delete dinfo.displayable;
    m_DisplayablesByPriority[ m_Factories[item->GetTypeString()]->displayPriority() ].erase( dinfo.posInPriorityList );

    return m_Displayables.erase( dmapIt );
}


void GLViewer::removeDisplayable( GenericUIData *m )
{
    DisplayableMap::iterator foundDisp = m_Displayables.find( m );
    if( foundDisp != m_Displayables.end() )
    {
        makeCurrent();

        if( dof() == DISPLAY_DOF_2D )
        {
            m_AddingOrder.remove( &foundDisp->second );
            removeDisplayable_Internal( foundDisp );
            repackDisplayables();
            frameAll();
        }
        else
            removeDisplayable_Internal( foundDisp );

        updatePrimitiveCounts();
        update();
    }
}


void GLViewer::removeAllDisplayables()
{
    makeCurrent();

	DisplayableMap::iterator disp = m_Displayables.begin();
    while( disp != m_Displayables.end() )
        disp = removeDisplayable_Internal( disp );

    m_AddingOrder.clear();

    updatePrimitiveCounts();
    update();
}


void GLViewer::initializeGL()
{
    makeCurrent();
    glewInit();

    setFocusPolicy( Qt::ClickFocus );

    resizeGL( width(), height() );

    update();
}


void GLViewer::mouseMotionNavigationEvent( float dx, float dy, QMouseEvent *evt )
{
    if( dof() == DISPLAY_DOF_2D )
    {
        if( evt->buttons() & Qt::MidButton )
	    {
            double proj[16];
            glGetDoublev( GL_PROJECTION_MATRIX, proj );
            double scaleFactor = 2.0*distToFocusPoint() / (width()*proj[0]);

		    double scaledDX = dx * scaleFactor;
		    double scaledDY = dy * scaleFactor;

            QVector3D fpoint = focusPoint();
            fpoint[0] += scaledDY*viewRotationMatrix()(1,0) - scaledDX*viewRotationMatrix()(0,0);
            fpoint[1] += scaledDY*viewRotationMatrix()(1,1) - scaledDX*viewRotationMatrix()(0,1);
            setFocusPoint( fpoint );

    	    update();
	    }
#if 0
        else if( evt->buttons() & Qt::LeftButton )
	    {
            const double orientation = (evt->x()-0.5*width())*dy - (evt->y()-0.5*height())*dx;

            Matrix4Dd deltaRot;
            if( orientation > 0.0 )
    		    deltaRot.SetRotation( Vector3Dd(0,0,1), -0.5*M_PI/180.0*std::sqrt(dx*dx+dy*dy) );
            else
    		    deltaRot.SetRotation( Vector3Dd(0,0,1),  0.5*M_PI/180.0*std::sqrt(dx*dx+dy*dy) );
            setViewRotationMatrix( viewRotationMatrix() * deltaRot );

            update();
	    }
#endif
    }
    else
    {
        if( evt->buttons() & Qt::LeftButton  &&  evt->buttons() & Qt::RightButton )
        {
            QVector3D axis( dy, dx, 0.0f );
            double axisLen = axis.length();

            QMatrix4x4 deltaRot;
            deltaRot.rotate( 0.5f*axisLen, axis/axisLen );

733
734
            if( m_View.isLightTrackingEnabled )
                m_View.lightRotationMatrix = deltaRot * m_View.lightRotationMatrix;
735
            else
736
                m_View.lightRotationMatrix = viewRotationMatrix() * deltaRot * viewRotationMatrix().inverted() * m_View.lightRotationMatrix;
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797

            update();
        }
        else if( evt->buttons() & Qt::MidButton )
	    {
            double proj[16];
            glGetDoublev( GL_PROJECTION_MATRIX, proj );
            double scaleFactor = 2.0*distToFocusPoint() / (width()*proj[0]);

		    double scaledDX = dx * scaleFactor;
		    double scaledDY = dy * scaleFactor;

            QVector3D fpoint = focusPoint();
            fpoint[0] += scaledDY*viewRotationMatrix()(1,0) - scaledDX*viewRotationMatrix()(0,0);
            fpoint[1] += scaledDY*viewRotationMatrix()(1,1) - scaledDX*viewRotationMatrix()(0,1);
            fpoint[2] += scaledDY*viewRotationMatrix()(1,2) - scaledDX*viewRotationMatrix()(0,2);
            setFocusPoint( fpoint );

            emit screenSpaceTranslation( QVector2D(-scaledDX,scaledDY) );

    	    update();
	    }
	    else if( evt->buttons() & Qt::LeftButton )
	    {
            QMatrix4x4 deltaRot;

		    if( evt->pos().x() < 0.15f*width() )
                deltaRot.rotate(  0.5f*dy, 0,0,1 );
		    else if( evt->pos().x() > 0.85f*width() )
			    deltaRot.rotate( -0.5f*dy, 0,0,1 );
		    else
            {
                QVector3D axis( dy, dx, 0.0f );
                double axisLen = axis.length();
			    deltaRot.rotate(  0.5f*axisLen, axis/axisLen );
            }

            emit viewRotationMatrixUpdated( deltaRot );
            setViewRotationMatrix( deltaRot * viewRotationMatrix() );

            update();
	    }
    }
}


QMatrix4x4 GLViewer::viewportMatrix( bool flipY ) const
{
    const float xOff = 0.5f*width(), yOff = 0.5f*height();
    const float xAmp = xOff, yAmp = flipY? 1.0f - yOff : yOff;

    return QMatrix4x4( xAmp, 0.0f, 0.0f, xOff,
                       0.0f, yAmp, 0.0f, yOff,
                       0.0f, 0.0f, 1.0f, 0.0f,
                       0.0f, 0.0f, 0.0f, 1.0f );
}


QMatrix4x4 GLViewer::modelMatrix( const DisplayableInterface *d ) const
{
    auto dispInfo = m_Displayables.find(d->getSource());
798
799
    assert( dispInfo != m_Displayables.end() );
    return dispInfo->second.GetTransform();
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
}


void GLViewer::manageAnimations()
{
    // Check if animated objects waiting to be started are pending.

    while( !m_AnimationStartingQueue.isEmpty() )
    {
        auto anim = m_AnimationStartingQueue.front();
        m_AnimationStartingQueue.pop_front();

        if( !m_ActiveAnimations.contains(anim) )
        {
            m_ActiveAnimations[anim] = 0.0f;
            anim->onAnimationStart();
        }
    }


    // Check if animated objects waiting to be stopped are pending.

    while( !m_AnimationStoppingQueue.isEmpty() )
    {
        auto anim = m_AnimationStoppingQueue.front();
        m_AnimationStoppingQueue.pop_front();

        auto foundAnim = m_ActiveAnimations.find( anim );
        if( foundAnim != m_ActiveAnimations.end() )
        {
            m_ActiveAnimations.erase( foundAnim );
            anim->onAnimationStop();
        }
    }


    // Check if at least one of the current animations is not paused.

    bool animationsRunning = false;

    for( auto anim=m_ActiveAnimations.begin(); anim!=m_ActiveAnimations.end(); ++anim )
        if( !anim.key()->isAnimationPaused() )
        {
            animationsRunning = true;
            break;
        }


    // Make all active animated objects to execute a new animation step.

    if( animationsRunning )
    {
        QTime currentTime = QTime::currentTime();
        float dt = 0.001f * m_AnimationFrameTime.msecsTo( currentTime );
        m_AnimationFrameTime = currentTime;

        if( m_AnimationsRunningAtPreviousFrame )
            for( auto anim=m_ActiveAnimations.begin(); anim!=m_ActiveAnimations.end(); ++anim )
                if( !anim.key()->isAnimationPaused() )
                {
                    if( anim.key()->animationTimeStepValue() != 0.0f )
                    {
                        anim.value() += dt;
                        if( anim.value() >= anim.key()->animationTimeStepValue() )
                        {
                            anim.key()->onAnimationStep( anim.value() );
                            anim.value() -= anim.key()->animationTimeStepValue();
                        }
                    }
                    else
                        anim.key()->onAnimationStep( dt );
                }

        update();
    }


    m_AnimationsRunningAtPreviousFrame = animationsRunning;
}


void GLViewer::paintGL()
{
    manageAnimations();


    // Setting up the OpenGL viewport.
887

888
889
890
891
	glViewport( 0, 0, width(), height() );


    // Clear the frame buffer.
892

893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glDisable( GL_LIGHTING );
    glDisable( GL_DEPTH_TEST );
    glDepthMask( GL_FALSE );

    glBegin( GL_QUADS );
        //glColor3ub( 144, 144, 144 );
        glColor3ub( 132, 132, 132 );
        glVertex2i( -1, -1 );
        glVertex2i(  1, -1 );
        glColor3ub( 208, 208, 208 );
        glVertex2i(  1,  1 );
        glVertex2i( -1,  1 );
    glEnd();

    glDepthMask( GL_TRUE );

	glClear( GL_DEPTH_BUFFER_BIT );


918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
    // Update the projection and view matrices, if needed.

    if( m_MustUpdateFocal )
    {
        m_Focal = 1.0 / std::tan( fovY()*M_PI/360.0 );

        m_MustUpdateFocal = false;
        m_MustUpdateProjectionMatrix = true;
    }

    bool mustUpdateViewProjectionMatrix = false;

    if( m_MustUpdateProjectionMatrix )
    {
        m_ProjectionMatrix.fill( 0.0f );
        m_ProjectionMatrix(0,0) = focal() * height() / width();
        m_ProjectionMatrix(1,1) = focal();
        m_ProjectionMatrix(2,2) = (zNear() + zFar())  / (zNear() - zFar());
        m_ProjectionMatrix(2,3) = 2.0f*zNear()*zFar() / (zNear() - zFar());
        m_ProjectionMatrix(3,2) = -1.0f;

        m_ProjectionMatrixInverse = m_ProjectionMatrix.inverted();

        m_MustUpdateProjectionMatrix = false;
        mustUpdateViewProjectionMatrix = true;
    }

    if( m_MustUpdateViewMatrix )
    {
        m_ViewMatrix.setToIdentity();
        m_ViewMatrix.translate( 0.0, 0.0, -distToFocusPoint() );
        m_ViewMatrix *= viewRotationMatrix();
        m_ViewMatrix.translate( -focusPoint() );

        m_ViewMatrixInverse = m_ViewMatrix.inverted();

954
955
        m_ViewRotationMatrixInverse = viewRotationMatrix().inverted();

956
957
958
959
960
961
962
963
        m_MustUpdateViewMatrix = false;
        mustUpdateViewProjectionMatrix = true;
    }

    if( mustUpdateViewProjectionMatrix )
    {
        m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix;
        m_ViewProjectionMatrixInverse = m_ViewMatrixInverse * m_ProjectionMatrixInverse;
964
965

        m_PixelToRayMatrix = viewRotationMatrixInverse() * projectionMatrixInverse();
966
967

        m_Frustum.UpdateFrustumPlanes( m_ViewMatrix, m_ProjectionMatrix );
968
969
970
971
972
    }

    // Setup the OpenGL transforms and viewport.

    glMatrixMode( GL_PROJECTION );
973
974
975
976
977
    glLoadMatrixf( projectionMatrix().data() );

    glMatrixMode( GL_MODELVIEW );
    glLoadMatrixf( viewMatrix().data() );

978
    glPointSize( (GLfloat) m_View.pointSize );
979
980
981
982
983
984
985
986
    glColor3ub( 255, 255, 255 );

    setupScene();


    // Display the scene content by increasing priority.
    for( PriorityMap::iterator dlist=m_DisplayablesByPriority.begin(); dlist!=m_DisplayablesByPriority.end(); ++dlist )
        for( DisplayableList::iterator dinfo=dlist->second.begin(); dinfo!=dlist->second.end(); ++dinfo )
987
988
989
990
991
992
993
994
995
996
997
998
999
            if( !m_Frustum.IsOutside( (*dinfo)->boundingBox, (*dinfo)->GetTransform() ) )
            {
                glPushMatrix();
                glMultMatrixf( (*dinfo)->GetTransform().data() );
                glPushAttrib( GL_ALL_ATTRIB_BITS );
                (*dinfo)->displayable->onDisplay( *(*dinfo)->displayable->getSource()->GetDisplayOptions() );
                displayLabel( (*dinfo)->displayable );
                if( (*dinfo)->selectionMgr )
                    (*dinfo)->selectionMgr->onDisplay( this );
                glPopAttrib();
                glPopMatrix();
            }

1000
1001
1002
1003
1004

    // Finalize the rendering.
    releaseScene();

    // Display the metric grid.
1005
    if( m_View.isGridDisplayed )
1006
1007
1008
1009
1010
1011
1012
1013
    {
        glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
        glDepthMask( GL_FALSE );
        glEnable( GL_DEPTH_TEST );
        m_MetricGrid.display( this );
        glDepthMask( GL_TRUE );
    }

1014
1015
1016
    // Display the label of the object under the mouse cursor.
    if( dof() == DISPLAY_DOF_3D  &&  m_BelowCursor )
    {
1017
        double textX, textY;
1018
        QVector3D c = m_BelowCursor->GetTransform().map( m_BelowCursor->boundingBox.Center() );
1019
1020
1021
        renderCoords( c.x(), c.y(), c.z(), &textX, &textY );

        QString label = m_BelowCursor->displayable->label();
1022
        QFont f( font().family(), 10, QFont::Bold );
1023

1024
        Qt::Alignment align = static_cast<Qt::Alignment>( Qt::AlignHCenter | Qt::AlignCenter );
1025
1026

        glColor3ub( 220, 220, 220 );
1027
1028
1029
1030
        renderText( textX-1, textY-1, label, f, align );
        renderText( textX-1, textY+1, label, f, align );
        renderText( textX+1, textY-1, label, f, align );
        renderText( textX+1, textY+1, label, f, align );
1031
        glColor3ub( 64, 64, 64 );
1032
        renderText( textX, textY, label, f, align );
1033
    }
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063

    // Display the selection tool, if selection mode is enabled.
    if( isSelectionEnabled() )
    {
        m_SelectionCurrentTool->displaySelectionState();
        m_SelectionCurrentTool->display();
    }


    // Display the information bar.
    m_InfoBarManager->display();
}


void GLViewer::setupScene()
{
    // Setup the OpenGL states.

    if( dof() == DISPLAY_DOF_2D )
    {
        glDisable( GL_DEPTH_TEST );
        glEnable( GL_MULTISAMPLE );
        glDisable( GL_LIGHTING );
    }
    else
    {
        // Place the light into the scene.
        glMatrixMode( GL_MODELVIEW );
        glPushMatrix();

1064
        if( m_View.isLightTrackingEnabled )
1065
            glLoadIdentity();
1066
        glMultMatrixf( m_View.lightRotationMatrix.data() );
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077

        GLfloat lightPos[4] = { 0.0f, 0.0f, 1.0f, 0.0f };
        glLightfv( GL_LIGHT0, GL_POSITION, lightPos );

        glPopMatrix();


        // Setup the OpenGL states.
	    glEnable( GL_DEPTH_TEST );
        glEnable( GL_MULTISAMPLE );

1078
        if( m_View.isLightingEnabled )
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
        {
            glEnable( GL_LIGHTING );
            glEnable( GL_LIGHT0 );
            glEnable( GL_COLOR_MATERIAL );
        }
        else
        {
            glDisable( GL_LIGHTING );
            glDisable( GL_LIGHT0 );
            glDisable( GL_COLOR_MATERIAL );
        }

1091
        glPolygonMode( GL_FRONT_AND_BACK, m_View.isWireframeEnabled && !m_SelectionEnabled? GL_LINE : GL_FILL );
1092

1093
        if( m_View.isCullingEnabled )
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
        {
            glEnable( GL_CULL_FACE );
            glCullFace( GL_BACK );
        }
        else
            glDisable( GL_CULL_FACE );
    }
}


void GLViewer::displayLabel( DisplayableInterface *d )
{
    if( dof() == DISPLAY_DOF_2D )
    {
        Box3f box;
        d->boundingBox( box );


        // Display the black border.

        glColor3ub( 0, 0, 0 );

        glBegin( GL_LINE_LOOP );
            glVertex2f( box.Min().x(), box.Min().y() );
            glVertex2f( box.Min().x(), box.Max().y() );
            glVertex2f( box.Max().x(), box.Max().y() );
            glVertex2f( box.Max().x(), box.Min().y() );
        glEnd();


        // Display the name of the image on overlay in the bottom-left corner, by constraining it to the displayed image rectangle.

1126
        QMatrix4x4 toViewportCoord = viewportMatrix(true) * MVPMatrix(d);
1127
1128
1129
        QVector3D bottomLeft = toViewportCoord.map( QVector3D( box.Min().x(), box.Min().y(), 0.0f ) );
        QVector3D topRight   = toViewportCoord.map( QVector3D( box.Max().x(), box.Max().y(), 0.0f ) );

1130
1131
        QFont f( font().family(), 10, QFont::Bold );
        QFontMetrics fm( f );
1132
1133
1134
1135
1136
1137

        QString imgName;
        int imgNameWidth;

        if( fm.height() < bottomLeft.y()-topRight.y()-4 )
        {
1138
            imgName = d->label();
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
            imgNameWidth = fm.width( imgName );

            if( imgNameWidth > topRight.x()-bottomLeft.x()-8 )
            {
                int imgNameLength = imgName.length();
                do
                {
                    -- imgNameLength;
                    imgNameWidth -= fm.width( imgName.at(imgNameLength) );
                } while( imgNameWidth > topRight.x()-bottomLeft.x()-8 );
                imgName = imgName.left( imgNameLength );
            }
        }

        if( imgName.length() > 0 )
        {
            int textX = bottomLeft.x() + 4;
1156
            int textY = bottomLeft.y() - 2;
1157
1158

            glColor3ub( 220, 220, 220 );
1159
1160
1161
1162
            renderText( textX-1, textY-1, imgName, f, Qt::AlignTop );
            renderText( textX-1, textY+1, imgName, f, Qt::AlignTop );
            renderText( textX+1, textY-1, imgName, f, Qt::AlignTop );
            renderText( textX+1, textY+1, imgName, f, Qt::AlignTop );
1163
            glColor3ub( 64, 64, 64 );
1164
            renderText( textX, textY, imgName, f, Qt::AlignTop );
1165
1166
1167
1168
1169
1170
1171
        }
    }
}


void GLViewer::resizeGL( int width, int height )
{
1172
1173
    m_MustUpdateProjectionMatrix = true;

1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
	glViewport( 0, 0, width, height );

    m_InfoBarManager->onReshape();

    for( DisplayableMap::iterator d=m_Displayables.begin(); d!=m_Displayables.end(); ++d )
        d->second.displayable->onReshape( *d->first->GetDisplayOptions() );

    if( isSelectionEnabled() )
        m_SelectionCurrentTool->onResize();

    updateSelectionZBuffer();
}


void GLViewer::updateSelection( SelectionTool &tool )
{
    makeCurrent();

    // Initializes the GL transformation so as to match the current view.

	glMatrixMode( GL_PROJECTION );
    glLoadMatrixf( projectionMatrix().data() );

    glMatrixMode( GL_MODELVIEW );
    glLoadMatrixf( viewMatrix().data() );


    // Initializes the selection context.

    tool.setDepthBuffer( m_SelectionDepthBuffer );
1204
    tool.selectBackFacingGeometry( m_View.isCullingEnabled? GL_FALSE : GL_TRUE );
1205
1206
1207
1208
1209
1210
1211
1212
1213
    tool.preSelectionUpdate();


    // Checks every item that can be selected.

    for( DisplayableMap::iterator d=m_Displayables.begin(); d!=m_Displayables.end(); ++d )
        if( d->second.selectionMgr  &&  d->second.selectionMgr->selectableEntity() == tool.entityToSelect() )
        {
            glPushMatrix();
1214
            glMultMatrixf( d->second.GetTransform().data() );
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
            d->second.selectionMgr->onUpdatingSelection( &tool );
            glPopMatrix();
        }


    tool.postSelectionUpdate();
}


void GLViewer::updateSelectionMode( const Qt::KeyboardModifiers &modifiers )
{
    if( isSelectionEnabled() )
    {
        SelectionTool::SelectionMode newMode;

        if( modifiers & Qt::ShiftModifier )
            newMode = SelectionTool::SELECTION_MODE_SET;
        else if( modifiers & Qt::ControlModifier )
            newMode = SelectionTool::SELECTION_MODE_REMOVE;
        else
            newMode = SelectionTool::SELECTION_MODE_ADD;

        if( m_SelectionCurrentTool->selectionMode() != newMode )
        {
            m_SelectionCurrentTool->setSelectionMode( newMode );
            update();
        }
    }
}


void GLViewer::updateSelectionZBuffer()
{
    if( !isSelectionEnabled() )
        return;

    makeCurrent();


    // Creates the shader that makes it possible to recover the scene Z-buffer.

    if( !m_ZBufferShader.IsCreated() )
    {
        std::string logs;
        if( !GPU::CreateShaderFromSources( m_ZBufferShader, s_ZBufferVPG, s_ZBufferFPG, &logs ) )
        {
            std::cout << "Z-buffer shader compilation error:" << std::endl << logs << std::endl;
            return;
        }
    }


    // Recovers the depth buffer matching the current view for depth test during selection.

    m_SelectionDepthBuffer.Create( GL_DEPTH_COMPONENT, width(), height(), GL_DEPTH_COMPONENT, GL_INT, NULL );
    m_SelectionDepthBuffer.SetFiltering( GL_LINEAR );
    m_SelectionDepthBuffer.SetBaseAndMaxLevels( 0 );
    m_SelectionDepthBuffer.SetCompareMode( GL_COMPARE_R_TO_TEXTURE );
    m_SelectionDepthBuffer.SetCompareFunc( GL_LEQUAL );
    m_SelectionDepthBuffer.SetDepthTextureMode( GL_INTENSITY );

    GPU::FrameBuffer fbuffer( width(), height() );
    fbuffer.Attach( GL_DEPTH_ATTACHMENT, m_SelectionDepthBuffer );
    fbuffer.Bind();

    glClear( GL_DEPTH_BUFFER_BIT );


    // Setting up the OpenGL transforms and viewport.

	glMatrixMode( GL_PROJECTION );
    glLoadMatrixf( projectionMatrix().data() );

    glMatrixMode( GL_MODELVIEW );
    glLoadMatrixf( viewMatrix().data() );

1291
    glPointSize( (GLfloat) m_View.pointSize );
1292
1293
1294
1295
1296
1297
1298
1299

    setupScene();


    // Display the scene content by increasing priority.

    for( PriorityMap::iterator dlist=m_DisplayablesByPriority.begin(); dlist!=m_DisplayablesByPriority.end(); ++dlist )
        for( DisplayableList::iterator dinfo=dlist->second.begin(); dinfo!=dlist->second.end(); ++dinfo )
1300
1301
1302
1303
1304
1305
1306
            if( !m_Frustum.IsOutside( (*dinfo)->boundingBox, (*dinfo)->GetTransform() ) )
            {
                m_ZBufferShader.SetUniform( "fullTransformMatrix", (viewProjectionMatrix() * (*dinfo)->GetTransform()).data() );
                glPushAttrib( GL_ALL_ATTRIB_BITS );
                (*dinfo)->displayable->onPicking( *(*dinfo)->displayable->getSource()->GetDisplayOptions(), m_ZBufferShader, "vertexPosition" );
                glPopAttrib();
            }
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388


    // Finalize the rendering.

    releaseScene();

    fbuffer.Unbind();
}


void GLViewer::processSelection( BaseSelectionProcessor &proc )
{
    std::list<BaseSelectionProcessor*> procList;
    procList.push_back( &proc );
    processSelection( procList );
}


void GLViewer::processSelection( std::list<BaseSelectionProcessor*> &procList )
{
#if 0
    std::map< TypeId, BaseSelectionProcessor* > processorByType;

    for( std::list<BaseSelectionProcessor*>::iterator p=procList.begin(); p!=procList.end(); ++p )
    {
        std::list<TypeId> acceptedTypes;
        (*p)->acceptedDataType( acceptedTypes );

        for( std::list<TypeId>::iterator t=acceptedTypes.begin(); t!=acceptedTypes.end(); ++t )
            processorByType[*t] = *p;
    }


    for( DisplayableMap::iterator d=m_Displayables.begin(); d!=m_Displayables.end(); ++d )
    {
        std::map< TypeId, BaseSelectionProcessor* >::iterator processorFound = processorByType.find( d->first->GetType() );

        if( processorFound != processorByType.end()  &&  (d->second.displayable->selectableEntities() & processorFound->second->entityToProcess()) )
        {
            d->second.displayable->processSelection( *processorFound->second );
            if( processorFound->second->isSelectionResetRequired() )
                d->second.displayable->clearSelection( processorFound->second->entityToProcess() );
            if( processorFound->second->isDisplayableUpdateRequired() )
                updateDisplayable( d->second.displayable->getSrcManageable() );
        }
    }
#endif
}


void GLViewer::processSelection( GenericUIData *m, BaseSelectionProcessor &proc )
{
#if 0
    DisplayableMap::iterator displayableFound = m_Displayables.find( m );

    if( displayableFound == m_Displayables.end() )
        return;

    DisplayableInterface *d = displayableFound->second.displayable;


    std::list<TypeId> acceptedTypes;
    proc.acceptedDataType( acceptedTypes );

    for( std::list<TypeId>::iterator t=acceptedTypes.begin(); t!=acceptedTypes.end(); ++t )
        if( m->GetType() == *t )
        {
            if( d->selectableEntities() & proc.entityToProcess() )
            {
                d->processSelection( proc );
                if( proc.isSelectionResetRequired() )
                    d->clearSelection( proc.entityToProcess() );
                if( proc.isDisplayableUpdateRequired() )
                    updateDisplayable( m );
            }

            break;
        }
#endif
}


1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
void GLViewer::renderCoords( double x, double y, double z, double *screenX, double *screenY )
{
    // Identify x and y locations to render text within widget

    QMatrix4x4 model, proj;
    GLint viewport[4];
    glGetFloatv( GL_MODELVIEW_MATRIX, model.data() );
    glGetFloatv( GL_PROJECTION_MATRIX, proj.data() );
    glGetIntegerv( GL_VIEWPORT, viewport );

    *screenX = *screenY = 0.0;
    QVector4D out = proj.map( model.map( QVector4D(x,y,z,1.0f) ) );

    if( out.w() != 0.0f )
    {
        float wInv = 1.0f / out.w();
        out.setX( out.x() * wInv );
        out.setY( out.y() * wInv );

        *screenX = viewport[0] + (1 + out.x()) * 0.5 * viewport[2];
        *screenY = viewport[1] + (1 + out.y()) * 0.5 * viewport[3];
    }

    *screenY = this->height() - *screenY; // y is inverted
}


1416
void GLViewer::renderText( double x, double y, const QString &text, const QFont &font, Qt::Alignment align )
1417
{
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
    QFontMetrics fm( font );

    // Extract lines from the input strings.

    QStringList textLines;

    int beg = 0, end;
    while( (end = text.indexOf('\n',beg)) >= 0 )
    {
        textLines.push_back( text.mid(beg,end-beg) );
        beg = end + 1;
    }

    textLines.push_back( (beg==0)? text : text.mid(beg) );

1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
    // Save OpenGL states.

    GLint buffer;
    GLboolean depthTest;
	GLboolean blend;
	GLint blendSrcRGB, blendSrcAlpha;
	GLint blendDstRGB, blendDstAlpha;

    glGetIntegerv( GL_FRAMEBUFFER_BINDING, &buffer );
	glGetBooleanv( GL_DEPTH_TEST, &depthTest );
	glGetBooleanv( GL_BLEND, &blend );
	glGetIntegerv( GL_BLEND_SRC_RGB  , &blendSrcRGB   );
	glGetIntegerv( GL_BLEND_SRC_ALPHA, &blendSrcAlpha );
	glGetIntegerv( GL_BLEND_DST_RGB  , &blendDstRGB   );
	glGetIntegerv( GL_BLEND_DST_ALPHA, &blendDstAlpha );

    // Retrieve last OpenGL color to use as a font color.

    GLfloat glColor[4];
    glGetFloatv( GL_CURRENT_COLOR, glColor );
    QColor fontColor = QColor( 255.0f*glColor[0], 255.0f*glColor[1], 255.0f*glColor[2], 255.0f*glColor[3] );

	// Paint text.

1457
1458
1459
1460
1461
    if( align & Qt::AlignTop )
        y -= (textLines.size()-1) * fm.height() + fm.descent();
    else if( align & Qt::AlignCenter )
        y -= ((textLines.size()-2) * fm.height())/2/* + fm.descent()*/;

1462
1463
1464
1465
    QPainter painter;
    painter.begin( this );
	    painter.setPen( fontColor );
	    painter.setFont( font );
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
        for( auto &l : textLines )
        {
            if( align & Qt::AlignRight )
        		painter.drawText( x - fm.width(l), y, l );
            else if( align & Qt::AlignHCenter )
        		painter.drawText( x - fm.width(l)/2, y, l );
            else
        		painter.drawText( x, y, l );
            y += fm.height();
        }
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
    painter.end();

	// Restore OpenGL states.

    glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, buffer );
    depthTest?  glEnable( GL_DEPTH_TEST )  :  glDisable( GL_DEPTH_TEST );
    blend?  glEnable( GL_BLEND )  :  glDisable( GL_BLEND );
	glBlendFuncSeparateEXT( blendSrcRGB, blendDstRGB, blendSrcAlpha, blendDstAlpha );
    glColor4fv( glColor );
}


1488
void GLViewer::renderText( double x, double y, double z, const QString &text, const QFont &font, Qt::Alignment align )
1489
{
1490
1491
    double screenX, screenY;
    renderCoords( x, y, z, &screenX, &screenY );
1492
    renderText( screenX, screenY, text, font, align );
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
}


bool GLViewer::imageOfCurrentDisplay( const GenericUIData *m, QImage &renderResult )
{
    // Check if the provided item is currently displayed.

    DisplayableInterface *d = getDisplayable( m );

    if( !d )
        return false;


    // Recover its dimensions so as to determine the size of the rendering output buffer.

    Box3f dBox;
    d->boundingBox( dBox );

    int w = (int) dBox.Dimensions().x();
    int h = (int) dBox.Dimensions().y();


    // Perform off-screen rendering.

    makeCurrent();

    GPU::FrameBuffer fb( w, h );
    fb.Attach( GL_COLOR_ATTACHMENT0, GL_RGBA );
    fb.Bind();

    glClearColor( 1.0f, 0.0f, 0.0f, 1.0f );
    glClear( GL_COLOR_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glPushMatrix();
    glLoadIdentity();
    glOrtho( dBox.Min().x(), dBox.Max().x(), dBox.Max().y(), dBox.Min().y(), -1.0f, 1.0f );

    glMatrixMode( GL_MODELVIEW );
    glPushMatrix();
    glLoadIdentity();

    d->onDisplay( *m->GetDisplayOptions() );

    glPopMatrix();
    glMatrixMode( GL_PROJECTION );
    glPopMatrix();

    fb.Unbind();


    // Recover the render result and store it to the provided image object.

    GLubyte *fbData = new GLubyte [ 4*w*h ];
    fb.DumpTo( GL_COLOR_ATTACHMENT0, fbData, GL_RGBA, GL_UNSIGNED_BYTE );

    renderResult = QImage( w, h, QImage::Format_RGBA8888 );
    for( int y=0, n=0; y<h; ++y )
    {
        unsigned char *lineData = renderResult.scanLine( y );
        for( int x=0; x<4*w; ++x, ++n )
            lineData[x] = fbData[n];
    }

    delete [] fbData;


    return true;
}


1564
1565
1566
1567
1568
1569
1570
void GLViewer::enterEvent( QEvent* evt )
{
    setFocus();
    QOpenGLWidget::enterEvent( evt );
}


1571
1572
1573
1574
1575
1576
void GLViewer::mousePressEvent( QMouseEvent *evt )
{
    if( dof() == DISPLAY_DOF_2D )
    {
        PickedPoint p;

1577
        if( !isSelectionEnabled()  &&  evt->button() == Qt::RightButton  &&  getPickedPoint( evt->pos().x(), height()-evt->pos().y(), p, true ) )
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
        {
            QMenu ctxMenu;
            ctxMenu.addAction( "Save current render" );

            if( ctxMenu.exec( evt->globalPos() ) )
            {
		        QStringList filters;
			    QString allImages;
                foreach( QByteArray ext, QImageWriter::supportedImageFormats() )
			    {
		            filters << QString(ext).toUpper() + " image files (*." + ext + ")";
				    allImages += " *." + ext;
			    }
			    filters.push_front( "All image files (" + allImages + " )" );

		        QFileDialog dlg( this, "Save image" );
		        dlg.setAcceptMode( QFileDialog::AcceptSave );
                dlg.setFileMode( QFileDialog::AnyFile );
                dlg.setNameFilters( filters );

			    if( dlg.exec() )
			    {
				    QImage img;
				    imageOfCurrentDisplay( p.srcObject, img );
				    img.save( dlg.selectedFiles().front() );
			    }
            }
        }
    }


    if( isSelectionEnabled() )
    {
        if( evt->button() == Qt::RightButton )
            toggleSelection();
        else
        {
            makeCurrent();
            m_SelectionCurrentTool->mousePressEvent( evt );
        }
    }

    m_PrevMousePos = evt->pos();

    update();
}


void GLViewer::mouseReleaseEvent( QMouseEvent *evt )
{
    if( isSelectionEnabled() )
    {
        makeCurrent();
        m_SelectionCurrentTool->mouseReleaseEvent( evt );
        updateSelectionMode( evt->modifiers() );
    }

    update();
}


1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
void GLViewer::findObjectUnderCursor( const QPoint& cursor )
{
    PickedPoint pp;
    if( getPickedPoint( cursor.x(), height()-cursor.y(), pp, true ) )
    {
        auto disp = &m_Displayables[ pp.srcObject ];
        if( disp != m_BelowCursor )
        {
            m_BelowCursor = disp;
            update();
        }
    }
    else if( m_BelowCursor )
    {
        m_BelowCursor = NULL;
        update();
    }
}


void GLViewer::clearObjectUnderCursor()
{
    if( m_BelowCursor )
    {
        m_BelowCursor = NULL;
        update();
    }
}


1669
1670
void GLViewer::mouseMoveEvent( QMouseEvent *evt )
{
1671
1672
1673
1674
1675
1676
1677
    if( isSelectionEnabled() )
    {
        makeCurrent();
        m_SelectionCurrentTool->mouseMoveEvent( evt );
        update();
    }
    else if( evt->buttons() != Qt::NoButton )
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
    {
	    double dx = (evt->pos().x() - m_PrevMousePos.x());
	    double dy = (evt->pos().y() - m_PrevMousePos.y());
	    m_PrevMousePos = evt->pos();

        if( evt->modifiers() & Qt::ShiftModifier )
        {
            dx *= m_ShiftSpeedFactor;
            dy *= m_ShiftSpeedFactor;
        }
        else if( evt->modifiers() & Qt::ControlModifier )
        {
            dx *= m_CtrlSpeedFactor;
            dy *= m_CtrlSpeedFactor;
        }
        else
        {
            dx *= m_SpeedFactor;
            dy *= m_SpeedFactor;
        }

        mouseMotionNavigationEvent( dx, dy, evt );
    }
1701
1702
    else if( !isSelectionEnabled() )
        findObjectUnderCursor( evt->pos() );
1703
1704
1705
1706
1707
1708
1709
1710
1711
}


void GLViewer::wheelEvent( QWheelEvent* evt )
{
	if( evt->orientation() == Qt::Vertical )
	{
        if( !isSelectionEnabled() )
        {
1712
		    double deltaD = -0.0005 * m_SpeedFactor * distToFocusPoint() * evt->delta();
1713
1714
1715
1716
1717
1718

		    if( evt->modifiers() & Qt::ShiftModifier )
			    deltaD *= m_ShiftSpeedFactor;
		    else if( evt->modifiers() & Qt::ControlModifier )
			    deltaD *= m_CtrlSpeedFactor;

1719
1720
		    if( distToFocusPoint() + deltaD > 0.0 )
                setDistToFocusPoint( distToFocusPoint() + deltaD );
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
        }
        else
        {
            makeCurrent();
            m_SelectionCurrentTool->wheelEvent( evt );
        }

		update();
	}
}


void GLViewer::mouseDoubleClickEvent( QMouseEvent *evt )
{
    if( isSelectionEnabled() )
    {
        makeCurrent();
        m_SelectionCurrentTool->mouseDoubleClickEvent( evt );
    }
    else if( evt->buttons() == Qt::LeftButton )
    {
        PickedPoint point;
        if( getPickedPoint( evt->x(), height()-evt->y(), point, false ) )
1744
1745
1746
1747
1748
1749
        {
            if( evt->modifiers() & Qt::ControlModifier )
                frameItem( point.srcObject );
            else
                setFocusPoint( point.global );
        }
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
    }
}


bool GLViewer::event( QEvent *evt )
{
    if( evt->type() == QEvent::KeyPress )
    {
        QKeyEvent *kevt = static_cast<QKeyEvent*>( evt );
        if( kevt->key() == Qt::Key_Tab )
        {
            makeCurrent();

            if( !isSelectionEnabled() )
            {
                m_SelectionContext.isSelecting = false;
                m_SelectionContext.selectionMode = SelectionTool::SELECTION_MODE_SET;
                toggleSelection();
            }
            else if( !(kevt->modifiers() & Qt::Modifier::CTRL) )
            {
                m_SelectionCurrentTool->onDisabled();

                m_SelectionCurrentToolName = (SelectionToolName)( (m_SelectionCurrentToolName + 1) % SELECTION_TOOL_END );
                m_SelectionCurrentTool = m_SelectionTools[ m_SelectionCurrentToolName ];

                m_SelectionCurrentTool->onEnabled();

                for( DisplayableMap::iterator d=m_Displayables.begin(); d!=m_Displayables.end(); ++d )
                    if( d->second.selectionMgr  &&  d->second.selectionMgr->selectableEntity() == m_SelectionCurrentTool->entityToSelect() )
                        d->second.selectionMgr->onRecompilingSelectionShader( m_SelectionCurrentTool );
            }

            if( kevt->modifiers() & Qt::Modifier::CTRL )
            {
                int availableEntities = 0;
                for( DisplayableMap::iterator d=m_Displayables.begin(); d!=m_Displayables.end(); ++d )
                    if( d->second.selectionMgr )
                        availableEntities |= d->second.selectionMgr->selectableEntity();

                if( availableEntities )
                {
                    int newEntity = m_SelectionCurrentTool->entityToSelect();
                    do
                    {
                        newEntity = (newEntity&4)?  1  :  (newEntity << 1);
                    } while( !(newEntity & availableEntities) );
                    setSelectionEntity( (SelectableEntity) newEntity );
                }
            }

            update();
            return true;
        }
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821

        else if( kevt->key() == Qt::Key_Shift  &&  !isSelectionEnabled() )
        {
            setMouseTracking( true );
            findObjectUnderCursor( mapFromGlobal( cursor().pos() ) );
            return true;
        }
    }

    else if( evt->type() == QEvent::KeyRelease )
    {
        QKeyEvent *kevt = static_cast<QKeyEvent*>( evt );
        if( kevt->key() == Qt::Key_Shift  &&  !isSelectionEnabled() )
        {
            setMouseTracking( false );
            clearObjectUnderCursor();
            return true;
        }
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
    }

    return QOpenGLWidget::event( evt );
}


void GLViewer::keyPressEvent( QKeyEvent *evt )
{
    bool defaultBehaviour = false;


    if( dof() == DISPLAY_DOF_2D )
    {
        switch( evt->key() )
        {
            case Qt::Key_Space: centerView(); break;
            case Qt::Key_F1:
            case Qt::Key_F2:
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
            case Qt::Key_F3:
            case Qt::Key_F4:
            case Qt::Key_F5:
            case Qt::Key_F6:
            case Qt::Key_F7:
            case Qt::Key_F8:
            case Qt::Key_F9:
            case Qt::Key_F10:
            case Qt::Key_F11:
            case Qt::Key_F12:
1850
            {
1851
1852
                QString filename;
                filename.sprintf(".viewer_%02i.cfg", evt->key() - Qt::Key_F1 + 1 );
1853

1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
                if( evt->modifiers() == Qt::Modifier::SHIFT )
                {
                    std::ofstream file( filename.toStdString(), std::ios::binary );
                    file.write( (char*) &m_View, sizeof(RenderState) );
                }
                else
                {
                    std::ifstream file( filename.toStdString(), std::ios::binary );
                    if( !file.bad() )
                    {
                        RenderState state;
                        file.read( (char*) &state, sizeof(RenderState) );
                        setRenderState( state );
                    }
                }
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962

                break;
            }
            case Qt::Key_4:
            {
                QMatrix4x4 rot;
                rot.setToIdentity();
                rot.rotate( -15.0f, 0,0,1 );
                setViewRotationMatrix( rot * viewRotationMatrix() );
                update();
                break;
            }
            case Qt::Key_5:
            {
                QMatrix4x4 rot;
                rot.setToIdentity();
                setViewRotationMatrix( rot );
                update();
                break;
            }
            case Qt::Key_6:
            {
                QMatrix4x4 rot;
                rot.setToIdentity();
                rot.rotate( 15.0f, 0,0,1 );
                setViewRotationMatrix( rot * viewRotationMatrix() );
                update();
                break;
            }
            case Qt::Key_G:
            {
                if( m_MetricGrid.isGridEnabled(MetricGrid::XY) )
                    m_MetricGrid.disableGrid( MetricGrid::ALL );
                else if( m_MetricGrid.isAxisEnabled(MetricGrid::X) )
                    m_MetricGrid.disableAxis( MetricGrid::X | MetricGrid::Y );
                else
                {
                    m_MetricGrid.enableAxis ( MetricGrid::X | MetricGrid::Y );
                    m_MetricGrid.enableGrid ( MetricGrid::XY );
                }
                update();
                break;
            }
            default: defaultBehaviour = true;
        }
    }


    else
    {
        switch( evt->key() )
        {
            case Qt::Key_W: toggleWireframe(); break;
            case Qt::Key_L: toggleLighting(); break;
            case Qt::Key_G:
            {
                if( m_MetricGrid.isGridEnabled(MetricGrid::ZX) )
                {
                    m_MetricGrid.disableAxis( MetricGrid::ALL );
                    m_MetricGrid.disableGrid( MetricGrid::ALL );
                }
                else
                {
                    m_MetricGrid.enableAxis( MetricGrid::ALL );
                    m_MetricGrid.enableGrid( MetricGrid::ZX );
                }
                update();
                break;
            }
            case Qt::Key_F1:
            case Qt::Key_F2:
            case Qt::Key_F3:
            case Qt::Key_F4:
            case Qt::Key_F5:
            case Qt::Key_F6:
            case Qt::Key_F7:
            case Qt::Key_F8:
            case Qt::Key_F9:
            case Qt::Key_F10:
            case Qt::Key_F11:
            case Qt::Key_F12:
            {
                qint32 viewId = evt->key() - Qt::Key_F1;
                std::ostringstream filename;
                filename << ".viewer" << viewId << ".cfg";

                if( evt->modifiers() & Qt::SHIFT )
                {
                    std::ofstream file( filename.str().c_str(), std::ios::binary );

                    file.write( (char*) &focusPoint(), sizeof(QVector3D) );
                    float f = distToFocusPoint();
                    file.write( (char*) &f, sizeof(float) );
                    file.write( (char*) &viewRotationMatrix(), sizeof(QMatrix4x4) );
1963
1964
1965
1966
1967
                    file.write( (char*) &m_View.lightRotationMatrix, sizeof(QMatrix4x4) );
                    file.write( (char*) &m_View.isWireframeEnabled, sizeof(bool) );
                    file.write( (char*) &m_View.isLightingEnabled, sizeof(bool) );
                    file.write( (char*) &m_View.isCullingEnabled, sizeof(bool) );
                    file.write( (char*) &m_View.isLightTrackingEnabled, sizeof(bool) );
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
                    double d = speedFactor();
                    file.write( (char*) &d, sizeof(double) );
                    d = ctrlSpeedFactor();
                    file.write( (char*) &d, sizeof(double) );
                    d = shiftSpeedFactor();
                    file.write( (char*) &d, sizeof(double) );
                    file.close();
                }
                else
                {
                    std::ifstream file( filename.str().c_str(), std::ios::binary );
                    if( !file.is_open() )
                        break;

                    QVector3D fp;
                    QMatrix4x4 vRot;
                    bool wireframe, lighting, culling, tracking;
                    float dist2fp;
                    double spF, ctrlSpF, shftSpF;

                    file.read( (char*) &fp, sizeof(QVector3D) );
                    file.read( (char*) &dist2fp, sizeof(float) );
                    file.read( (char*) &vRot, sizeof(QMatrix4x4) );
1991
                    file.read( (char*) &m_View.lightRotationMatrix, sizeof(QMatrix4x4) );
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
                    file.read( (char*) &wireframe, sizeof(bool) );
                    file.read( (char*) &lighting, sizeof(bool) );
                    file.read( (char*) &culling, sizeof(bool) );
                    file.read( (char*) &tracking, sizeof(bool) );
                    file.read( (char*) &spF, sizeof(double) );
                    file.read( (char*) &ctrlSpF, sizeof(double) );
                    file.read( (char*) &shftSpF, sizeof(double) );
                    file.close();

                    setFocusPoint( fp );
                    setDistToFocusPoint( dist2fp );
                    setViewRotationMatrix( vRot );
                    setWireframeEnabled( wireframe );
                    setLightingEnabled( lighting );
                    setCullingEnabled( culling );
                    setLightTrackingEnabled( tracking );
                    setSpeedFactor( spF );
                    setCtrlSpeedFactor( ctrlSpF );
                    setShiftSpeedFactor( shftSpF );

                    update();
                }
                break;
            }
            case Qt::Key_1:
            {
                QMatrix4x4 rot;
                setViewRotationMatrix( rot );
                update();
                break;
            }
            case Qt::Key_3:
            {
                QMatrix4x4 rot;
                rot.rotate( 90.0f, 0,1,0 );
                setViewRotationMatrix( rot );
                update();
                break;
            }
            case Qt::Key_7:
            {
                QMatrix4x4 rot;
                rot.rotate( -90.0f, 1,0,0 );
                setViewRotationMatrix( rot );
                update();
                break;
            }
            case Qt::Key_4:
            {
                QMatrix4x4 rot;
                rot.rotate( -15.0f, 0,1,0 );
                setViewRotationMatrix( viewRotationMatrix() * rot );
                update();
                break;
            }
            case Qt::Key_6:
            {
                QMatrix4x4 rot;
                rot.rotate( 15.0f, 0,1,0 );
                setViewRotationMatrix( viewRotationMatrix() * rot );
                update();
                break;
            }
            case Qt::Key_2:
            {
                QMatrix4x4 rot;
                rot.rotate( 15.0f, 1,0,0 );
                setViewRotationMatrix( rot * viewRotationMatrix() );
                update();
                break;
            }
            case Qt::Key_8:
            {
                QMatrix4x4 rot;
                rot.rotate( -15.0f, 1,0,0 );
                setViewRotationMatrix( rot * viewRotationMatrix() );
                update();
                break;
            }
		    case Qt::Key_Plus:
		    {
			    increasePointSize();
			    update();
			    break;
		    }
		    case Qt::Key_Minus:
		    {
			    decreasePointSize();
			    update();
			    break;
		    }
            default: defaultBehaviour = true;
        }
    }


    if( defaultBehaviour )
    {
        switch( evt->key() )
        {
            case Qt::Key_C:  toggleCulling(); break;
2093
            case Qt::Key_G:  m_View.isGridDisplayed = !m_View.isGridDisplayed; update(); break;
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123