SelectionBasePlugin.cc 68 KB
Newer Older
Jan Möbius's avatar
 
Jan Möbius committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *      Copyright (C) 2001-2010 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openflipper.org                             *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenFlipper.                                        *
 *                                                                           *
 *  OpenFlipper is free software: you can redistribute it and/or modify      *
 *  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 with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenFlipper is distributed in the hope that it will be useful,           *
 *  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 LesserGeneral Public          *
 *  License along with OpenFlipper. If not,                                  *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
Jan Möbius's avatar
Jan Möbius committed
37
38
39
 *   $Revision$                                                      *
 *   $Author$                                                       *
 *   $Date$                   *
Jan Möbius's avatar
 
Jan Möbius committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 *                                                                           *
\*===========================================================================*/

#include "SelectionBasePlugin.hh"

#include <OpenFlipper/common/GlobalOptions.hh>

// Standard selection mode icon files
#define TOGGLE_IMG          "selection_toggle.png"
#define LASSO_IMG           "selection_lasso.png"
#define VOLUME_LASSO_IMG    "selection_lasso2.png"
#define SURFACE_LASSO_IMG   "surface-lasso.png"
#define SPHERE_IMG          "selection_paintSphere.png"
#define BOUNDARY_IMG        "selection_boundary.png"
#define FLOODFILL_IMG       "selection_floodFill.png"
55
#define COMPONENTS_IMG      "selection_connected.png"
Jan Möbius's avatar
 
Jan Möbius committed
56
57
58
59
60
61
62
63
64

// Standard selection mode descriptions
#define TOGGLE_DESC         "Toggle Selection"
#define LASSO_DESC          "Lasso Selection"
#define VOLUME_LASSO_DESC   "Volume Lasso Selection"
#define SURFACE_LASSO_DESC  "Surface Lasso Selection"
#define SPHERE_DESC         "Sphere Selection"
#define BOUNDARY_DESC       "Boundary Selection"
#define FLOODFILL_DESC      "Floodfill Selection"
65
#define COMPONENTS_DESC     "Selected Components Selection"
Jan Möbius's avatar
 
Jan Möbius committed
66
67
68
69
70
71
72
73
74

// Standard selection mode names
#define SB_TOGGLE           "sb_toggle"
#define SB_LASSO            "sb_lasso"
#define SB_VOLUME_LASSO     "sb_volumelasso"
#define SB_SURFACE_LASSO    "sb_surfacelasso"
#define SB_SPHERE           "sb_sphere"
#define SB_BOUNDARY         "sb_closestboundary"
#define SB_FLOODFILL        "sb_floodfill"
75
#define SB_COMPONENTS       "sb_components"
Jan Möbius's avatar
 
Jan Möbius committed
76
77
78
79
80
81
82
83
84
85
86
87

// Constant to set if no selection picking is enabled
#define NO_SELECTION_PICKING    "No_Selection_Picking"
#define NO_SELECTION_MODE       "No_Selection_Mode"

#define SELECTION_PICKING   "SelectionBasePicking"

// Constructor
SelectionBasePlugin::SelectionBasePlugin() :
toolBar_(0),
tool_(0),
primitivesBarGroup_(0),
Jan Möbius's avatar
Jan Möbius committed
88
pickModeToolBar_(0),
89
selectionModesGroup_(0),
Jan Möbius's avatar
 
Jan Möbius committed
90
91
92
93
94
95
96
toggleSelectionAction_(0),
lassoSelectionAction_(0),
volumeLassoSelectionAction_(0),
surfaceLassoSelectionAction_(0),
sphereSelectionAction_(0),
boundarySelectionAction_(0),
floodFillSelectionAction_(0),
97
componentsSelectionAction_(0),
Jan Möbius's avatar
 
Jan Möbius committed
98
99
100
101
nextFreePrimitiveType_(1u),
sphere_mat_node_(0),
sphere_node_(0),
line_node_(0),
Jan Möbius's avatar
Jan Möbius committed
102
103
104
lassoSelection_(false),
toolIcon_(0)
{
Jan Möbius's avatar
 
Jan Möbius committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    
    // Reset active pick mode
    currentPickMode_            = NO_SELECTION_PICKING;
    lastPickMode_               = NO_SELECTION_PICKING;
    currentSelectionMode_       = NO_SELECTION_MODE;
    
    currentPrimitiveType_ = 0u;
    
    // We initially want selection, not deselection
    deselection_ = false;
    
    sphere_radius_ = 0.0;
}

//============================================================================================

void SelectionBasePlugin::initializePlugin() {
    
    // Skip if no gui is available
    if (OpenFlipper::Options::nogui())
        return;
  
    // Create tool box
    tool_ = new SelectionBaseToolboxWidget();
    QSize size(300, 300);
    tool_->resize(size);
    
    // Connect load/save buttons
    connect(tool_->loadSelection, SIGNAL(clicked()), this, SLOT(slotLoadSelection()));
    connect(tool_->saveSelection, SIGNAL(clicked()), this, SLOT(slotSaveSelection()));
    
    // Add toolbox to OpenFlipper main window
Dirk Wilden's avatar
Dirk Wilden committed
137
138
    toolIcon_ = new QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"selection_base.png");
    emit addToolbox("Selections", tool_, toolIcon_ );
