WMClusterDisplayVoxels.cpp 39.1 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 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
//---------------------------------------------------------------------------
//
// Project: OpenWalnut ( http://www.openwalnut.org )
//
// Copyright 2009 OpenWalnut Community, BSV-Leipzig and CNCF-CBS
// For more information see http://www.openwalnut.org/copying
//
// This file is part of OpenWalnut.
//
// OpenWalnut 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.
//
// OpenWalnut 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 Lesser General Public License
// along with OpenWalnut. If not, see <http://www.gnu.org/licenses/>.
//
//---------------------------------------------------------------------------

#include <queue>
#include <string>
#include <vector>

#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>
#include <osgViewer/ViewerEventHandlers>
#include <osgWidget/Util> //NOLINT
#include <osgWidget/ViewerEventHandlers> //NOLINT
#include <osgWidget/WindowManager> //NOLINT
#include <osg/LightModel>

#include "../../common/WPathHelper.h"
#include "../../common/WPropertyHelper.h"
#include "../../graphicsEngine/algorithms/WMarchingLegoAlgorithm.h"
40
#include "../../graphicsEngine/WGEUtils.h"
41
#include "../../kernel/WKernel.h"
42
#include "../../kernel/WSelectionManager.h"
43
#include "WFileParser.h"
44
#include "WMClusterDisplayVoxels.h"
45
#include "WMClusterDisplayVoxels.xpm"
46 47 48 49 50 51

// This line is needed by the module loader to actually find your module. Do not remove. Do NOT add a ";" here.
W_LOADABLE_MODULE( WMClusterDisplayVoxels )

WMClusterDisplayVoxels::WMClusterDisplayVoxels():
    WModule(),
52 53
    m_currentDisplayMode( CDV_SINGLE ),
    m_currentDisplayModeString( "" ),
54 55 56
    m_moduleNode( new WGEGroupNode() ),
    m_dendrogramNode( new WGEGroupNode() ),
    m_meshNode( new WGEGroupNode() ),
57
    m_selectionChanged( false ),
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 101 102 103 104 105 106 107 108 109 110 111
    m_dendrogramDirty( false )
{
}

WMClusterDisplayVoxels::~WMClusterDisplayVoxels()
{
    // Cleanup!
}

boost::shared_ptr< WModule > WMClusterDisplayVoxels::factory() const
{
    // See "src/modules/template/" for an extensively documented example.
    return boost::shared_ptr< WModule >( new WMClusterDisplayVoxels() );
}

const char** WMClusterDisplayVoxels::getXPMIcon() const
{
    return clusterDisplayVoxels_xpm;
}
const std::string WMClusterDisplayVoxels::getName() const
{
    // Specify your module name here. This name must be UNIQUE!
    return "ClusterDisplayVoxels";
}

const std::string WMClusterDisplayVoxels::getDescription() const
{
    // Specify your module description here. Be detailed. This text is read by the user.
    // See "src/modules/template/" for an extensively documented example.
    return "Visualizes voxel clusterings in texture and 3D view";
}

void WMClusterDisplayVoxels::connectors()
{
    // the input dataset is just used as source for resolurtion and transformation matrix
    m_input = boost::shared_ptr< WModuleInputData < WDataSetSingle  > >(
        new WModuleInputData< WDataSetSingle >( shared_from_this(), "in", "The input dataset." ) );
    addConnector( m_input );

    m_output = boost::shared_ptr< WModuleOutputData < WDataSetScalar  > >(
        new WModuleOutputData< WDataSetScalar >( shared_from_this(), "out", "The extracted image." ) );
    addConnector( m_output );

    WModule::connectors();
}

