WIGTLinkRemote.cpp 17.5 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 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 137 138 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 167 168 169 170 171 172 173 174 175 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 205 206 207 208 209 210 211 212 213 214 215 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
//---------------------------------------------------------------------------
//
// Project: OpenWalnut ( http://www.openwalnut.org )
//
// Copyright 2009 OpenWalnut Community, BSV@Uni-Leipzig and CNCF@MPI-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 <iostream>
#include <string>
#include <vector>

#include "WIGTLinkRemote.h"

#include "core/dataHandler/WDataSet.h"
#include "core/dataHandler/WValueSet.h"
#include "core/dataHandler/WGridRegular3D.h"
#include "core/dataHandler/WDataSetScalar.h"
#include "core/common/WIOTools.h"
#include "core/common/WLogger.h"

#include "igtlOSUtil.h"
#include "igtlImageMessage.h"
#include "igtlImageMetaMessage.h"
#include "igtlServerSocket.h"
#include "igtlTransformMessage.h"

WIGTLinkRemote::WIGTLinkRemote()
    : checkCRC( false ), port( 0 )
{
    receiversCondition.reset( new WCondition );
    statusCondition.reset( new WCondition );
}

WIGTLinkRemote::~WIGTLinkRemote()
{
    receiversMutex.lock();
    //receiveQueue.clear();
    receiversCondition->notify();
    receiversMutex.unlock();
    if( socket.IsNotNull() )
    {
        socket->CloseSocket();
    }
}

void WIGTLinkRemote::createSocketAndWaitForConnection( uint32_t port )
{
    this->port = port;
}

void WIGTLinkRemote::createSocketAndConnect( std::string hostname, uint32_t port )
{
    std::cout << "setting up connection to: \"" <<  hostname << ":" <<  port <<  "\"" << std::endl;
    this->port = 0;
    socket = igtl::ClientSocket::New();
    int r =  socket->ConnectToServer( hostname.c_str(), port );
    if( r != 0 )
    {
        throw WException( "Cannot connect to server" );
    }
    std::cout << "connection established" <<  std::endl;
    statusCondition->notify(); // link established
}

void WIGTLinkRemote::threadMain()
{
    readDataLoop();
}

void WIGTLinkRemote::listenLoop()
{
    igtl::ServerSocket::Pointer serverSocket;
    serverSocket = igtl::ServerSocket::New();
    serverSocket->CreateServer( port );

    // wait for connection
    while( !m_shutdownFlag() && socket.IsNull() )
    {
        socket = serverSocket->WaitForConnection( 2000 );
    }
    if( !m_shutdownFlag() && socket.IsNotNull() )
    {
        statusCondition->notify(); // passive connection established
    }
}

void WIGTLinkRemote::readDataLoop()
{
    igtl::MessageHeader::Pointer headerMsg;
    headerMsg = igtl::MessageHeader::New();

    headerMsg->InitPack();

    if( port > 0 )
    {
        listenLoop();
    }

    WAssert( socket.IsNotNull(), "Something failed when setting up the socket" );

    while( !m_shutdownFlag() )
    {
        try
        {
            std::cout << "Waiting for data." <<  std::endl;
            int r = socket->Receive( headerMsg->GetPackPointer(), headerMsg->GetPackSize() );
            if( r == 0 )
            {
                // socket failed!!!
                throw WException( "Socket Failed" );
            }
            std::cout << "got something." <<  std::endl;

            if( r !=  headerMsg->GetPackSize() )
            {
                throw WException( "Invalid data size" );
            }

            // deserialize the header
            headerMsg->Unpack( checkCRC ? 1:0 );

            // check data type
            if( strcmp( headerMsg->GetDeviceType(), "TRANSFORM" ) == 0 )
            {
                //debugLog() << "Received TRANSFORM";
                receiveTransform( headerMsg );
            }
            else if( strcmp( headerMsg->GetDeviceType(), "IMAGE" ) == 0 )
            {
                std::cout << "got an image!!!" << std::endl;
                WDataSetScalarSPtr ds = receiveImage( headerMsg );
                receiversMutex.lock();
                receiveQueue.push( ds );
                receiversCondition->notify();
                receiversMutex.unlock();
            }
            else if( strcmp( headerMsg->GetDeviceType(), "POSITION" ) ==  0 )
            {
                //readPosition( headerMsg );
                socket->Skip( headerMsg->GetBodySizeToRead(), 0 );
            }
            else if( strcmp( headerMsg->GetDeviceType(), "STATUS" ) == 0 )
            {
                //readStatus( headerMsg );
                socket->Skip( headerMsg->GetBodySizeToRead(), 0 );
            }
            else
            {
                //debugLog() << "Unknown header received";
                socket->Skip( headerMsg->GetBodySizeToRead(), 0 );
            }
        }
        catch( const std::exception &e )
        {
            if( socket.IsNotNull() )
            {
                socket->CloseSocket();
            }
            if( port == 0 )
            {
                // we are in client mode and the connection failed
                // notify the main program and quit this thread
                // we have to start a new connection if this happens
                throw e;
            }
            else
            {
                // just continue listening
                socket = igtl::ClientSocket::Pointer();
                listenLoop();
            }
        }
    }
}