Jan Möbius's avatar
 
Jan Möbius committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    
    // Create toolbar that holds the selection environment buttons
    toolBar_ = new QToolBar(tr("Selection Base"));
    emit addToolbar(toolBar_);
    
    QString iconPath = OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator();
    QAction* selectionEnvironmentButton = new QAction(QIcon(iconPath + "selection_base.png"), "Selections", toolBar_);
    toolBar_->addAction(selectionEnvironmentButton);
    
    // Connect QAction to local function that switches mode
    connect(selectionEnvironmentButton, SIGNAL(triggered(bool)), this, SLOT(slotSelectionEnvironmentRequested(bool)));
    
    // Register keys
    emit registerKey(Qt::Key_Control, Qt::NoModifier, tr("Deselection"), true);
    emit registerKey(Qt::Key_Control, Qt::ControlModifier, tr("Deselection"), true);
    
    emit registerKey(Qt::Key_Shift, Qt::NoModifier, tr("Source/Target Selection"), true);
    emit registerKey(Qt::Key_Shift, Qt::ShiftModifier, tr("Source/Target Selection"), true);
    
    // Add pickmode for the selection environment
    emit addPickMode(SELECTION_PICKING);
    // Enable mouse tracking for all pick modes
    emit setPickModeMouseTracking(SELECTION_PICKING, true);
    
    // Set tabs widget movable
    tool_->typeTabWidget->setMovable(true);

    // Set pick mode toolbar
167
168
    pickModeToolBar_ = new QToolBar("Selection Picking Toolbar");

Jan Möbius's avatar
 
Jan Möbius committed
169
    // Create primitive toolbar
170
    primitivesBarGroup_ = new QActionGroup(pickModeToolBar_);
Jan Möbius's avatar
 
Jan Möbius committed
171
    primitivesBarGroup_->setExclusive(true);
172
173


Jan Möbius's avatar
 
Jan Möbius committed
174
    // Create default selection mode actions
175
    selectionModesGroup_ = new QActionGroup(pickModeToolBar_);
Jan Möbius's avatar
 