void WMClusterDisplayVoxels::properties()
{
    m_propCondition = boost::shared_ptr< WCondition >( new WCondition() );

    m_propClusterFile = m_properties->addProperty( "Cluster file", "", boost::filesystem::path( "/SCR/schurade/data/david/whole/avg.txt" ) );
    m_propReadTrigger = m_properties->addProperty( "Do read",  "Press!", WPVBaseTypes::PV_TRIGGER_READY, m_propCondition );


112 113 114
    // Group selection
    m_groupSelection = m_properties->addPropertyGroup( "Cluster selections",  "Groups the different cluster selection methods" ); //NOLINT

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    m_clusterSelectionsList = boost::shared_ptr< WItemSelection >( new WItemSelection() );
    m_clusterSelectionsList->addItem( "Single", "" );
    m_clusterSelectionsList->addItem( "Biggest", "" );
    m_clusterSelectionsList->addItem( "X Clusters", "" );
    m_clusterSelectionsList->addItem( "Similarity", "" );
    m_clusterSelectionsList->addItem( "Levels from top", "" );
    m_clusterSelectionsList->addItem( "Minimum branch length", "" );
    m_clusterSelectionsList->addItem( "Loaded partition", "" );

    m_clusterSelection = m_groupSelection->addProperty( "Selection method",  "selection",
            m_clusterSelectionsList->getSelectorFirst(), m_propCondition );
    WPropertyHelper::PC_SELECTONLYONE::addTo( m_clusterSelection );



130
    m_propSelectedCluster = m_groupSelection->addProperty( "Selected Cluster", "", 0, m_propCondition );
131 132 133
    m_propSelectedCluster->setMin( 0 );
    m_propSelectedCluster->setMax( 0 );

134
    m_propXBiggestClusters = m_groupSelection->addProperty( "Biggest Clusters", "", 5, m_propCondition );
135 136 137
    m_propXBiggestClusters->setMin( 1 );
    m_propXBiggestClusters->setMax( 1000 );

138
    m_propXClusters = m_groupSelection->addProperty( "X Clusters", "", 5, m_propCondition );
139 140 141
    m_propXClusters->setMin( 1 );
    m_propXClusters->setMax( 1000 );

142
    m_propValue = m_groupSelection->addProperty( "Similarity Value", "", 1.0, m_propCondition );
143 144 145
    m_propValue->setMin( 0.0 );
    m_propValue->setMax( 1.0 );

146 147 148 149 150 151 152
    m_propLevelsFromTop = m_groupSelection->addProperty( "Levels from top", "", 0, m_propCondition );
    m_propHideOutliers = m_groupSelection->addProperty( "Hide outliers", "", false, m_propCondition );

    m_propSelectedLoadedPartion = m_groupSelection->addProperty( "Loaded Partition", "Activates a predetermined partition, loaded from file", 0, m_propCondition ); // NOLINT
    m_propSelectedLoadedPartion->setMin( 1 );
    m_propSelectedLoadedPartion->setMax( 1 );

153
    m_propMinBranchLength = m_groupSelection->addProperty( "Minimum branch length", "", 0.1, m_propCondition );
154 155 156
    m_propMinBranchLength->setMin( 0.0 );
    m_propMinBranchLength->setMax( 1.0 );

157
    m_propMinBranchSize = m_groupSelection->addProperty( "Minimum branch size", "", 50, m_propCondition );
158 159 160
    m_propMinBranchSize->setMin( 1 );
    m_propMinBranchSize->setMax( 500 );

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    m_buttonExecuteSelection = m_groupSelection->addProperty( "Update",  "Press!", WPVBaseTypes::PV_TRIGGER_READY, m_propCondition );

    m_propShowSelectedButtons = m_groupSelection->addProperty( "Show Buttons", "Shows/Hides the buttons for selected cluster on the left side", true, m_propCondition ); //NOLINT

    m_buttonLabelList = boost::shared_ptr< WItemSelection >( new WItemSelection() );
    m_buttonLabelList->addItem( "Number", "" );
    m_buttonLabelList->addItem( "Size", "" );
    m_buttonLabelList->addItem( "Level", "" );
    m_buttonLabelList->addItem( "Similarity", "" );

    m_buttonLabelSelection = m_groupSelection->addProperty( "Button label",  "selection",
                m_buttonLabelList->getSelectorFirst(), m_propCondition );
    WPropertyHelper::PC_SELECTONLYONE::addTo( m_buttonLabelSelection );


176 177 178 179
    //  Group Triangulation
    m_groupTriangulation = m_properties->addPropertyGroup( "Triangulation",  "Groups the triangulation properties" ); //NOLINT
    m_propShowVoxelTriangulation = m_groupTriangulation->addProperty( "Triangulate", "", false, m_propCondition );
    m_showNotInClusters = m_groupTriangulation->addProperty( "Show non active", "", false, m_propCondition );
180

181
    // Group Dendrogram
182 183 184
    m_groupDendrogram = m_properties->addPropertyGroup( "Dendrogram",  "Properties only related to the dendrogram." );

    m_propShowDendrogram = m_groupDendrogram->addProperty( "Show dendrogram", "", true, m_propCondition );
185 186
    m_propPlotHeightByLevel = m_groupDendrogram->addProperty( "Height by Level or Value", "", false, m_propCondition );

187 188 189 190
    m_propMinSizeToColor = m_groupDendrogram->addProperty( "Min size to show", "Specifies a minimum size for a cluster to be drawn", 1, m_propCondition ); // NOLINT
    m_propMinSizeToColor->setMin( 1 );
    m_propMinSizeToColor->setMax( 200 );

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    m_propResizeWithWindow = m_groupDendrogram->addProperty( "Resize with window", "", true, m_propCondition );

    m_propDendrogramSizeX = m_groupDendrogram->addProperty( "Width", "", 100, m_propCondition );
    m_propDendrogramSizeX->setMin( 0 );
    m_propDendrogramSizeX->setMax( 10000 );
    m_propDendrogramSizeY = m_groupDendrogram->addProperty( "Height", "", 100, m_propCondition );
    m_propDendrogramSizeY->setMin( 0 );
    m_propDendrogramSizeY->setMax( 10000 );
    m_propDendrogramOffsetX = m_groupDendrogram->addProperty( "Horizontal position", "", 100, m_propCondition );
    m_propDendrogramOffsetX->setMin( -9000 );
    m_propDendrogramOffsetX->setMax( 1000 );
    m_propDendrogramOffsetY = m_groupDendrogram->addProperty( "Verctical position", "", 100, m_propCondition );
    m_propDendrogramOffsetY->setMin( -9000 );
    m_propDendrogramOffsetY->setMax( 1000 );

206 207 208 209
    m_groupSelection->setHidden( true );
    m_groupTriangulation->setHidden( true );
    m_groupDendrogram->setHidden( true );

210 211 212 213
    m_buttonUpdateOutput = m_properties->addProperty( "Update output", "Updates the output connector",
            WPVBaseTypes::PV_TRIGGER_READY, m_propCondition  );


214
    // Info properties
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    m_infoCountLeafes = m_infoProperties->addProperty( "Count voxels", "", 0 );
    m_infoCountClusters  = m_infoProperties->addProperty( "Count clusters", "", 0 );
    m_infoMaxLevel = m_infoProperties->addProperty( "Max Level", "", 0 );

    WModule::properties();
}