void WIGTLinkRemote::receiveTransform( igtl::MessageHeader::Pointer headerMsg )
{
    // TODO(mario): OpenWalnut needs a nice interface for transforms to display tracking devices etc

    // message body handler for transform
    igtl::TransformMessage::Pointer transMsg;
    transMsg =  igtl::TransformMessage::New();
    transMsg->SetMessageHeader( headerMsg );
    transMsg->AllocatePack();

    socket->Receive( transMsg->GetPackBodyPointer(), transMsg->GetPackBodySize() );

    // deserialize the message body
    int c =  transMsg->Unpack( checkCRC ? 1:0 ); // 1 indicates to perform CRC
    if( c & igtl::MessageHeader::UNPACK_BODY )
    {
        // if CRC check is OK, read transform data
        igtl::Matrix4x4 matrix;
        transMsg->GetMatrix( matrix );

        // TODO(mario): add better debugging
        igtl::PrintMatrix( matrix );
    }
}

WDataSetScalarSPtr WIGTLinkRemote::receiveImage( igtl::MessageHeader::Pointer headerMsg )
{
    igtl::ImageMessage::Pointer imgMsg;
    imgMsg = igtl::ImageMessage::New();
    imgMsg->SetMessageHeader( headerMsg );
    imgMsg->AllocatePack();

    // receive data from socket
    socket->Receive( imgMsg->GetPackBodyPointer(), imgMsg->GetPackBodySize() );

    // deserialize the data
    int c =  imgMsg->Unpack( checkCRC ? 1:0 ); // 1 stands for do CRC

    if( c & igtl::MessageHeader::UNPACK_BODY )
    {
        int size[ 3 ];
        float spacing[ 3 ];
        int svsize[ 3 ];
        int svoffset[ 3 ];
        igtl::Matrix4x4 mat;

        imgMsg->GetDimensions( size );
        imgMsg->GetSpacing( spacing );
        imgMsg->GetSubVolume( svsize, svoffset );
        imgMsg->GetMatrix( mat );

        WMatrix<double> owmat( 4, 4 );
        for( int i = 0; i < 4; ++i )
        {
            for( int j = 0; j < 4; ++j )
            {
                owmat( i, j ) = mat[ i ][ j ];
            }
        }
        WGridRegular3D::SPtr grid( new WGridRegular3D( size[ 0 ], size[ 1 ], size[ 2 ], WGridTransformOrtho( owmat ) ) );

        boost::shared_ptr< WValueSetBase > valueSet = createValueSet( imgMsg );

        WDataSetScalarSPtr ds( new WDataSetScalar( valueSet, grid ) );
        // if( length( imgMsg->GetDeviceName() > 0 ) )
        // {
259
        //    ds->setFilename( imgMsg->GetDeviceName() );
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
        // }

        return ds;
    }
    else
    {
        std::cerr << "decoding image failed" << std::endl;
    }
    return WDataSetScalarSPtr ();
}