Jan Möbius committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    selectionModesGroup_->setExclusive(true);
    toggleSelectionAction_ = new HandleAction(QIcon(iconPath + TOGGLE_IMG), TOGGLE_DESC, selectionModesGroup_);
    toggleSelectionAction_->setCheckable(true);
    toggleSelectionAction_->selectionModeHandle(SB_TOGGLE);
    connect(toggleSelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
    lassoSelectionAction_ = new HandleAction(QIcon(iconPath + LASSO_IMG), LASSO_DESC, selectionModesGroup_);
    lassoSelectionAction_->setCheckable(true);
    lassoSelectionAction_->selectionModeHandle(SB_LASSO);
    connect(lassoSelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
    volumeLassoSelectionAction_ = new HandleAction(QIcon(iconPath + VOLUME_LASSO_IMG), VOLUME_LASSO_DESC, selectionModesGroup_);
    volumeLassoSelectionAction_->setCheckable(true);
    volumeLassoSelectionAction_->selectionModeHandle(SB_VOLUME_LASSO);
    connect(volumeLassoSelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
    surfaceLassoSelectionAction_ = new HandleAction(QIcon(iconPath + SURFACE_LASSO_IMG), SURFACE_LASSO_DESC, selectionModesGroup_);
    surfaceLassoSelectionAction_->setCheckable(true);
    surfaceLassoSelectionAction_->selectionModeHandle(SB_SURFACE_LASSO);
    connect(surfaceLassoSelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
    sphereSelectionAction_ = new HandleAction(QIcon(iconPath + SPHERE_IMG), SPHERE_DESC, selectionModesGroup_);
    sphereSelectionAction_->setCheckable(true);
    sphereSelectionAction_->selectionModeHandle(SB_SPHERE);
    connect(sphereSelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
    boundarySelectionAction_ = new HandleAction(QIcon(iconPath + BOUNDARY_IMG), BOUNDARY_DESC, selectionModesGroup_);
    boundarySelectionAction_->setCheckable(true);
    boundarySelectionAction_->selectionModeHandle(SB_BOUNDARY);
    connect(boundarySelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
    floodFillSelectionAction_ = new HandleAction(QIcon(iconPath + FLOODFILL_IMG), FLOODFILL_DESC, selectionModesGroup_);
    floodFillSelectionAction_->setCheckable(true);
    floodFillSelectionAction_->selectionModeHandle(SB_FLOODFILL);
    connect(floodFillSelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
205
206
207
208
    componentsSelectionAction_ = new HandleAction(QIcon(iconPath + COMPONENTS_IMG), COMPONENTS_DESC, selectionModesGroup_);
    componentsSelectionAction_->setCheckable(true);
    componentsSelectionAction_->selectionModeHandle(SB_COMPONENTS);
    connect(componentsSelectionAction_, SIGNAL(triggered(bool)), this, SLOT(slotEnterSelectionMode(bool)));
209

210
211
212
213
214
215
    pickModeToolBar_->clear();
    pickModeToolBar_->addActions(primitivesBarGroup_->actions());
    pickModeToolBar_->addSeparator();
    pickModeToolBar_->addActions(selectionModesGroup_->actions());

    emit setPickModeToolbar(SELECTION_PICKING, pickModeToolBar_);
Jan Möbius's avatar
 
Jan Möbius committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
}

//============================================================================================

void SelectionBasePlugin::pluginsInitialized() {
    
    // Initialize scenegraph nodes that are used for the
    // rendering of the selection tools (e.g. sphere, lasso, etc.)
    
    // Sphere node
    
    std::string nodeName = std::string( tr("Selection Base Plugin: Selection Sphere Material").toUtf8() );
    sphere_mat_node_  = new ACG::SceneGraph::MaterialNode(0, nodeName );
    PluginFunctions::addGlobalNode(sphere_mat_node_);
    sphere_mat_node_->applyProperties( MaterialNode::Blending  |
                                       MaterialNode::Material  |
                                       MaterialNode::AlphaTest |
                                       MaterialNode::BackFaceCulling );
                                       
    sphere_mat_node_->set_color(ACG::Vec4f(1.0, 0.0, 0.0, 0.3));
    sphere_mat_node_->enable_blending();
    sphere_mat_node_->disable_alpha_test();
    sphere_mat_node_->enable_backface_culling();

    nodeName = std::string( tr("Selection Base Plugin: Selection Sphere").toUtf8() );
    sphere_node_ = new ACG::SceneGraph::GlutPrimitiveNode(ACG::SceneGraph::GlutPrimitiveNode::SPHERE, sphere_mat_node_, nodeName);
    sphere_node_->drawMode(ACG::SceneGraph::DrawModes::SOLID_SMOOTH_SHADED);
    sphere_node_->get_primitive(0).color = ACG::Vec4f(1.0, 0.0, 0.0,0.3);
    sphere_node_->hide();

    // Line node
    
    nodeName = std::string( tr("Selection Base Plugin: Lasso Selection Line").toUtf8() );
    line_node_ = new ACG::SceneGraph::LineNode (ACG::SceneGraph::LineNode::PolygonMode, 0, nodeName );
    PluginFunctions::addGlobalNode(line_node_);                                              
    line_node_->set_line_width (2.0);
    line_node_->alwaysOnTop() = true;
    line_node_->setTraverseMode (BaseNode::NodeFirst | BaseNode::SecondPass);
    line_node_->hide();
}

//============================================================================================

SelectionTypeFrameWidget* SelectionBasePlugin::createNewTypeFrame(SelectionEnvironment& _env) {
    
    SelectionTypeFrameWidget* tab = new SelectionTypeFrameWidget(tool_->typeTabWidget);
    
    // Layout in tool box that contains the primitive buttons
    _env.primitivesBar = new QHBoxLayout(tab->toolPrimitivesBar);
        
    // Layout in tool box that contains the operation buttons
    _env.operationsBar = new QVBoxLayout(tab->toolOperationsWidget);
    
    QSizePolicy policy;
    policy.setVerticalPolicy(QSizePolicy::MinimumExpanding);
    policy.setHorizontalPolicy(QSizePolicy::Preferred);
    tab->selectionGroup->setSizePolicy(policy);
    
    tab->toolPrimitivesBar->setLayout(_env.primitivesBar);
    tab->toolPrimitivesBar->setMinimumHeight(68);
    tab->toolOperationsWidget->setLayout(_env.operationsBar);
    tab->toolOperationsWidget->setMinimumHeight(150);
    
    _env.primitiveActions = new QActionGroup(0);
    _env.primitiveActions->setExclusive(true);
    
    return tab;
}

//============================================================================================

void SelectionBasePlugin::slotLoadSelection() {
    // Load selection button has been clicked

    QString filename = QFileDialog::getOpenFileName(0, tr("Load Selection"), "selection.ini", tr("Selection files ( *.ini )"));

    if(filename.length() > 0) {
        
        INIFile file;
    
        if(!file.connect(filename, false)) {
            emit log(LOGERR, QString("Could not read file '%1'!").arg(filename));
            return;
        }
        
        // Pass ini-file to all object selection implementations
        emit loadSelection(file);
        
        // Close file
        file.disconnect();
    }
}

//============================================================================================

void SelectionBasePlugin::slotSaveSelection() {
    // Save selection button has been clicked
    
    QString filename = QFileDialog::getSaveFileName(0, tr("Save Selection"), "selection.ini", tr("Selection files ( *.ini )"));

    if(filename.length() > 0) {
        
        INIFile file;
    
        if(!file.connect(filename, true)) {
            emit log(LOGERR, QString("Could not create file '%1'!").arg(filename));
            return;
        }
        
        // Pass ini-file to all object selection implementations
        emit saveSelection(file);
        
        // Write all data to the file
        file.disconnect();
    }
}

//============================================================================================

void SelectionBasePlugin::slotKeyEvent(QKeyEvent* _event) {
    
    // Check if we want to select or deselect
    if ((_event->modifiers() & Qt::ControlModifier) || (_event->key() == Qt::Key_Control)) {
        deselection_ = true;
        primitivesBarGroup_->setExclusive(false);
    } else {
        deselection_ = false;
        primitivesBarGroup_->setExclusive(true);
    }
    
    // Check if we want to source or target selection
    if ((_event->modifiers() & Qt::ShiftModifier) || (_event->key() == Qt::Key_Shift))
        tool_->restrictOnTargets->setChecked(true);
    else
        tool_->restrictOnTargets->setChecked(false);
    
    // We have to store and search for registered key combinations at this point
    // in order to preserve the possibility to register some key events exclusively
    // for SelectionBasePlugin (whithout passing them on to al type selection plugins...
    
    // Search for key combination
    std::set<std::pair<int,Qt::KeyboardModifiers> >::iterator f =
        registeredKeys_.find(std::pair<int,Qt::KeyboardModifiers>(_event->key(), _event->modifiers()));
        
    if(f != registeredKeys_.end()) {
        // Some registered key found
        emit keyShortcutEvent((*f).first,(*f).second);
    }
}

//============================================================================================

void SelectionBasePlugin::slotKeyReleaseEvent(QKeyEvent* _event) {
    
    //check if we want to select or deselect
    if ((_event->modifiers() & Qt::ControlModifier) || (_event->key() == Qt::Key_Control)) {
        deselection_ = false;
        primitivesBarGroup_->setExclusive(true);
    }
    
    // Check if we want to source or target selection
    if ((_event->modifiers() & Qt::ShiftModifier) || (_event->key() == Qt::Key_Shift))
        tool_->restrictOnTargets->setChecked(false);
}

//============================================================================================

void SelectionBasePlugin::slotAddSelectionEnvironment(QString _modeName, QString _description, QIcon _icon, QString& _handleName) {
    /*
    A new selection environment is to be added. We first test if the
    associated selection environment already exists. If not, we create
    a new button and hide it.
    */
    std::map<QString,SelectionEnvironment>::iterator it =
        selectionEnvironments_.begin();    
    
    for(; it != selectionEnvironments_.end(); ++it) {
        if(_modeName == (*it).second.name) {
            emit log(LOGINFO, QString("Selection environment %1 already exists.").arg(_modeName));
            return;
        }
    }

    // Create new selection environment
    SelectionEnvironment env;
    env.name = _modeName;
    
    SelectionTypeFrameWidget* tab = createNewTypeFrame(env);
    
    // Add type frame to tab widget
    int index = tool_->typeTabWidget->addTab(tab, _icon, _modeName);
407
    env.tabWidget = tool_->typeTabWidget->widget(index);
Jan Möbius's avatar
 
Jan Möbius committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    
    // Disable type frame unless there's at least one
    // object of the desired type in the scene
    tool_->typeTabWidget->setTabEnabled(index, false);
    tool_->typeTabWidget->widget(index)->setEnabled(false);
    
    // Create a unique handle name for this selection environment
    _handleName = getUniqueHandleName("h_" + _modeName.replace(" ", "_"));
    
    // Set handle for selection environment
    env.handle = _handleName;
    
    // Update pick mode toolbar
    updatePickModeToolBar();
    
    // Add selection environment to local map
    selectionEnvironments_.insert(std::pair<QString,SelectionEnvironment>(_handleName, env));
}

//============================================================================================

void SelectionBasePlugin::slotRegisterType(QString _handleName, DataType _type) {
    /*
    Register new data type under the selection environment with
    handle name _handleName.
    */
    std::map<QString,SelectionEnvironment>::iterator it =
        selectionEnvironments_.find(_handleName);
        
    // If the associated selection environment has been found,
    // we add the specified data type to the list of supported data types
    if(it != selectionEnvironments_.end()) {
        // Search if the data type has already been added before...
        for(std::vector<DataType>::iterator t_it = (*it).second.types.begin();
            t_it != (*it).second.types.end(); ++t_it) {
            // If the type already exists in the list -> return
            if ((*t_it) == _type) return;
        }
        // ...if not, add it.
        (*it).second.types.push_back(_type);
        // And show selection environment button if at least one object
        // of the associated type already exists in the scenegraph
        if(typeExists(_type)) {
            // Show selection environment's tab widget
452
453
            tool_->typeTabWidget->setTabEnabled(tool_->typeTabWidget->indexOf((*it).second.tabWidget), true);
            (*it).second.tabWidget->setEnabled(true);
Jan Möbius's avatar
 
Jan Möbius committed
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
        }
        
    } else {
        emit log(LOGERR, "The specified selection environment has not been found! The data type could not be registered.");
    }
}

void SelectionBasePlugin::updatePickModeToolBar() {
    
    // Add newly added primitive and tool buttons
    QList<QAction*> primitivesList = primitivesBarGroup_->actions();
    
    for(QList<QAction*>::iterator it = primitivesList.begin(); it != primitivesList.end(); ++it) {
            (*it)->setEnabled(false);
            
469
470
471
472
473
474
475
476
477
478
479
480
481
482
        // If at least one object of this type exists in the scene,
        // don't grey out the button
        PrimitiveAction* act = dynamic_cast<PrimitiveAction*>(*it);
        if(act) {
            std::map<QString,SelectionEnvironment>::iterator sit =
                selectionEnvironments_.find(act->selectionEnvironmentHandle());
            if(sit != selectionEnvironments_.end()) {

                bool atLeastOne = false;
                for(std::vector<DataType>::iterator tit = (*sit).second.types.begin();
                    tit != (*sit).second.types.end(); ++tit) {
                    if(typeExists(*tit)) {
                        atLeastOne = true;
                        break;
Jan Möbius's avatar
 
Jan Möbius committed
483
484
                    }
                }
485
486
487
                if(atLeastOne) {
                    (*it)->setEnabled(true);
                }
Jan Möbius's avatar
 
Jan Möbius committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
            }
        }
    }
    
    // Only activate those tools, that are available for the current
    // active primitive type
    
    for(std::map<QString,SelectionEnvironment>::iterator it = selectionEnvironments_.begin();
        it != selectionEnvironments_.end(); ++it) {
            
        // Default selection modes
        toggleSelectionAction_->setEnabled(toggleSelectionAction_->isAssociated(currentPrimitiveType_, true));
        lassoSelectionAction_->setEnabled(lassoSelectionAction_->isAssociated(currentPrimitiveType_, true));
        volumeLassoSelectionAction_->setEnabled(volumeLassoSelectionAction_->isAssociated(currentPrimitiveType_, true));
        surfaceLassoSelectionAction_->setEnabled(surfaceLassoSelectionAction_->isAssociated(currentPrimitiveType_, true));
        sphereSelectionAction_->setEnabled(sphereSelectionAction_->isAssociated(currentPrimitiveType_, true));
        boundarySelectionAction_->setEnabled(boundarySelectionAction_->isAssociated(currentPrimitiveType_, true));
        floodFillSelectionAction_->setEnabled(floodFillSelectionAction_->isAssociated(currentPrimitiveType_, true));
506
        componentsSelectionAction_->setEnabled(componentsSelectionAction_->isAssociated(currentPrimitiveType_, true));
Jan Möbius's avatar
 
Jan Möbius committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
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

        // Custom selection modes
        for(std::set<HandleAction*>::iterator cit = (*it).second.customSelectionModes.begin();
            cit != (*it).second.customSelectionModes.end(); ++cit) {
            (*cit)->setEnabled((*cit)->isAssociated(currentPrimitiveType_, true));
        }

        break;
    }
}

//============================================================================================

void SelectionBasePlugin::slotMouseWheelEvent(QWheelEvent* _event, const std::string& _mode) {
    
    if(currentPickMode_ == NO_SELECTION_PICKING) return;
    
    // Increase sphere radius
    if (currentSelectionMode_ == SB_SPHERE) {
        
        float d = -(float)_event->delta() / 120.0 * 0.1;
        sphere_radius_ *= 1.0 + d;

        sphere_node_->set_size(sphere_radius_);
        sphere_node_->show();

        emit updateView();
    }
}

//============================================================================================

void SelectionBasePlugin::slotMouseEvent(QMouseEvent* _event) {
    
    if(currentPickMode_ == NO_SELECTION_PICKING) return;
    
    // Go into appropriate pick processing
    if(currentSelectionMode_ == SB_TOGGLE) {
        slotToggleSelection(_event);
    } else if (currentSelectionMode_ == SB_LASSO) {
        slotLassoSelection(_event);
    } else if (currentSelectionMode_ == SB_VOLUME_LASSO) {
        slotVolumeLassoSelection(_event);
    } else if (currentSelectionMode_ == SB_SURFACE_LASSO) {
        slotSurfaceLassoSelection(_event);
    } else if (currentSelectionMode_ == SB_SPHERE) {
        slotSphereSelection(_event);
    } else if (currentSelectionMode_ == SB_BOUNDARY) {
        slotBoundarySelection(_event);
    } else if (currentSelectionMode_ == SB_FLOODFILL) {
        slotFloodFillSelection(_event);
558
559
    } else if (currentSelectionMode_ == SB_COMPONENTS) {
        slotComponentsSelection(_event);
Jan Möbius's avatar
 
Jan Möbius committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
    } else {
        // Custom selection mode
        slotCustomSelection(_event);
    }
}

//============================================================================================

void SelectionBasePlugin::slotAddPrimitiveType(QString _handleName, QString _name, QIcon _icon, SelectionInterface::PrimitiveType& _typeHandle) {
    
    // Get selection environment
    std::map<QString,SelectionEnvironment>::iterator it =
        selectionEnvironments_.find(_handleName);
        
    if(it == selectionEnvironments_.end()) {
        emit log(LOGERR, QString("Could not find selection environment width handle '%1'!").arg(_handleName));
        return;
    }
    
    SelectionEnvironment& env = (*it).second;
    
    // Test if there's a free primitive type available
    // Note: This is actually limited to 31
    if(nextFreePrimitiveType_ > nextFreePrimitiveType_ << 1) {
        emit log(LOGERR, "Maximum number of custom primitive types for selection reached!");
        return;
    }
    
    // Test if there's a custom type with the same name already
    QList<QAction*>::const_iterator a_it = env.primitiveActions->actions().constBegin();
    for(; a_it != env.primitiveActions->actions().constEnd(); ++a_it) {
        if((*a_it)->text() == _name) {
            emit log(LOGERR, QString("A custom primitive type with name \"%1\" already exists!").arg(_name));
            return;
        }
    }
    
    // Add custom primitive type
    PrimitiveAction* action = new PrimitiveAction(_icon, _name, env.primitiveActions);
    action->setCheckable(true);
    action->selectionEnvironmentHandle(_handleName);
    primitivesBarGroup_->addAction(action);
602
603
604
605
606
    pickModeToolBar_->clear();
    pickModeToolBar_->addActions(primitivesBarGroup_->actions());
    pickModeToolBar_->addSeparator();
    pickModeToolBar_->addActions(selectionModesGroup_->actions());

Jan Möbius's avatar
 
Jan Möbius committed
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
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
    // Also add type button to tool box of environment tab
    ActionButton* button = new ActionButton(action);
    button->setMinimumSize(QSize(32,32));
    button->setMaximumSize(QSize(64,64));
    env.primitivesBar->addWidget(button);
    
    _typeHandle = nextFreePrimitiveType_;
    action->primitiveType(_typeHandle);
    
    // Add primitive type to environment
    env.primitiveTypes |= _typeHandle;
    
    primitiveTypeButtons_.insert(std::pair<PrimitiveType,QAction*>(_typeHandle,action));
    
    // Go over to next free primitive type
    nextFreePrimitiveType_ <<= 1;
    
    // Connect action to local slot in order to keep track of active primitive types
    connect(action, SIGNAL(toggled(bool)), this, SLOT(updateActivePrimitiveTypes(bool)));
    
    updatePickModeToolBar();
}

//============================================================================================

void SelectionBasePlugin::updateActivePrimitiveTypes(bool _checked) {
    
    QObject* sender = QObject::sender();
    PrimitiveAction* clickedAction = 0;
    clickedAction = dynamic_cast<PrimitiveAction*>(sender);
    
    if(!clickedAction) return;
    
    // Change button state
    clickedAction->setChecked(_checked);
    
    // Reset types
    currentPrimitiveType_ = 0u;
    
    QList<QAction*> actions = primitivesBarGroup_->actions();
    for(int i = 0; i < actions.size(); ++i) {
        
        if(actions[i]->isChecked()) {
            PrimitiveAction* pa = 0;
            pa = dynamic_cast<PrimitiveAction*>(actions[i]);
            if(pa) {
                currentPrimitiveType_ |= pa->primitiveType();
            }
        }
    }
    
    // If the primitive type button has been activated,
    // automatically go into the associated selection environment's
    // picking mode
    if(_checked) {
        slotSelectionEnvironmentRequested(_checked);
    }
    
    // If currently selected selection mode is not available
    // for the currently active primitive types, reset selection mode
    QList<QAction*> sm_actions = selectionModesGroup_->actions();
668
    bool atLeastOneSelectionMode = false;
Jan Möbius's avatar
 
Jan Möbius committed
669
670
671
    for(int i = 0; i < sm_actions.size(); ++i) {

        if(sm_actions[i]->isChecked()) {
672
            atLeastOneSelectionMode = true;
Jan Möbius's avatar
 
Jan Möbius committed
673
674
675
676
677
678
679
680
681
682
683
684
            HandleAction* ha = 0;
            ha = dynamic_cast<HandleAction*>(sm_actions[i]);
            if(ha) {
                if(!ha->isAssociated(currentPrimitiveType_)) {
                    ha->blockSignals(true);
                    ha->setChecked(false);
                    ha->blockSignals(false);
                    toggleSelectionAction_->trigger();
                }
            }
        }
    }
685
686
687
688
    // If no selection mode is active, automatically go into toggle mode
    if(!atLeastOneSelectionMode) {
        toggleSelectionAction_->trigger();
    }
Jan Möbius's avatar
 
Jan Möbius committed
689
690
691
692

    // Automatically show tab widget associated to this primitive type
    std::map<QString,SelectionEnvironment>::iterator sit = selectionEnvironments_.find(clickedAction->selectionEnvironmentHandle());
    if(sit != selectionEnvironments_.end() && _checked) {
693
        tool_->typeTabWidget->setCurrentIndex(tool_->typeTabWidget->indexOf((*sit).second.tabWidget));
Jan Möbius's avatar
 
Jan Möbius committed
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
733
734
735
736
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
798
799
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
    }
    
    // Clear lines
    line_node_->clear();
    linePoints_.clear();
    lassoSelection_ = false;

    // Hide and show selection functions that are associated
    // with the currently active primitive types
    slotShowAndHideOperations();
    
    // Update pick modes bar
    updatePickModeToolBar();
}

//============================================================================================

void SelectionBasePlugin::slotAddSelectionOperations(QString _handleName, QStringList _operationsList, QString _category, PrimitiveType _type) {
    
    // Get selection environment
    std::map<QString,SelectionEnvironment>::iterator e_it =
        selectionEnvironments_.find(_handleName);
        
    if(e_it == selectionEnvironments_.end()) {
        emit log(LOGERR, QString("Could not find selection environment with handle '%1'!").arg(_handleName));
        return;
    }
    
    SelectionEnvironment& env = (*e_it).second;
    
    // Find associated layout from category
    std::map<QString,std::pair<FillingLayout*,QGroupBox*> >::iterator it = env.categories.find(_category);
    if(it == env.categories.end()) {
        // Create new category
        FillingLayout* fillLayout = new FillingLayout(2);
        QGroupBox* group = new QGroupBox(_category);
        group->setLayout(fillLayout);
        // Insert newly created fillLayout into map
        std::pair<std::map<QString,std::pair<FillingLayout*,QGroupBox*> >::iterator,bool> ret;
        ret = env.categories.insert(std::pair<QString,std::pair<FillingLayout*,QGroupBox*> >(_category,
                                            std::pair<FillingLayout*,QGroupBox*>(fillLayout,group)));
        it = ret.first;
        // Add group box to vertical operations layout
        env.operationsBar->addWidget(group);
    }
    
    // Add buttons with function names to operations widget
    for(int i = 0; i < _operationsList.size(); ++i) {
        QPushButton* button = new QPushButton(_operationsList[i]);
        button->setDisabled(true);
        button->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
        int width = button->fontMetrics().width(_operationsList[i]);
        button->setMinimumWidth(width);
        button->setFixedHeight(26);

        connect(button, SIGNAL(clicked()), this, SLOT(slotOperationRequested()));
        // Add operation to local list
        env.operations.insert(std::pair<PrimitiveType,QPushButton*>(_type, button));
        // Add button to operations widget in tool box
        (*it).second.first->addWidget(button);
    }
    // Show operations if in supported primitive type mode
    slotShowAndHideOperations();
}

//============================================================================================

void SelectionBasePlugin::slotOperationRequested() {
    
    QObject* sender = QObject::sender();
    QPushButton* button = 0;
    button = dynamic_cast<QPushButton*>(sender);
    
    if(!button) return;
    
    emit selectionOperation(button->text());
}

//============================================================================================
        
void SelectionBasePlugin::slotShowAndHideOperations() {
    
    for(std::map<QString,SelectionEnvironment>::iterator e_it = selectionEnvironments_.begin();
        e_it != selectionEnvironments_.end(); ++e_it) {
        
        for(std::multimap<PrimitiveType,QPushButton*>::iterator it = (*e_it).second.operations.begin();
            it != (*e_it).second.operations.end(); ++it) {
            
            if((currentPrimitiveType_ & (*it).first) || (*it).first == 0u) {
                // Type is currently active -> show button
                (*it).second->setDisabled(false);
            } else {
                // Type is currently not active -> hide button
                (*it).second->setDisabled(true);
            }
        }
    }
}

//============================================================================================

void SelectionBasePlugin::slotSelectionEnvironmentRequested(bool _checked) {
    
    updatePickModeToolBar();
    
    PluginFunctions::actionMode(Viewer::PickingMode);
    PluginFunctions::pickMode(SELECTION_PICKING);
    
    currentPickMode_ = SELECTION_PICKING;
}

//============================================================================================

void SelectionBasePlugin::slotEnterSelectionMode(bool _checked) {
    
    QObject* obj = QObject::sender();
    HandleAction* act = 0;
    act = dynamic_cast<HandleAction*>(obj);
    
    if(act == 0) return;
    
    // Make button checked
    act->setChecked(_checked);
    
    // Keep active selection mode
    if(_checked) {
        currentSelectionMode_ = act->selectionModeHandle();
    }
    
    // Clear lines
    line_node_->clear();
    linePoints_.clear();
    lassoSelection_ = false;

    if(currentSelectionMode_ == SB_SPHERE) {
        // Adjust sphere radius to have size defined relatively to the scene radius
        sphere_radius_ = 0.03 * PluginFunctions::sceneRadius();
    }
}

//============================================================================================

void SelectionBasePlugin::slotPickModeChanged (const std::string& _pickmode) {
    
    // Test if current pickmode is a selection pick mode
    bool selectionPicking = (_pickmode == "SelectionBasePicking");
     
    // Show/hode line and sphere node
    if(currentSelectionMode_ == SB_SPHERE)
        sphere_node_->show();
    else
        sphere_node_->hide();
    
    if(currentSelectionMode_ == SB_LASSO || currentSelectionMode_ == SB_VOLUME_LASSO)
        line_node_->show();
    else
        line_node_->hide();
    
    bool resetPickToolBar = false;
    
    if(currentPickMode_ != NO_SELECTION_PICKING) {
        // We go into examiner (or some other) mode for the first time
        
        // Just hide line and sphere nodes
        sphere_node_->hide();
        line_node_->hide();
        
        // Save values
        lastPickMode_ = currentPickMode_;
        currentPickMode_ = NO_SELECTION_PICKING;
        
    } else if (selectionPicking && currentPickMode_ == NO_SELECTION_PICKING && lastPickMode_ != NO_SELECTION_PICKING) {
        // We come back from examiner mode (windows key hit)
        
        currentPickMode_ = lastPickMode_;
        
    } else if (!selectionPicking && currentPickMode_ == NO_SELECTION_PICKING) {
        // We go into some other picking mode
        
        // Clear line nodes
        linePoints_.clear();
        line_node_->clear_points();
        
        // A completely different pick mode has been chosen that
        // is not handled by this plugin, so reset current pickmode
        currentPickMode_            = NO_SELECTION_PICKING;
        currentSelectionMode_       = NO_SELECTION_MODE;
        lastPickMode_               = NO_SELECTION_PICKING;
        
        // We don't want no tool to be selected anymore
        resetPickToolBar = true;
        
    } else {
        // We return from some other pickimg mode (or mutliple examiner sessions)
        // to selection mode
        
        lastPickMode_ = currentPickMode_ = _pickmode.c_str();
        
        // Reset pick toolbar
        resetPickToolBar = true;
        
        // Clear line nodes
        linePoints_.clear();
        line_node_->clear_points();
    }
    
    // Make sure that the pick mode buttons are in correct state
    toggleSelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_TOGGLE);
    lassoSelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_LASSO);
    volumeLassoSelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_VOLUME_LASSO);
    surfaceLassoSelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_SURFACE_LASSO);
    sphereSelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_SPHERE);
    boundarySelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_BOUNDARY);
    floodFillSelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_FLOODFILL);