void WMClusterDisplayVoxels::setPropertyBoundaries()
{
    m_propSelectedCluster->setMin( m_tree.getLeafCount() );
    m_propSelectedCluster->setMax( m_tree.getClusterCount() - 1 );

    m_propSelectedCluster->setMin( 0 );
    m_propSelectedCluster->setMax( m_tree.getClusterCount() - 1 );
    m_propSelectedCluster->set( m_tree.getClusterCount() - 1 );

231 232
    m_infoCountLeafes->set( m_tree.getLeafCount() );
    m_infoCountClusters->set( m_tree.getClusterCount() );
233 234
    m_infoMaxLevel->set( m_tree.getMaxLevel() );

235
    m_propMinSizeToColor->setMax( 1000 );
236 237 238 239
    m_rootCluster = m_propSelectedCluster->get();

    m_propLevelsFromTop->setMin( 0 );
    m_propLevelsFromTop->setMax( m_tree.getMaxLevel() );
240 241 242 243 244 245 246 247 248 249

    if ( m_loadedPartitions.empty() )
    {
        m_propSelectedLoadedPartion->setHidden( true );
    }
    else
    {
        m_propSelectedLoadedPartion->setMin( 1 );
        m_propSelectedLoadedPartion->setMax( m_loadedPartitions.size() );
    }
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
}

void WMClusterDisplayVoxels::moduleMain()
{
    boost::signals2::connection con = WKernel::getRunningKernel()->getGraphicsEngine()->getViewer()->getPickHandler()->getPickSignal()->
            connect( boost::bind( &WMClusterDisplayVoxels::dendrogramClick, this, _1 ) );


    m_moduleState.setResetable( true, true );
    m_moduleState.add( m_input->getDataChangedCondition() );
    m_moduleState.add( m_propCondition );
    m_moduleState.add( m_active->getUpdateCondition() );

    ready();

265
    // wait for a dataset to be connected, most likely an anatomy dataset
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    while ( !m_shutdownFlag() )
    {
        m_moduleState.wait();

        if ( m_shutdownFlag() )
        {
            break;
        }

        boost::shared_ptr< WDataSetSingle > newDataSet = m_input->getData();
        bool dataChanged = ( m_dataSet != newDataSet );
        bool dataValid   = ( newDataSet );

        if( dataValid )
        {
            if ( dataChanged )
            {
                m_dataSet = newDataSet;
                m_grid = boost::shared_dynamic_cast< WGridRegular3D >( m_dataSet->getGrid() );
                break;
            }
        }
    }

290
    // wait for a cluster file to be loaded
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    while ( !m_shutdownFlag() )
    {
        m_moduleState.wait();

        if ( m_shutdownFlag() )
        {
            break;
        }

        if ( m_propReadTrigger->get( true ) == WPVBaseTypes::PV_TRIGGER_TRIGGERED )
        {
            boost::filesystem::path fileName = m_propClusterFile->get();
            m_propReadTrigger->set( WPVBaseTypes::PV_TRIGGER_READY, true );

            if ( loadClustering( fileName ) )
            {
                m_propReadTrigger->setHidden( true );
                m_propClusterFile->setHidden( true );
309 310 311 312
                m_groupSelection->setHidden( false );
                m_groupTriangulation->setHidden( false );
                m_groupDendrogram->setHidden( false );

313 314 315 316 317
                break;
            }
        }
    }

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    // initialize
    if ( !m_shutdownFlag() )
    {
        createTexture();
        setPropertyBoundaries();
        initWidgets();

        m_propSelectedCluster->get( true );
        m_propSelectedLoadedPartion->get( true );
        m_propMinSizeToColor->get( true );
        m_propXClusters->get( true );
        m_propXBiggestClusters->get( true );
        m_propValue->get( true );
        m_propMinBranchLength->get( true );
        m_propMinBranchSize->get( true );
        m_propLevelsFromTop->get( true );
334
        m_propHideOutliers->get( true );
335
        m_showNotInClusters->get( true );
336 337

        updateAll();
338
    }
339

340
    // main loop, respond to controls
341 342 343 344 345 346 347 348 349
    while ( !m_shutdownFlag() )
    {
        m_moduleState.wait();

        if ( m_shutdownFlag() )
        {
            break;
        }

350
        if ( m_clusterSelection->changed( true ) )
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
            m_propSelectedCluster->setHidden( true );
            m_propXBiggestClusters->setHidden( true );
            m_propXClusters->setHidden( true );
            m_propValue->setHidden( true );
            m_propLevelsFromTop->setHidden( true );
            m_propHideOutliers->setHidden( true );
            m_propMinBranchLength->setHidden( true );
            m_propMinBranchSize->setHidden( true );
            m_propSelectedLoadedPartion->setHidden( true );

            switch ( m_clusterSelection->get( true ).getItemIndexOfSelected( 0 ) )
            {
                case 0:
                    m_propSelectedCluster->setHidden( false );
                    break;
                case 1:
                    m_propXBiggestClusters->setHidden( false );
                    break;
                case 2:
                    m_propXClusters->setHidden( false );
                    break;
                case 3:
                    m_propValue->setHidden( false );
                    break;
                case 4:
                    m_propLevelsFromTop->setHidden( false );
                    m_propHideOutliers->setHidden( false );
                    break;
                case 5:
                    m_propMinBranchLength->setHidden( false );
                    m_propMinBranchSize->setHidden( false );
                    break;
                case 6:
                    m_propSelectedLoadedPartion->setHidden( false );
                    break;
                default:
                    m_propSelectedCluster->setHidden( false );
                    break;
            }
391 392
        }

393
        if ( m_buttonExecuteSelection->get( true ) == WPVBaseTypes::PV_TRIGGER_TRIGGERED )
394
        {
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
            m_buttonExecuteSelection->set( WPVBaseTypes::PV_TRIGGER_READY, false );
            switch ( m_clusterSelection->get( true ).getItemIndexOfSelected( 0 ) )
            {
                case 0:
                    m_currentDisplayMode = CDV_SINGLE;
                    break;
                case 1:
                    m_currentDisplayMode = CDV_BIGGEST;
                    break;
                case 2:
                    m_currentDisplayMode = CDV_X;
                    break;
                case 3:
                    m_currentDisplayMode = CDV_SIMILARITY;
                    break;
                case 4:
                    m_currentDisplayMode = CDV_LEVELSFROMTOP;
                    break;
                case 5:
                    m_currentDisplayMode = CDV_MINBRANCHLENGTH;
                    break;
                case 6:
                    m_currentDisplayMode = CDV_LOADED;
                    break;
                default:
                    m_currentDisplayMode = CDV_SINGLE;
                    break;
            }
423 424 425
            updateAll();
        }

426
        if( m_propShowVoxelTriangulation->changed( true ) )
427 428 429 430 431
        {
            createMesh();
            renderMesh();
        }

432 433 434 435 436 437
        if ( m_showNotInClusters->changed( true ) )
        {
            updateAll();
        }

        if ( m_propMinSizeToColor->changed( true ) )
438 439 440 441
        {
            handleMinSizeChanged();
        }

442 443 444 445 446
        if ( m_buttonLabelSelection->changed() )
        {
            setButtonLabels();
        }

447 448
        if ( m_propShowDendrogram->changed( true ) || m_propResizeWithWindow->changed( true ) || m_propDendrogramSizeX->changed( true ) ||
                m_propDendrogramSizeY->changed( true ) || m_propDendrogramOffsetX->changed( true ) || m_propDendrogramOffsetY->changed( true ) ||
449
                m_propPlotHeightByLevel->changed( true ) || m_propShowSelectedButtons->changed() )
450 451 452
        {
            m_dendrogramDirty = true;
        }
453 454 455 456 457 458

        if ( m_buttonUpdateOutput->get( true ) == WPVBaseTypes::PV_TRIGGER_TRIGGERED )
        {
            updateOutDataset();
            m_buttonUpdateOutput->set( WPVBaseTypes::PV_TRIGGER_READY, false );
        }
459 460 461 462 463 464 465 466 467
    }

    con.disconnect();

    WKernel::getRunningKernel()->getGraphicsEngine()->getScene()->remove( m_moduleNode );
}