void WIGTLinkRemote::injectMessage()
{
}

void WIGTLinkRemote::sendTransform( const std::string& name, const WMatrix<double> & matrix )
{
    if( socket.IsNotNull() )
    {
        igtl::TransformMessage::Pointer transMsg;
        transMsg = igtl::TransformMessage::New();
        transMsg->SetDeviceName( name.c_str() );
        igtl::Matrix4x4 igtlMatrix;
        for( int i = 0; i < 4; ++i )
        {
            for( int j = 0; j < 4; ++j )
            {
                igtlMatrix[ i ][ j ] =  matrix( i, j );
            }
        }
        transMsg->SetMatrix( igtlMatrix );

        transMsg->Pack();

        socket->Send( transMsg->GetPackPointer(), transMsg->GetPackSize() );
    }
}

namespace
{
    int convertTypeOWtoIGTL( int type )
    {
        switch( type )
        {
            case igtl::ImageMessage::TYPE_INT8:
                    return W_DT_INT8;
            case igtl::ImageMessage::TYPE_UINT8:
                    return W_DT_UINT8;
            case igtl::ImageMessage::TYPE_INT16:
                    return W_DT_INT16;
            case igtl::ImageMessage::TYPE_UINT16:
                    return W_DT_UINT16;
            case igtl::ImageMessage::TYPE_INT32:
                    return W_DT_INT16;
            case igtl::ImageMessage::TYPE_UINT32:
                    return W_DT_UINT32;
            default:
                // TODO(mario): throw exception?
                return W_DT_UNKNOWN;
        }
    }
}

void WIGTLinkRemote::sendImageMetaData( const std::vector < WDataSetScalarSPtr >& dataSets )
{
    igtl::ImageMetaMessage::Pointer imgMetaMsg;
    imgMetaMsg =  igtl::ImageMetaMessage::New();

    imgMetaMsg->SetDeviceName( "OpenWalnut" );

    // create meta data for each data set
    for( size_t i = 0; i < dataSets.size(); ++i )
    {
        igtl::ImageMetaElement::Pointer imgMeta;
        imgMeta = igtl::ImageMetaElement::New();
335 336
        imgMeta->SetName( dataSets[ i ]->getFilename().c_str() );
        imgMeta->SetDeviceName( dataSets[ i ]->getFilename().c_str() );
337
        imgMeta->SetModality( "UNKNOWN_MODALITY" );
338
        imgMeta->SetPatientName( dataSets[ i ]->getFilename().c_str() );
339 340 341 342 343 344 345
        imgMeta->SetPatientID( "PATIENT_ID_0" );

        igtl::TimeStamp::Pointer ts0;
        ts0 = igtl::TimeStamp::New();
        ts0->SetTime( 123456.78 );

        imgMeta->SetTimeStamp( ts0 );
346
        boost::shared_ptr < WGridRegular3D > g3dr( boost::dynamic_pointer_cast < WGridRegular3D > ( dataSets[ i ]->getGrid() ) );
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        imgMeta->SetSize( g3dr->getNbCoordsX(), g3dr->getNbCoordsY(), g3dr->getNbCoordsZ() );
        imgMeta->SetScalarType( convertTypeOWtoIGTL( dataSets[ i ]->getValueSet()->getDataType() ) );
        imgMetaMsg->AddImageMetaElement( imgMeta );
    }
    imgMetaMsg->Pack();

    socket->Send( imgMetaMsg->GetPackPointer(), imgMetaMsg->GetPackSize() );
}

namespace Ugly
{
    template < int DT >
    size_t getRawSizeT( boost::shared_ptr < WValueSetBase >  valueSet )
    {
        typedef typename DataTypeRT<DT>::type type;
362
        boost::shared_ptr < WValueSet < type > > v = boost::dynamic_pointer_cast < WValueSet < type > >( valueSet );
363 364 365 366 367 368 369 370 371
        WAssert( v, "Type cast failed" );
        return valueSet->rawSize() * sizeof( type );
    }