908
    componentsSelectionAction_->setChecked(!resetPickToolBar && currentSelectionMode_ == SB_COMPONENTS);
Jan Möbius's avatar
 
Jan Möbius committed
909
910
911
912
913
914
915
916
917
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    
    for(std::map<QString,SelectionEnvironment>::iterator it = selectionEnvironments_.begin();
        it != selectionEnvironments_.end(); ++it) {
        
        // Custom selection modes
        for(std::set<HandleAction*>::iterator csm_it = (*it).second.customSelectionModes.begin();
            csm_it != (*it).second.customSelectionModes.end(); ++csm_it) {
            (*csm_it)->setChecked(!resetPickToolBar && currentSelectionMode_ == (*csm_it)->selectionModeHandle());
        }
    }

    if(selectionPicking)
        updatePickModeToolBar();
}

//============================================================================================

void SelectionBasePlugin::showSelectionMode(QString _mode, QIcon _icon, QString _desc, QString _handleName,
                                            bool _show, SelectionInterface::PrimitiveType _associatedTypes,
                                            QString& _customIdentifier, bool _custom) {
    
    // Find selection environment that is associated to _handleName
    std::map<QString,SelectionEnvironment>::iterator it = selectionEnvironments_.find(_handleName);
    
    // Return if the requested selection environment was not found
    if(it == selectionEnvironments_.end()) return;
    
    if(!_custom) {
        if(_mode == SB_TOGGLE) {
            if(_show) {
                (*it).second.defaultSelectionModes.insert(toggleSelectionAction_);
                toggleSelectionAction_->addAssociatedType(_associatedTypes);
            } else {
                std::set<HandleAction*>::iterator e = (*it).second.defaultSelectionModes.find(toggleSelectionAction_);
                if(e != (*it).second.defaultSelectionModes.end()) {
                    (*it).second.defaultSelectionModes.erase(e);
                    toggleSelectionAction_->removeAssociatedType(_associatedTypes);
                }
            }
        } else if (_mode == SB_LASSO) {
            if(_show) {
                (*it).second.defaultSelectionModes.insert(lassoSelectionAction_);
                lassoSelectionAction_->addAssociatedType(_associatedTypes);
            } else {
                std::set<HandleAction*>::iterator e = (*it).second.defaultSelectionModes.find(lassoSelectionAction_);
                if(e != (*it).second.defaultSelectionModes.end()) {
                    (*it).second.defaultSelectionModes.erase(e);
                    lassoSelectionAction_->removeAssociatedType(_associatedTypes);
                }
            }
        } else if (_mode == SB_VOLUME_LASSO) {
            if(_show) {
                (*it).second.defaultSelectionModes.insert(volumeLassoSelectionAction_);
                volumeLassoSelectionAction_->addAssociatedType(_associatedTypes);
            } else {
                std::set<HandleAction*>::iterator e = (*it).second.defaultSelectionModes.find(volumeLassoSelectionAction_);
                if(e != (*it).second.defaultSelectionModes.end()) {
                    (*it).second.defaultSelectionModes.erase(e);
                    volumeLassoSelectionAction_->removeAssociatedType(_associatedTypes);
                }
            }
        } else if (_mode == SB_SURFACE_LASSO) {
            if(_show) {
                (*it).second.defaultSelectionModes.insert(surfaceLassoSelectionAction_);
                surfaceLassoSelectionAction_->addAssociatedType(_associatedTypes);
            } else {
                std::set<HandleAction*>::iterator e = (*it).second.defaultSelectionModes.find(surfaceLassoSelectionAction_);
                if(e != (*it).second.defaultSelectionModes.end()) {
                    (*it).second.defaultSelectionModes.erase(e);
                    surfaceLassoSelectionAction_->removeAssociatedType(_associatedTypes);
                }
            }
        } else if (_mode == SB_SPHERE) {
            if(_show) {
                (*it).second.defaultSelectionModes.insert(sphereSelectionAction_);
                sphereSelectionAction_->addAssociatedType(_associatedTypes);
            } else {
                std::set<HandleAction*>::iterator e = (*it).second.defaultSelectionModes.find(sphereSelectionAction_);
                if(e != (*it).second.defaultSelectionModes.end()) {
                    (*it).second.defaultSelectionModes.erase(e);
                    sphereSelectionAction_->removeAssociatedType(_associatedTypes);
                }
            }
        } else if (_mode == SB_BOUNDARY) {
            if(_show) {
                (*it).second.defaultSelectionModes.insert(boundarySelectionAction_);
                boundarySelectionAction_->addAssociatedType(_associatedTypes);
            } else {
                std::set<HandleAction*>::iterator e = (*it).second.defaultSelectionModes.find(boundarySelectionAction_);
                if(e != (*it).second.defaultSelectionModes.end()) {
                    (*it).second.defaultSelectionModes.erase(e);
                    boundarySelectionAction_->removeAssociatedType(_associatedTypes);