void WMClusterDisplayVoxels::updateAll()
{
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    switch ( m_currentDisplayMode )
    {
        case CDV_SINGLE:
            m_activatedClusters.clear();
            m_activatedClusters.push_back( m_propSelectedCluster->get( true ) );
            m_currentDisplayModeString = std::string( "Single selection" );
            break;
        case CDV_BIGGEST:
            m_activatedClusters = m_tree.findXBiggestClusters2( m_propSelectedCluster->get(), m_propXBiggestClusters->get( true ) );
            m_currentDisplayModeString = std::string( "Biggest clusters" );
            break;
        case CDV_X:
            m_activatedClusters = m_tree.findXClusters( m_propSelectedCluster->get(), m_propXClusters->get( true ) );
            m_currentDisplayModeString = std::string( "X clusters" );
            break;
        case CDV_SIMILARITY:
            m_activatedClusters = m_tree.findClustersForValue( m_propValue->get( true ) );
            m_currentDisplayModeString = std::string( "Similarity value selection" );
            break;
        case CDV_LEVELSFROMTOP:
            m_activatedClusters = m_tree.downXLevelsFromTop( m_propLevelsFromTop->get( true ), m_propHideOutliers->get( true ) );
            m_currentDisplayModeString = std::string( "Levels from top" );
            break;
        case CDV_MINBRANCHLENGTH:
            m_activatedClusters = m_tree.findClustersForBranchLength( m_propMinBranchLength->get( true ), m_propMinBranchSize->get( true ) );
            m_currentDisplayModeString = std::string( "Minimum branch length" );
            break;
        case CDV_LOADED:
            m_activatedClusters = m_loadedPartitions[ m_propSelectedLoadedPartion->get( true ) - 1 ];
            m_currentDisplayModeString = std::string( "Loaded Partition" );
            break;
        default:
            break;
    };


504
    // set colors for cluster in the tree
505 506 507 508
    m_tree.colorCluster( m_tree.getClusterCount() - 1, WColor( 0.3, 0.3, 0.3, 1.0 ) );
    for ( size_t k = 0; k < m_activatedClusters.size(); ++k )
    {
        size_t current = m_activatedClusters[k];
509
        m_tree.colorCluster( current, wge::getNthHSVColor( k ) );
510 511
    }

512
    // redraw the texture
513 514
    m_data.clear();
    m_data.resize( m_grid->size(), 0 );
515 516 517 518 519 520 521 522
    std::vector<size_t> vox = m_tree.getVoxelsForCluster( m_tree.getClusterCount() - 1 );
    if ( m_showNotInClusters->get() )
    {
        for ( size_t k = 0; k < vox.size(); ++k )
        {
            m_data[vox[k]] = 999999;
        }
    }
523 524 525 526 527 528 529 530 531 532 533 534
    for ( size_t i = 0; i < m_activatedClusters.size(); ++i )
    {
        std::vector<size_t> voxels = m_tree.getVoxelsForCluster( m_activatedClusters[i] );

        for ( size_t k = 0; k < voxels.size(); ++k )
        {
            m_data[voxels[k]] = i + 1;
        }
    }
    unsigned char* data = m_texture->getImage()->data();
    for ( size_t i = 0; i < m_grid->size(); ++i )
    {
535 536 537 538 539 540 541
        if ( m_data[i] == 999999 )
        {
            data[i * 3    ] = 75;
            data[i * 3 + 1] = 75;
            data[i * 3 + 2] = 75;
        }
        else if ( m_data[i] != 0 )
542
        {
543
            WColor color = wge::getNthHSVColor( m_data[i] - 1 );
544 545 546
            data[i * 3    ] = color[0] * 255;
            data[i * 3 + 1] = color[1] * 255;
            data[i * 3 + 2] = color[2] * 255;
547 548 549 550 551 552 553 554 555
        }
        else
        {
            data[i * 3    ] = 0.0;
            data[i * 3 + 1] = 0.0;
            data[i * 3 + 2] = 0.0;
        }
    }
    m_texture->dirtyTextureObject();
556

557 558 559
    createMesh();
    renderMesh();

560
    m_selectionChanged = true;
561 562 563 564 565 566 567 568 569 570 571 572
    m_dendrogramDirty = true;
}