    template < int DT >
    const void* getRawPtrT( boost::shared_ptr < WValueSetBase > valueSet )
    {
        typedef typename DataTypeRT<DT>::type type;
        boost::shared_ptr < WValueSet < type > > v;
372
        v = boost::dynamic_pointer_cast < WValueSet < type > >( valueSet );
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 407 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 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        WAssert( v, "Type cast failed" );
        const void* ptr = v->rawData();
        WAssert( ptr != 0, "Trying to query raw data, got null pointer" );
        return ptr;
    }

    size_t getRawSize( boost::shared_ptr < WValueSetBase > valueSet )
    {
        int type = valueSet->getDataType();
#define CASE( A ) case A: return getRawSizeT < A > ( valueSet );
        switch( type )
        {
            CASE( W_DT_UNSIGNED_CHAR );
            CASE( W_DT_INT8 );
            CASE( W_DT_SIGNED_SHORT ); // INT16
            CASE( W_DT_SIGNED_INT ); // INT32
            CASE( W_DT_FLOAT );
            CASE( W_DT_DOUBLE );
            CASE( W_DT_UINT16 );
            CASE( W_DT_UINT32 );
            CASE( W_DT_INT64 );
            CASE( W_DT_UINT64 );
            CASE( W_DT_FLOAT128 );
            default:
                throw WException( "Not implemented for given data type" );
        }
#undef CASE
    }

    const void* getRawPtr( boost::shared_ptr < WValueSetBase > valueSet )
    {
        int type = valueSet->getDataType();
#define CASE( A ) case A: return getRawPtrT < A > ( valueSet );
        switch( type )
        {
            CASE( W_DT_UNSIGNED_CHAR );
            CASE( W_DT_INT8 );
            CASE( W_DT_SIGNED_SHORT ); // INT16
            CASE( W_DT_SIGNED_INT ); // INT32
            CASE( W_DT_FLOAT );
            CASE( W_DT_DOUBLE );
            CASE( W_DT_UINT16 );
            CASE( W_DT_UINT32 );
            CASE( W_DT_INT64 );
            CASE( W_DT_UINT64 );
            CASE( W_DT_FLOAT128 );
            default:
                throw WException( "Not implemented for given data type" );
        }
#undef CASE
    }
}