void WMClusterDisplayVoxels::handleMinSizeChanged()
{
    m_dendrogramDirty = true;
}

bool WMClusterDisplayVoxels::loadClustering( boost::filesystem::path clusterFile )
{
    debugLog() << "start parsing tree file...";

573 574
    WFileParser parser( clusterFile.string() );
    if ( !parser.readFile() )
575
    {
576
        debugLog() << "parser error";
577 578
        return false;
    }
579 580

    std::vector<std::string>lines = parser.getRawLines();
581 582 583 584 585 586 587

    if ( lines.size() == 0 )
    {
        debugLog() << "file is empty";
        return false;
    }

588
    std::vector< std::vector< std::string> >coords = parser.getLinesForTagSeparated( "coordinates" );
589

590
    for ( size_t i = 0; i < coords.size(); ++i )
591
    {
592 593 594 595 596
        std::vector< std::string > svec = coords[i];

        m_tree.addLeaf( m_grid->getVoxelNum( boost::lexical_cast< size_t >( svec[0] ),
                                             boost::lexical_cast< size_t >( svec[1] ),
                                             boost::lexical_cast< size_t >( svec[2] ) ) );
597
    }
598

599 600 601
    std::vector< std::vector< std::string> >clusters = parser.getLinesForTagSeparated( "clusters" );

    for ( size_t i = 0; i < clusters.size(); ++i )
602
    {
603 604 605 606 607
        std::vector< std::string > svec = clusters[i];

        m_tree.addCluster( boost::lexical_cast< size_t >( svec[0] ),
                           boost::lexical_cast< size_t >( svec[1] ),
                           boost::lexical_cast< float >( svec[2] ) );
608
    }
609 610 611 612

    std::vector< std::vector< std::string> >partitions = parser.getLinesForTagSeparated( "partitions" );

    for ( size_t i = 0; i < partitions.size(); ++i )
613
    {
614
        std::vector< std::string > svec = partitions[i];
615

616
        std::vector<size_t>partition;
617

618 619 620
        for ( size_t k = 0; k < svec.size(); ++k )
        {
            partition.push_back( boost::lexical_cast< size_t >( svec[k] ) );
621
        }
622
        m_loadedPartitions.push_back( partition );
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
    return true;
}

void WMClusterDisplayVoxels::createTexture()
{
     osg::ref_ptr< osg::Image > ima = new osg::Image;
     ima->allocateImage( m_grid->getNbCoordsX(), m_grid->getNbCoordsY(), m_grid->getNbCoordsZ(), GL_RGB, GL_UNSIGNED_BYTE );
     unsigned char* data = ima->data();
     m_data.resize( m_grid->getNbCoordsX() * m_grid->getNbCoordsY() * m_grid->getNbCoordsZ(), 0 );

     for ( unsigned int i = 0; i < m_grid->size() * 3; ++i )
     {
         data[i] = 0.0;
     }

     m_texture = osg::ref_ptr<osg::Texture3D>( new osg::Texture3D );
     m_texture->setFilter( osg::Texture3D::MIN_FILTER, osg::Texture3D::LINEAR );
     m_texture->setFilter( osg::Texture3D::MAG_FILTER, osg::Texture3D::LINEAR );
     m_texture->setWrap( osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER );
     m_texture->setWrap( osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER );
     m_texture->setWrap( osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_BORDER );
     m_texture->setImage( ima );
     m_texture->setResizeNonPowerOfTwoHint( false );

     WKernel::getRunningKernel()->getSelectionManager()->setTexture( m_texture, m_grid );
     WKernel::getRunningKernel()->getSelectionManager()->setShader( 0 );
     WKernel::getRunningKernel()->getSelectionManager()->setUseTexture( true );

     WDataHandler::getDefaultSubject()->getChangeCondition()->notify();
}

void WMClusterDisplayVoxels::createMesh()
{
    m_triMeshes.clear();

    for ( size_t k = 1; k <= m_activatedClusters.size(); ++k )
    {
661 662 663 664 665 666
        WMarchingLegoAlgorithm mlAlgo;
        m_triMeshes.push_back( mlAlgo.genSurfaceOneValue( m_grid->getNbCoordsX(), m_grid->getNbCoordsY(), m_grid->getNbCoordsZ(),
                                            m_grid->getTransformationMatrix(),
                                            &m_data,
                                            k ) );
    }
667

668 669
    if ( m_showNotInClusters->get() )
    {
670
        WMarchingLegoAlgorithm mlAlgo;
671
        m_nonActiveMesh = mlAlgo.genSurfaceOneValue( m_grid->getNbCoordsX(), m_grid->getNbCoordsY(), m_grid->getNbCoordsZ(),
672
                                            m_grid->getTransformationMatrix(),
673 674
                                            &m_data,
                                            999999 );
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
    }
}

void WMClusterDisplayVoxels::renderMesh()
{
    if ( !m_outputGeodes.empty() )
    {
        for ( size_t i = 0; i < m_outputGeodes.size(); ++i )
        {
            m_meshNode->remove( m_outputGeodes[i] );
        }
        m_outputGeodes.clear();
    }

    if ( m_propShowVoxelTriangulation->get( true ) )
    {
        for ( size_t i = 0; i < m_triMeshes.size(); ++i )
        {
            osg::Geometry* surfaceGeometry = new osg::Geometry();
            osg::ref_ptr< osg::Geode >outputGeode = osg::ref_ptr< osg::Geode >( new osg::Geode );

            outputGeode->setName( ( std::string( "cluster" ) + boost::lexical_cast<std::string>( m_activatedClusters[i] ) ).c_str() );

            surfaceGeometry->setVertexArray( m_triMeshes[i]->getVertexArray() );

            // ------------------------------------------------
            // normals
            surfaceGeometry->setNormalArray( m_triMeshes[i]->getTriangleNormalArray() );
            surfaceGeometry->setNormalBinding( osg::Geometry::BIND_PER_PRIMITIVE );

            // ------------------------------------------------
            // colors
            osg::Vec4Array* colors = new osg::Vec4Array;
708
            colors->push_back( wge::getNthHSVColor( i ) );
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
            surfaceGeometry->setColorArray( colors );
            surfaceGeometry->setColorBinding( osg::Geometry::BIND_OVERALL );

            osg::DrawElementsUInt* surfaceElement = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLES, 0 );

            std::vector< size_t >tris = m_triMeshes[i]->getTriangles();
            surfaceElement->reserve( tris.size() );

            for( unsigned int vertId = 0; vertId < tris.size(); ++vertId )
            {
                surfaceElement->push_back( tris[vertId] );
            }
            surfaceGeometry->addPrimitiveSet( surfaceElement );
            outputGeode->addDrawable( surfaceGeometry );

            osg::StateSet* state = outputGeode->getOrCreateStateSet();
            osg::ref_ptr<osg::LightModel> lightModel = new osg::LightModel();
            lightModel->setTwoSided( true );
            state->setAttributeAndModes( lightModel.get(), osg::StateAttribute::ON );
            state->setMode(  GL_BLEND, osg::StateAttribute::ON );

            m_meshNode->insert( outputGeode );
            m_outputGeodes.push_back( outputGeode );
        }
    }
734
    if ( m_propShowVoxelTriangulation->get( true ) && m_showNotInClusters->get() )
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
    {
        osg::Geometry* surfaceGeometry = new osg::Geometry();
        osg::ref_ptr< osg::Geode >outputGeode = osg::ref_ptr< osg::Geode >( new osg::Geode );

        outputGeode->setName( ( std::string( "non active" ) ).c_str() );

        surfaceGeometry->setVertexArray( m_nonActiveMesh->getVertexArray() );

        // ------------------------------------------------
        // normals
        surfaceGeometry->setNormalArray( m_nonActiveMesh->getTriangleNormalArray() );
        surfaceGeometry->setNormalBinding( osg::Geometry::BIND_PER_PRIMITIVE );

        // ------------------------------------------------
        // colors
        osg::Vec4Array* colors = new osg::Vec4Array;

        colors->push_back( osg::Vec4( 0.3, 0.3, 0.3, 1.0f ) );
        surfaceGeometry->setColorArray( colors );
        surfaceGeometry->setColorBinding( osg::Geometry::BIND_OVERALL );

        osg::DrawElementsUInt* surfaceElement = new osg::DrawElementsUInt( osg::PrimitiveSet::TRIANGLES, 0 );

        std::vector< size_t >tris = m_nonActiveMesh->getTriangles();
        surfaceElement->reserve( tris.size() );

        for( unsigned int vertId = 0; vertId < tris.size(); ++vertId )
        {
            surfaceElement->push_back( tris[vertId] );
        }
        surfaceGeometry->addPrimitiveSet( surfaceElement );
        outputGeode->addDrawable( surfaceGeometry );

        osg::StateSet* state = outputGeode->getOrCreateStateSet();
        osg::ref_ptr<osg::LightModel> lightModel = new osg::LightModel();
        lightModel->setTwoSided( true );
        state->setAttributeAndModes( lightModel.get(), osg::StateAttribute::ON );
        state->setMode(  GL_BLEND, osg::StateAttribute::ON );

        m_meshNode->insert( outputGeode );
        m_outputGeodes.push_back( outputGeode );
    }
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
}

void WMClusterDisplayVoxels::initWidgets()
{
    osg::ref_ptr<osgViewer::View> viewer = WKernel::getRunningKernel()->getGraphicsEngine()->getViewer()->getView();

    int height = viewer->getCamera()->getViewport()->height();
    int width = viewer->getCamera()->getViewport()->width();

    m_oldViewHeight = height;
    m_oldViewWidth = width;

    m_moduleNode = osg::ref_ptr< WGEManagedGroupNode >( new WGEManagedGroupNode( m_active ) );
    m_dendrogramNode = osg::ref_ptr< WGEManagedGroupNode >( new WGEManagedGroupNode( m_active ) );
    m_meshNode = osg::ref_ptr< WGEManagedGroupNode >( new WGEManagedGroupNode( m_active ) );
    m_moduleNode->insert( m_dendrogramNode );
    m_moduleNode->insert( m_meshNode );

    m_wm = new osgWidget::WindowManager( viewer, 0.0f, 0.0f, MASK_2D );

    m_camera = new osg::Camera();
    m_camera->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF );

    m_camera->setProjectionMatrix( osg::Matrix::ortho2D( 0.0, width, 0.0f, height ) );
    m_camera->setReferenceFrame( osg::Transform::ABSOLUTE_RF );
    m_camera->setViewMatrix( osg::Matrix::identity() );
    m_camera->setClearMask( GL_DEPTH_BUFFER_BIT );
    m_camera->setRenderOrder( osg::Camera::POST_RENDER );

    m_dendrogramNode->addChild( m_camera );
    m_camera->addChild( m_wm );

    viewer->addEventHandler( new osgWidget::MouseHandler( m_wm ) );
    viewer->addEventHandler( new osgWidget::KeyboardHandler( m_wm ) );
    viewer->addEventHandler( new osgWidget::ResizeHandler( m_wm, m_camera ) );
    viewer->addEventHandler( new osgWidget::CameraSwitchHandler( m_wm, m_camera ) );
    viewer->addEventHandler( new osgViewer::StatsHandler() );
    viewer->addEventHandler( new osgViewer::WindowSizeHandler() );
    viewer->addEventHandler( new osgGA::StateSetManipulator( viewer->getCamera()->getOrCreateStateSet() ) );

    m_wm->resizeAllWindows();

    m_moduleNode->addUpdateCallback( new WGEFunctorCallback< osg::Node >( boost::bind( &WMClusterDisplayVoxels::updateWidgets, this ) ) );
    WKernel::getRunningKernel()->getGraphicsEngine()->getScene()->insert( m_moduleNode );
}