void WIGTLinkRemote::sendImageData( WDataSetScalarSPtr dataSetScalar )
{
    boost::shared_ptr< WValueSetBase > valueSet = dataSetScalar->getValueSet();
    //size_t rawSize = valueSet->rawSize();

    int scalarType = 0;
    switch( valueSet->getDataType() )
    {
        case W_DT_FLOAT:
            scalarType = igtl::ImageMessage::TYPE_FLOAT32;
            break;
        case W_DT_DOUBLE:
            scalarType = igtl::ImageMessage::TYPE_FLOAT64;
            break;
        case W_DT_UINT16:
            scalarType = igtl::ImageMessage::TYPE_UINT16;
            break;
        case W_DT_UINT32:
            scalarType = igtl::ImageMessage::TYPE_UINT32;
            break;
        case W_DT_UNSIGNED_CHAR:
            scalarType = igtl::ImageMessage::TYPE_UINT8;
            break;
        case W_DT_INT8:
            scalarType = igtl::ImageMessage::TYPE_INT8;
            break;
        case W_DT_INT64:
        case W_DT_FLOAT128:
            throw WException( "Unsupported scalar type: not supported by igtl?" );
            break;
        case W_DT_SIGNED_INT:
            scalarType = igtl::ImageMessage::TYPE_INT32;
            break;
        case W_DT_SIGNED_SHORT:
            scalarType = igtl::ImageMessage::TYPE_INT16;
            break;
        case W_DT_BINARY:
        case W_DT_UINT64:
            throw WException( "Unsupported scalar type" );
            break;
        case W_DT_RGB:
        case W_DT_RGBA32:
            throw WException( "RGB not supported" );
            break;
        case W_DT_COMPLEX:
        case W_DT_COMPLEX128:
        case W_DT_COMPLEX256:
            throw WException( "Complex types are not supported, yet" );
            break;
        case W_DT_NONE:
            throw WException( "W_DT_NONE should never occur as a type." );
            break;
        case W_DT_ALL:
            throw WException( "W_DT_ALL should never occur as a type." );
            break;
    }

    if( socket.IsNotNull() )
    {
        int size[ 3 ];
486
        boost::shared_ptr < WGridRegular3D > g3dr( boost::dynamic_pointer_cast < WGridRegular3D > ( dataSetScalar->getGrid() ) );
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        size[ 0 ] = g3dr->getNbCoordsX();
        size[ 1 ] = g3dr->getNbCoordsY();
        size[ 2 ] = g3dr->getNbCoordsZ();

        int svsize[ 3 ] = { size[ 0 ], size[ 1 ], size[ 2 ]};
        int svoffset[] = { 0, 0, 0 };

        igtl::ImageMessage::Pointer imgMsg =  igtl::ImageMessage::New();
        imgMsg->SetDimensions( size );
        imgMsg->SetSpacing( g3dr->getOffsetX(), g3dr->getOffsetY(), g3dr->getOffsetZ() );
        imgMsg->SetDeviceName( "OpenWalnut" );
        imgMsg->SetSubVolume( svsize, svoffset );
        imgMsg->SetScalarType( scalarType );
        imgMsg->AllocateScalars();

        size_t rawsize =  Ugly::getRawSize( valueSet );
        std::cout << "Transfering " << rawsize << " = " << imgMsg->GetImageSize() << " bytes of data." << std::endl;
        memcpy( imgMsg->GetScalarPointer(), Ugly::getRawPtr( valueSet ), rawsize );

        igtl::Matrix4x4 matrix;
        igtl::IdentityMatrix( matrix );
        imgMsg->SetMatrix( matrix ); // TODO(mario): get the matrix from the data set
        imgMsg->Pack();

        socket->Send( imgMsg->GetPackPointer(), imgMsg->GetPackSize() );
    }
}

boost::shared_ptr < WValueSetBase > WIGTLinkRemote::createValueSet( const igtl::ImageMessage::Pointer& imgMsg )
{
    boost::shared_ptr<WValueSetBase> valueSet;
    int size[ 3 ];
    imgMsg->GetDimensions( size );
    size_t sz =  size[ 0 ] * size[ 1 ] * size[ 2 ];
#define CASE( igtltype, ctype, owtype )\
    case igtltype: \
            {\
                boost::shared_ptr < std::vector < ctype > > values( new std::vector < ctype >( sz ) );\
                memcpy( ( void* )&( ( *values )[ 0 ] ), imgMsg->GetScalarPointer(), sizeof( ctype ) * sz );\
                valueSet.reset( new WValueSet < ctype >( 0, 1, values, owtype ) );\
            }\
            break

     switch( imgMsg->GetScalarType() )
    {
        CASE( igtl::ImageMessage::TYPE_INT8, int8_t, W_DT_INT8 );
        CASE( igtl::ImageMessage::TYPE_UINT8, uint8_t, W_DT_UINT8 );
        CASE( igtl::ImageMessage::TYPE_INT16, int16_t, W_DT_INT16 );
        CASE( igtl::ImageMessage::TYPE_UINT16, uint16_t, W_DT_UINT16 );
        CASE( igtl::ImageMessage::TYPE_INT32, int32_t, W_DT_SIGNED_INT );
        CASE( igtl::ImageMessage::TYPE_UINT32, uint32_t, W_DT_UINT32 );
         default:
            break;
            // TODO(mario): throw exception?
    }
#undef CASE
    return valueSet;
}