void WMClusterDisplayVoxels::updateWidgets()
{
    osg::ref_ptr<osgViewer::View> viewer = WKernel::getRunningKernel()->getGraphicsEngine()->getViewer()->getView();

    int height = viewer->getCamera()->getViewport()->height();
    int width = viewer->getCamera()->getViewport()->width();

830 831
    int rows = ( height - 20 ) / 20;
    int buttonWidth = 70;
832

833 834 835 836 837 838 839 840
    if ( ( height != m_oldViewHeight ) || width != m_oldViewWidth )
    {
        m_oldViewHeight = height;
        m_oldViewWidth = width;

        m_dendrogramDirty = true;
    }

841 842 843
    bool buttonClicked = widgetClicked();

    if ( !buttonClicked && !m_dendrogramDirty )
844 845 846 847
    {
        return;
    }

848
    if ( m_selectionChanged || m_propShowSelectedButtons->changed() || m_dendrogramDirty )
849 850 851 852 853 854 855
    {
        for ( size_t i = 0; i < m_activeClustersButtonList.size(); ++i )
        {
            m_wm->removeChild( m_activeClustersButtonList[i] );
        }

        m_activeClustersButtonList.clear();
856

857
        if ( m_propShowSelectedButtons->get( true ) )
858
        {
859 860 861
            for ( size_t i = 0; i < m_activatedClusters.size(); ++i )
            {
                osg::ref_ptr<WOSGButton> newButton = osg::ref_ptr<WOSGButton>( new WOSGButton( std::string( "" ),
862
                        osgWidget::Box::VERTICAL, true, true ) );
863
                newButton->setPosition( osg::Vec3( 5.f + ( i / rows ) * buttonWidth,  ( i % rows ) * 20.f, 0 ) );
864 865 866 867 868 869 870 871
                newButton->setId( m_activatedClusters[i] );
                newButton->managed( m_wm );
                m_wm->addChild( newButton );
                m_activeClustersButtonList.push_back( newButton );
                newButton->setBackgroundColor( wge::getNthHSVColor( i ) );
            }
        }

872 873 874 875 876 877 878 879 880 881 882 883
        setButtonLabels();

        osg::ref_ptr<WOSGButton> newButton = osg::ref_ptr<WOSGButton>( new WOSGButton( std::string( "" ),
                                osgWidget::Box::VERTICAL, true, true ) );
        newButton->setPosition( osg::Vec3( 5.f, height - 20.f, 0 ) );
        newButton->setId( 0 );
        newButton->setLabel( m_currentDisplayModeString );
        newButton->managed( m_wm );
        m_wm->addChild( newButton );
        m_activeClustersButtonList.push_back( newButton );
        newButton->setBackgroundColor( wge::getNthHSVColor( m_currentDisplayMode ) );

884
        m_selectionChanged = false;
885 886 887
    }
    m_wm->resizeAllWindows();

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    if ( m_propShowSelectedButtons && buttonClicked )
    {
        m_tree.colorCluster( m_tree.getClusterCount() - 1, WColor( 0.3, 0.3, 0.3, 1.0 ) );
        for ( size_t k = 0; k < m_activatedClusters.size(); ++k )
        {
            if ( m_activeClustersButtonList[k]->pushed() )
            {
                size_t current = m_activatedClusters[k];
                m_tree.colorCluster( current, wge::getNthHSVColor( k ) );
            }
        }
        m_dendrogramDirty = true;
    }



904 905 906 907 908 909 910 911 912 913 914 915 916 917
    if ( m_dendrogramDirty )
    {
        m_camera->removeChild( m_dendrogramGeode );
        //m_camera->removeChild( 1, 1 );

        int dwidth = m_propDendrogramSizeX->get( true );
        int dheight = m_propDendrogramSizeY->get( true );
        int dxOff = m_propDendrogramOffsetX->get( true );
        int dyOff = m_propDendrogramOffsetY->get( true );

        if ( m_propShowDendrogram->get( true ) )
        {
            if ( m_propResizeWithWindow->get( true ) )
            {
918 919 920
                if ( m_propShowSelectedButtons->get() )
                {
                    m_dendrogramGeode = new WDendrogramGeode( &m_tree, m_tree.getClusterCount() - 1, m_propPlotHeightByLevel->get( true ),
921 922
                                        m_propMinSizeToColor->get(), width - ( ( m_activatedClusters.size() / rows ) + 1 ) * buttonWidth, height / 2 ,
                                        ( ( m_activatedClusters.size() / rows ) + 1 ) * buttonWidth );
923 924 925 926 927 928
                }
                else
                {
                    m_dendrogramGeode = new WDendrogramGeode( &m_tree, m_tree.getClusterCount() - 1, m_propPlotHeightByLevel->get( true ),
                                            m_propMinSizeToColor->get(), width - 20, height / 2 , 10 );
                }
929 930 931
            }
            else
            {
932
                m_dendrogramGeode = new WDendrogramGeode( &m_tree, m_tree.getClusterCount() - 1, m_propPlotHeightByLevel->get( true ),
933 934 935 936 937 938 939 940 941 942 943
                        m_propMinSizeToColor->get(), dwidth, dheight, dxOff, dyOff );
            }
            m_camera->addChild( m_dendrogramGeode );
        }
        m_dendrogramDirty = false;
    }
}

bool WMClusterDisplayVoxels::widgetClicked()
{
    bool clicked = false;
944
    bool selectionChanged = false;
945 946 947 948 949 950 951

    for ( size_t i = 0; i < m_activeClustersButtonList.size(); ++i )
    {
        if ( m_activeClustersButtonList[i]->clicked() )
        {
            if ( m_activeClustersButtonList[i]->getId() < 10000000 )
            {
952
                selectionChanged = true;
953 954 955 956 957
                clicked = true;
            }
        }
    }

958
    if ( selectionChanged )
959 960 961 962 963 964
    {
        std::vector<size_t>activeClusters;
        for ( size_t i = 0; i < m_activeClustersButtonList.size(); ++i )
        {
            if ( m_activeClustersButtonList[i]->pushed() )
            {
965 966 967 968 969 970 971 972 973 974 975
                if ( m_outputGeodes.size() > i )
                {
                    m_outputGeodes[i]->setNodeMask( 0xFFFFFFFF );
                }
            }
            else
            {
                if ( m_outputGeodes.size() > i )
                {
                    m_outputGeodes[i]->setNodeMask( 0x00000000 );
                }
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
            }
        }
    }
    return clicked;
}

void WMClusterDisplayVoxels::dendrogramClick( WPickInfo pickInfo )
{
    if ( !m_propShowDendrogram->get() || !( pickInfo.getName() == "nothing" ) )
    {
        return;
    }
    int x = pickInfo.getPickPixelPosition().first;
    int y = pickInfo.getPickPixelPosition().second;

991 992 993
    size_t cluster = m_dendrogramGeode->getClickedCluster( x, y );
    std::cout << cluster << std::endl;
    m_propSelectedCluster->set( cluster );
994
}
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 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

void WMClusterDisplayVoxels::updateOutDataset()
{
    WAssert( m_dataSet, "" );
    WAssert( m_dataSet->getValueSet(), "" );
    WAssert( m_dataSet->getGrid(), "" );

    boost::shared_ptr< std::vector< float > >ptr( new std::vector< float >( m_data.size() ) );

    for ( size_t i = 0; i < m_data.size(); ++i )
    {
        ptr->at( i ) = static_cast<float>( m_data[i] );
    }

    boost::shared_ptr< WValueSet< float > > vs =
        boost::shared_ptr< WValueSet< float > >( new WValueSet< float >( 0, 1, ptr, W_DT_FLOAT ) );

    m_outData = boost::shared_ptr< WDataSetScalar >( new WDataSetScalar( vs, m_grid ) );
    m_output->updateData( m_outData );
}

void WMClusterDisplayVoxels::setButtonLabels()
{
    if ( m_propShowSelectedButtons->get() )
    {
        std::string ns;
        for ( size_t i = 0; i < m_activatedClusters.size(); ++i )
        {
            if ( m_buttonLabelSelection->get( true ).getItemIndexOfSelected( 0 ) == 0 )
            {
                ns = boost::lexical_cast<std::string>( m_activatedClusters[i] );
            }
            else if ( m_buttonLabelSelection->get( true ).getItemIndexOfSelected( 0 ) == 1 )
            {
                ns = boost::lexical_cast<std::string>( m_tree.size( m_activatedClusters[i] ) );
            }
            else if ( m_buttonLabelSelection->get( true ).getItemIndexOfSelected( 0 ) == 2 )
            {
                ns = boost::lexical_cast<std::string>( m_tree.getLevel( m_activatedClusters[i] ) );
            }
            else
            {
                ns = boost::lexical_cast<std::string>( m_tree.getCustomData( m_activatedClusters[i] ) );
                if ( ns.size() > 8 )
                {
                    ns = ns.substr( 0, 8 );
                }
            }


            for ( size_t k = 8 - ns.size(); k > 0; --k )
            {
                if ( k %2 == 1 )
                {
                    ns = std::string( " " ) + ns;
                }
                else
                {
                    ns = ns + std::string( " " );
                }
            }
            if ( m_activeClustersButtonList.size() > i )
            {
                m_activeClustersButtonList[i]->setLabel( ns );
            }
        }
    }
}