FileVTK.cc 99.2 KB
Newer Older
1 2 3
/*===========================================================================*\
*                                                                            *
*                              OpenFlipper                                   *
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
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
39 40 41
*                                                                            *
\*===========================================================================*/

Jan Möbius's avatar
Jan Möbius committed
42

43

44 45
#include "FileVTK.hh"

46 47 48
#include <QVBoxLayout>
#include <QPushButton>

49
#ifdef ENABLE_HEXAHEDRALMESH_SUPPORT
50
#endif
51
#ifdef ENABLE_POLYHEDRALMESH_SUPPORT
52 53
#endif

54

55

56
//-----------------------------------------------------------------------------------------------------
57 58 59 60 61
void remove_duplicated_vertices(std::vector<quint32>& _indices)
{
  std::vector<quint32>::iterator endIter = _indices.end();
  for (std::vector<quint32>::iterator iter = _indices.begin(); iter != endIter; ++iter)
    endIter = std::remove(iter+1, endIter, *(iter));
62

63
  _indices.erase(endIter,_indices.end());
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
//-----------------------------------------------------------------------------------------------------

/// Constructor
FileVTKPlugin::FileVTKPlugin():
  forceTriangleMesh_(false),
  forcePolyMesh_(false),
  saveOptions_(0),
  saveBinary_(0),
  saveFaceNormals_(0),
  saveVertexNormals_(0),
  saveVertexTexCoords_(0),
  savePrecisionLabel_(0),
  savePrecision_(0),
  saveDefaultButton_(),
  binary_(false),
  userWriteOptions_(0)
{
}

//-----------------------------------------------------------------------------------------------------

void FileVTKPlugin::initializePlugin() {

    if(OpenFlipperSettings().value("FileVtk/Save/Binary",false).toBool())
        userWriteOptions_ |= BINARY; //currently unsupported
    if(OpenFlipperSettings().value("FileVtk/Save/FaceNormals",true).toBool())
        userWriteOptions_ |= FACENORMALS;
    if(OpenFlipperSettings().value("FileVtk/Save/VertexNormals",true).toBool())
        userWriteOptions_ |= VERTEXNORMALS;
    if(OpenFlipperSettings().value("FileVtk/Save/VertexTexCoords",true).toBool())
        userWriteOptions_ |= VERTEXTEXCOORDS;
}

//-----------------------------------------------------------------------------------------------------

QString FileVTKPlugin::getLoadFilters() {
    return QString( tr("Visualization Toolkit ASCII ( *.vtk )") );
103
}
104 105 106 107 108

//-----------------------------------------------------------------------------------------------------

QString FileVTKPlugin::getSaveFilters() {
   return QString( tr("Visualization Toolkit ASCII ( *.vtk )") );
109
}
110 111 112 113 114 115

//-----------------------------------------------------------------------------------------------------

DataType  FileVTKPlugin::supportedType() {
    DataType type = DATA_POLY_MESH | DATA_TRIANGLE_MESH | DATA_GROUP;

116
#ifdef ENABLE_POLYHEDRALMESH_SUPPORT
117 118
    type |= DATA_POLYHEDRAL_MESH;
#endif
119
#ifdef ENABLE_HEXAHEDRALMESH_SUPPORT
120 121
    type |= DATA_HEXAHEDRAL_MESH;
#endif
122
#ifdef ENABLE_TETRAHEDRALMESH_SUPPORT
Max Lyon's avatar
Max Lyon committed
123 124
    type |= DATA_TETRAHEDRAL_MESH;
#endif
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
    return type;
}

//-----------------------------------------------------------------------------------------------------

QWidget* FileVTKPlugin::loadOptionsWidget(QString /*_currentFilter*/) {
  return 0;
}

//-----------------------------------------------------------------------------------------------------

QWidget* FileVTKPlugin::saveOptionsWidget(QString /*_currentFilter*/) {

    if (saveOptions_ == 0){
        //generate widget
        saveOptions_ = new QWidget();
        QVBoxLayout* layout = new QVBoxLayout();
        layout->setAlignment(Qt::AlignTop);

        saveBinary_ = new QCheckBox("Save Binary");
        layout->addWidget(saveBinary_);
        saveBinary_->setCheckable(false);

        saveFaceNormals_ = new QCheckBox("Save Face Normals");
        layout->addWidget(saveFaceNormals_);

        saveVertexNormals_ = new QCheckBox("Save Vertex Normals");
        layout->addWidget(saveVertexNormals_);

        saveVertexTexCoords_ = new QCheckBox("Save Vertex TexCoords");
        layout->addWidget(saveVertexTexCoords_);

        savePrecisionLabel_ = new QLabel("Writer Precision");
        layout->addWidget(savePrecisionLabel_);

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
        savePrecision_ = new QSpinBox();
        savePrecision_->setMinimum(1);
        savePrecision_->setMaximum(12);
        savePrecision_->setValue(6);
        layout->addWidget(savePrecision_);

        saveDefaultButton_ = new QPushButton("Make Default");
        layout->addWidget(saveDefaultButton_);

        saveOptions_->setLayout(layout);

        connect(saveBinary_, SIGNAL(clicked(bool)), savePrecision_, SLOT(setDisabled(bool)));
        connect(saveDefaultButton_, SIGNAL(clicked()), this, SLOT(slotSaveDefault()));

        saveBinary_->setChecked( OpenFlipperSettings().value("FileVtk/Save/Binary",false).toBool() );
        saveFaceNormals_->setChecked( OpenFlipperSettings().value("FileVtk/Save/FaceNormals",true).toBool() );
        saveVertexNormals_->setChecked( OpenFlipperSettings().value("FileVtk/Save/VertexNormals",true).toBool() );
        saveVertexTexCoords_->setChecked( OpenFlipperSettings().value("FileVtk/Save/VertexTexCoords",true).toBool() );
    }

    return saveOptions_;
}

//-----------------------------------------------------------------------------------------------------

void FileVTKPlugin::slotSaveDefault() {
  OpenFlipperSettings().setValue( "FileVtk/Save/Binary",          saveBinary_->isChecked()  );
  OpenFlipperSettings().setValue( "FileVtk/Save/FaceNormals",     saveFaceNormals_->isChecked()  );
  OpenFlipperSettings().setValue( "FileVtk/Save/VertexNormals",   saveVertexNormals_->isChecked()  );
  OpenFlipperSettings().setValue( "FileVtk/Save/VertexTexCoords", saveVertexTexCoords_->isChecked()  );
}

//-----------------------------------------------------------------------------------------------------


//-----------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
//-------------------------------------- cool helper function -----------------------------------------
//-----------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------


template <typename MeshT>
int FileVTKPlugin::addTetraCellToOpenMesh(MeshT /*_mesh*/, std::vector<quint32> /*_indices*/)
{
    emit log(LOGWARN,tr("Unsupported Cell Type TETRA") );
    return -1;
}

template <typename MeshT>
int FileVTKPlugin::addHexaCellToOpenMesh(MeshT /*_mesh*/, std::vector<quint32> /*_indices*/)
{
    emit log(LOGWARN,tr("Unsupported Cell Type HEXAHEDRON") );
    return -1;
}

template <typename MeshT>
int FileVTKPlugin::addWedgeCellToOpenMesh(MeshT /*_mesh*/, std::vector<quint32> /*_indices*/)
{
    emit log(LOGWARN,tr("Unsupported Cell Type WEDGE") );
    return -1;
}

template <typename MeshT>
int FileVTKPlugin::addPyramidCellToOpenMesh(MeshT /*_mesh*/, std::vector<quint32> /*_indices*/)
{
    emit log(LOGWARN,tr("Unsupported Cell Type PYRAMID") );
    return -1;
}

template <typename MeshT>
232
int FileVTKPlugin::addFaceToOpenMesh(MeshT*& _mesh, std::vector<quint32> _indices)
233 234
{
    std::vector<OpenMesh::VertexHandle> handles;
235
    for (std::vector<quint32>::const_iterator it = _indices.begin(); it != _indices.end(); ++it)
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
        handles.push_back(_mesh->vertex_handle(*it));

    OpenMesh::FaceHandle fh = _mesh->add_face(handles);

    // Try the other direction
    if ( ! fh.is_valid() ) {

        std::vector< OpenMesh::VertexHandle > inverseHandles;
        for ( int i = handles.size()-1 ; i >= 0 ; --i)
            inverseHandles.push_back(handles[i]);

        fh = _mesh->add_face(inverseHandles);

        if ( !fh.is_valid() ) {
            return add_non_manifold_face(_mesh, handles);
        }
    }
    return fh.idx();
}

template <typename MeshT>
int FileVTKPlugin::addFaceToOpenMesh(MeshT*& _mesh, quint32 _index1, quint32 _index2, quint32 _index3)
{
    OpenMesh::VertexHandle v1 = _mesh->vertex_handle(_index1);
    OpenMesh::VertexHandle v2 = _mesh->vertex_handle(_index2);
    OpenMesh::VertexHandle v3 = _mesh->vertex_handle(_index3);
    return _mesh->add_face(v1,v2,v3).idx();
}

template <typename MeshT>
void FileVTKPlugin::updateFaceNormalsOfOpenMesh(MeshT*& _mesh)
{
    _mesh->update_face_normals();
}

void FileVTKPlugin::updateFaceNormals(TriMesh*& _mesh)        { updateFaceNormalsOfOpenMesh(_mesh);       }
void FileVTKPlugin::updateFaceNormals(PolyMesh*& _mesh)       { updateFaceNormalsOfOpenMesh(_mesh);       }


template <typename MeshT>
void FileVTKPlugin::updateVertexNormalsOfOpenMesh(MeshT*& _mesh)
{
    _mesh->update_vertex_normals();
}

template <typename MeshT>
void FileVTKPlugin::removeTemporaryPropertiesOfOpenMesh(MeshT*& _mesh)
{
    //if we added this property temporarily, we need to remove it now
    OpenMesh::VPropHandleT< OpenMesh::VertexHandle > originalVertexIdx;
    if (! _mesh->get_property_handle(originalVertexIdx,"FileVTKPlugin_originalVertexIdx")) {
      _mesh->remove_property( originalVertexIdx );
    }
}

template <typename MeshT>
void FileVTKPlugin::addVertexNormalToOpenMesh(MeshT _mesh, quint32 _index, OpenMesh::Vec3d _normal)
{
    OpenMesh::VertexHandle vh = _mesh->vertex_handle(_index);
    if ( vh.is_valid() )
      _mesh->set_normal( vh , _normal );
}


template <typename MeshT>
void FileVTKPlugin::addFaceNormalToOpenMesh(MeshT _mesh, quint32 _index, OpenMesh::Vec3d _normal)
{
    OpenMesh::FaceHandle fh = _mesh->face_handle(_index);
    if ( fh.is_valid() )
       _mesh->set_normal( fh, _normal );
}

template <typename MeshT>
309
void FileVTKPlugin::addCellNormal(MeshT*& _mesh,const CellType& _cell, OpenMesh::Vec3d _normal)
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
{
    if ((_cell.type <= 4) || (_cell.type >= 10))
    {
        // vertex, poly vertex, line, poly line, tetra, voxel, hexahedron, wedge, pyramid, and quadratic stuff
        emit log(LOGWARN,tr("Normals not supported for type %1").arg(_cell.type) );
    }
    else if (_cell.type == 5)
    {
        // Triangle
        addFaceNormal(_mesh, _cell.index, _normal);
    }
    else if (_cell.type == 6)
    {
        // Triangle strip
        int numberOfTriangles = _cell.indices.size() - 2;
        // we assume here that the triangles have contigous indices as they were freshly created while loading the file
        for (int i = 0; i < numberOfTriangles; i++)
            addFaceNormal(_mesh, _cell.index + i, _normal);
    }
    else if ((_cell.type >= 7) &&  (_cell.type <= 9))
    {
        // polygon, pixel, quad
        if (forceTriangleMesh_)
        {
            // _mesh is a TriMesh even if cell represents a polygon with more than 3 vertices
            // for more than 3 vertices the polygon will be split into triangles
            // we have to set the normal for all these triangles
            // we assume again that the triangles have contigous indices as they were freshly created while loading the file
            int numberOfTriangles = _cell.indices.size() - 2;
            for (int i = 0; i < numberOfTriangles; i++)
                addFaceNormal(_mesh, _cell.index + i, _normal);
        }
        else
        {
            // Here _mesh might also be a TriMesh. But this is only the case if all polygons are triangles
            // so we only need to set a single normal
            addFaceNormal(_mesh, _cell.index , _normal);
        }
    }
}

template <typename MeshT>
void FileVTKPlugin::setNormalsOfDuplicatedVerticesOfOpenMesh(MeshT*& _mesh)
{
    //iterate over all contained vertices and set the normals
    OpenMesh::VPropHandleT< OpenMesh::VertexHandle > originalVertexIdx;
    if (! _mesh->get_property_handle(originalVertexIdx,"FileVTKPlugin_originalVertexIdx")) {
      //TODO: check if this is correct;
      //if the property was not found, there are no copied vertices and we can leave
       return;
      //old and maybe unnecessary:  _mesh->add_property( originalVertexIdx, "FileVTKPlugin_originalVertexIdx" );
    }

    typename MeshT::VertexIter vit = _mesh->vertices_begin();
    typename MeshT::VertexIter vend = _mesh->vertices_end();

    for(; vit != vend; ++vit) {
Matthias Möller's avatar
Matthias Möller committed
367
      if ( _mesh->property(originalVertexIdx, *vit).is_valid() ) {
368
          //copied vertex found
Matthias Möller's avatar
Matthias Möller committed
369
          _mesh->set_normal( *vit, _mesh->normal(_mesh->property (originalVertexIdx, *vit) ) );
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
      }
    }
}

template< class MeshT >
bool FileVTKPlugin::writeASCIIDataOfOpenMesh(std::ostream& _out, MeshT& _mesh ) {

    if ( !OpenFlipper::Options::savingSettings() && saveOptions_ != 0)
        _out.precision(savePrecision_->value());

    _out << "DATASET POLYDATA\n";

    typename MeshT::Point p;
    typename MeshT::Normal n;
    typename OpenMesh::Vec4f c;
    typename MeshT::TexCoord2D t;

    typename MeshT::VertexIter vit = _mesh.vertices_begin();
    typename MeshT::VertexIter end_vit = _mesh.vertices_end();
    typename MeshT::FaceIter fit = _mesh.faces_begin();
    typename MeshT::FaceIter end_fit = _mesh.faces_end();
    typename MeshT::FaceVertexIter fvit;

393
    int total_face_vertices = _mesh.n_faces();
394
    for (; fit != end_fit; ++fit) {
Matthias Möller's avatar
Matthias Möller committed
395
        total_face_vertices += _mesh.valence(*fit);
396 397 398 399 400
    }
    // Write vertex data
    _out << "POINTS " << _mesh.n_vertices() << " float\n";
    for (; vit != end_vit; ++vit) {
        // Write vertex p[0] p[1] p[2]
Matthias Möller's avatar
Matthias Möller committed
401
        p = _mesh.point(*vit);
402 403 404 405 406 407 408 409
        _out << p[0] << " " << p[1] << " " << p[2];
        _out << "\n";
    }

    // Write face connectivity
    _out << "POLYGONS "<< _mesh.n_faces() << " " << total_face_vertices << "\n";
    for (fit = _mesh.faces_begin(); fit != end_fit; ++fit) {
        // Write face valence
Matthias Möller's avatar
Matthias Möller committed
410
        _out << _mesh.valence(*fit);
411 412

        // Get face-vertex iterator
Matthias Möller's avatar
Matthias Möller committed
413
        fvit = _mesh.fv_iter(*fit);
414 415

        // Write vertex indices
Matthias Möller's avatar
Matthias Möller committed
416 417
        for (;fvit.is_valid(); ++fvit) {
            _out << " " << fvit->idx();
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
        }
        _out << "\n";
    }

    //*************//
    //OPTIONAL DATA//
    //*************//

    /*** Write face attributes ***/
    _out << "CELL_DATA "<< _mesh.n_faces() << "\n";

    //Write face normals
    if (_mesh.has_face_normals() && (userWriteOptions_ & FileVTKPlugin::FACENORMALS)) {
        _out << "NORMALS faceNormals float\n";
        for (fit = _mesh.faces_begin(); fit != end_fit; ++fit) {
Matthias Möller's avatar
Matthias Möller committed
433
            n = _mesh.normal(*fit);
434 435 436 437 438 439 440 441 442 443 444 445
            _out << n[0] << " " << n[1] << " " << n[2];
            _out << "\n";
        }
    }

    /*** Write vertex attributes ***/
    _out << "POINT_DATA "<< _mesh.n_vertices() << "\n";

    //Write vertex normals
    if (_mesh.has_vertex_normals() && (userWriteOptions_ & FileVTKPlugin::VERTEXNORMALS)) {
        _out << "NORMALS vertexNormals float\n";
        for (vit = _mesh.vertices_begin(); vit != end_vit; ++vit) {
Matthias Möller's avatar
Matthias Möller committed
446
            n = _mesh.normal(*vit);
447 448 449 450 451 452 453 454 455
            _out << n[0] << " " << n[1] << " " << n[2];
            _out << "\n";
        }
    }

    // Write vertex texcoords (only 2D for now)
    if (_mesh.has_vertex_texcoords2D() && (userWriteOptions_ & FileVTKPlugin::VERTEXTEXCOORDS)) {
        _out << "TEXTURE_COORDINATES vertexTexcoords 2 float\n";
        for (vit = _mesh.vertices_begin(); vit != end_vit; ++vit) {
Matthias Möller's avatar
Matthias Möller committed
456
            t = _mesh.texcoord2D(*vit);
457 458 459 460 461 462 463 464
            _out << t[0] << " " << t[1];
            _out << "\n";
        }
    }

    return true;
}

465 466
int FileVTKPlugin::addTetraCell(TriMesh*& _mesh, const std::vector<quint32>& _indices)                 { return addTetraCellToOpenMesh(_mesh, _indices);             }
int FileVTKPlugin::addTetraCell(PolyMesh*& _mesh, const std::vector<quint32>& _indices)                { return addTetraCellToOpenMesh(_mesh, _indices);             }
467

468 469
int FileVTKPlugin::addHexaCell(TriMesh*& _mesh, const std::vector<quint32>& _indices)                  { return addHexaCellToOpenMesh(_mesh, _indices);              }
int FileVTKPlugin::addHexaCell(PolyMesh*& _mesh, const std::vector<quint32>& _indices)                 { return addHexaCellToOpenMesh(_mesh, _indices);              }
470

471 472
int FileVTKPlugin::addWedgeCell(TriMesh*& _mesh, const std::vector<quint32>& _indices)                 { return addWedgeCellToOpenMesh(_mesh, _indices);             }
int FileVTKPlugin::addWedgeCell(PolyMesh*& _mesh, const std::vector<quint32>& _indices)                { return addWedgeCellToOpenMesh(_mesh, _indices);             }
473

474 475
int FileVTKPlugin::addPyramidCell(TriMesh*& _mesh, const std::vector<quint32>& _indices)               { return addPyramidCellToOpenMesh(_mesh, _indices);           }
int FileVTKPlugin::addPyramidCell(PolyMesh*& _mesh, const std::vector<quint32>& _indices)              { return addPyramidCellToOpenMesh(_mesh, _indices);           }
476

477 478
int FileVTKPlugin::addFace(TriMesh*& _mesh, const std::vector<quint32>& _indices)                      { return addFaceToOpenMesh(_mesh, _indices);                  }
int FileVTKPlugin::addFace(PolyMesh*& _mesh, const std::vector<quint32>& _indices)                     { return addFaceToOpenMesh(_mesh, _indices);                  }
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

int FileVTKPlugin::addFace(TriMesh*& _mesh, quint32 _index1, quint32 _index2, quint32 _index3)  { return addFaceToOpenMesh(_mesh, _index1, _index2, _index3); }
int FileVTKPlugin::addFace(PolyMesh*& _mesh, quint32 _index1, quint32 _index2, quint32 _index3) { return addFaceToOpenMesh(_mesh, _index1, _index2, _index3); }

void FileVTKPlugin::updateVertexNormals(TriMesh*& _mesh)                                        { updateVertexNormalsOfOpenMesh(_mesh);                       }
void FileVTKPlugin::updateVertexNormals(PolyMesh*& _mesh)                                       { updateVertexNormalsOfOpenMesh(_mesh);                       }

void FileVTKPlugin::removeTemporaryProperties(TriMesh*& _mesh)                                  { removeTemporaryPropertiesOfOpenMesh(_mesh);                 }
void FileVTKPlugin::removeTemporaryProperties(PolyMesh*& _mesh)                                 { removeTemporaryPropertiesOfOpenMesh(_mesh);                 }

void FileVTKPlugin::addVertexNormal(TriMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)   { addVertexNormalToOpenMesh(_mesh, _index, _normal);          }
void FileVTKPlugin::addVertexNormal(PolyMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)  { addVertexNormalToOpenMesh(_mesh, _index, _normal);          }

void FileVTKPlugin::addFaceNormal(TriMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)     { addFaceNormalToOpenMesh(_mesh, _index, _normal);            }
void FileVTKPlugin::addFaceNormal(PolyMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)    { addFaceNormalToOpenMesh(_mesh, _index, _normal);            }

void FileVTKPlugin::setNormalsOfDuplicatedVertices(TriMesh*& _mesh)                             { setNormalsOfDuplicatedVerticesOfOpenMesh(_mesh);            }
void FileVTKPlugin::setNormalsOfDuplicatedVertices(PolyMesh*& _mesh)                            { setNormalsOfDuplicatedVerticesOfOpenMesh(_mesh);            }

498 499
bool FileVTKPlugin::writeASCIIData(std::ostream &_out, TriMesh &_mesh)                          { return writeASCIIDataOfOpenMesh(_out, _mesh);               }
bool FileVTKPlugin::writeASCIIData(std::ostream &_out, PolyMesh &_mesh)                         { return writeASCIIDataOfOpenMesh(_out, _mesh);               }
500 501


502
#if defined(ENABLE_HEXAHEDRALMESH_SUPPORT) || defined(ENABLE_POLYHEDRALMESH_SUPPORT) || defined(ENABLE_TETRAHEDRALMESH_SUPPORT)
503 504 505 506 507 508 509 510 511

template <typename MeshT>
int FileVTKPlugin::addTetraCellToOpenVolumeMesh(MeshT _mesh, std::vector<quint32> _indices)
{
    if (_indices.size() != 4)
    {   /*emit log(LOGWARN,tr("Unsupported Cell Type Tetra") );*/ }

    std::vector< std::vector<OpenVolumeMesh::VertexHandle> > faces;
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
512 513 514
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
515
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
516 517 518
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
519
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
520 521 522
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
523
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
524 525 526
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
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

    std::vector<OpenVolumeMesh::HalfFaceHandle> halffacehandles;
    for (unsigned int i = 0; i < faces.size(); i++)
        halffacehandles.push_back(_mesh->halfface(faces[i]));

    for (unsigned int i = 0; i < halffacehandles.size(); i++)
        if (halffacehandles[i] == OpenVolumeMesh::HalfFaceHandle(-1))
        {
            // face didn't exist
            OpenVolumeMesh::FaceHandle fh = _mesh->add_face(faces[i]);
            halffacehandles[i] = _mesh->halfface_handle(fh, 0);
        }

    return _mesh->add_cell(halffacehandles).idx();

}

template <typename MeshT>
int FileVTKPlugin::addHexaCellToOpenVolumeMesh(MeshT _mesh, std::vector<quint32> _indices)
{
    if (_indices.size() != 8)
    {   emit log(LOGWARN,tr("Expected 8 indices to add Hexahedron but got %1").arg(_indices.size()) ); }

    std::vector< std::vector<OpenVolumeMesh::VertexHandle> > faces;
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
552 553 554 555
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
556
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
557 558 559 560
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[5]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
561
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
562 563 564 565
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[7]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
566
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
567 568 569 570
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[5]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[6]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
571
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
572 573 574 575
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[6]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[7]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
576
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
577 578 579 580
    faces[5].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
    faces[5].push_back(OpenVolumeMesh::VertexHandle(_indices[7]));
    faces[5].push_back(OpenVolumeMesh::VertexHandle(_indices[6]));
    faces[5].push_back(OpenVolumeMesh::VertexHandle(_indices[5]));
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

    std::vector<OpenVolumeMesh::HalfFaceHandle> halffacehandles;
    for (unsigned int i = 0; i < faces.size(); i++)
        halffacehandles.push_back(_mesh->halfface(faces[i]));

    for (unsigned int i = 0; i < halffacehandles.size(); i++)
        if (halffacehandles[i] == OpenVolumeMesh::HalfFaceHandle(-1))
        {
            // face didn't exist
            OpenVolumeMesh::FaceHandle fh = _mesh->add_face(faces[i]);
            halffacehandles[i] = _mesh->halfface_handle(fh, 0);
        }

    return _mesh->add_cell(halffacehandles).idx();
}

template <typename MeshT>
int FileVTKPlugin::addWedgeCellToOpenVolumeMesh(MeshT _mesh, std::vector<quint32> _indices)
{
    if (_indices.size() != 6)
    {   emit log(LOGWARN,tr("Expected 6 indices to add Hexahedron but got %1").arg(_indices.size()) ); }

    std::vector< std::vector<OpenVolumeMesh::VertexHandle> > faces;
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
605 606 607 608
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
609
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
610 611 612
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
613
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
614 615 616
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[5]));
617
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
618 619 620 621
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[5]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
622
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
623 624 625 626
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[5]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650

    std::vector<OpenVolumeMesh::HalfFaceHandle> halffacehandles;
    for (unsigned int i = 0; i < faces.size(); i++)
        halffacehandles.push_back(_mesh->halfface(faces[i]));

    for (unsigned int i = 0; i < halffacehandles.size(); i++)
        if (halffacehandles[i] == OpenVolumeMesh::HalfFaceHandle(-1))
        {
            // face didn't exist
            OpenVolumeMesh::FaceHandle fh = _mesh->add_face(faces[i]);
            halffacehandles[i] = _mesh->halfface_handle(fh, 0);
        }

    return _mesh->add_cell(halffacehandles).idx();
}

template <typename MeshT>
int FileVTKPlugin::addPyramidCellToOpenVolumeMesh(MeshT _mesh, std::vector<quint32> _indices)
{
    if (_indices.size() != 6)
    {   emit log(LOGWARN,tr("Expected 6 indices to add Hexahedron but got %1").arg(_indices.size()) ); }

    std::vector< std::vector<OpenVolumeMesh::VertexHandle> > faces;
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
651 652 653 654
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
    faces[0].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
655
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
656 657 658
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
    faces[1].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
659
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
660 661 662
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[0]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
    faces[2].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
663
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
664 665 666
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
    faces[3].push_back(OpenVolumeMesh::VertexHandle(_indices[3]));
667
    faces.push_back(std::vector<OpenVolumeMesh::VertexHandle>());
668 669 670
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[1]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[4]));
    faces[4].push_back(OpenVolumeMesh::VertexHandle(_indices[2]));
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699

    std::vector<OpenVolumeMesh::HalfFaceHandle> halffacehandles;
    for (unsigned int i = 0; i < faces.size(); i++)
        halffacehandles.push_back(_mesh->halfface(faces[i]));

    for (unsigned int i = 0; i < halffacehandles.size(); i++)
        if (halffacehandles[i] == OpenVolumeMesh::HalfFaceHandle(-1))
        {
            // face didn't exist
            OpenVolumeMesh::FaceHandle fh = _mesh->add_face(faces[i]);
            halffacehandles[i] = _mesh->halfface_handle(fh, 0);
        }

    return _mesh->add_cell(halffacehandles).idx();
}

template <typename MeshT>
int FileVTKPlugin::addFaceToOpenVolumeMesh(MeshT*& _mesh, std::vector<quint32> _indices)
{
    if (_indices.size() < 3)
    {   emit log(LOGWARN,tr("Expected at least 3 indices to add a face but got %1").arg(_indices.size()) ); }

    std::vector<OpenVolumeMesh::VertexHandle> face;
    for (unsigned int i = 0; i < _indices.size(); i++)
        face.push_back(OpenVolumeMesh::VertexHandle(_indices[i]));


    OpenVolumeMesh::HalfFaceHandle halffacehandle;
    halffacehandle = _mesh->halfface(face);
700
    if (!halffacehandle.is_valid()) // face didn't exist
701
    {
702
        OpenVolumeMesh::FaceHandle fh = _mesh->add_face(face);
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
        halffacehandle = _mesh->halfface_handle(fh, 0);
    }
    return halffacehandle.idx();
}

template <typename MeshT>
int FileVTKPlugin::addFaceToOpenVolumeMesh(MeshT*& _mesh, quint32 _index1, quint32 _index2, quint32 _index3)
{
    std::vector<OpenVolumeMesh::VertexHandle> face;
    face.push_back(OpenVolumeMesh::VertexHandle(_index1));
    face.push_back(OpenVolumeMesh::VertexHandle(_index2));
    face.push_back(OpenVolumeMesh::VertexHandle(_index3));

    OpenVolumeMesh::HalfFaceHandle halffacehandle;
    halffacehandle = _mesh->halfface(face);
718
    if (!halffacehandle.is_valid()) // face didn't exist
719
    {
720
        OpenVolumeMesh::FaceHandle fh = _mesh->add_face(face);
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
        halffacehandle = _mesh->halfface_handle(fh, 0);
    }
    return halffacehandle.idx();
}

template <typename MeshT>
void FileVTKPlugin::addVertexNormalToOpenVolumeMesh(MeshT _mesh, quint32 _index, OpenMesh::Vec3d _normal)
{
    OpenVolumeMesh::VertexPropertyT< typename OpenMesh::Vec3d > vertexNormals = _mesh->template request_vertex_property< typename OpenMesh::Vec3d >("vertex_normals");
    vertexNormals[OpenVolumeMesh::VertexHandle(_index)] = _normal;
}

template <typename MeshT>
void FileVTKPlugin::addFaceNormalToOpenVolumeMesh(MeshT _mesh, quint32 _index, OpenMesh::Vec3d _normal)
{
    OpenVolumeMesh::FacePropertyT< OpenMesh::Vec3d > faceNormals = _mesh->template request_face_property< OpenMesh::Vec3d >("face_normals");

    OpenVolumeMesh::HalfFaceHandle hfh = OpenVolumeMesh::HalfFaceHandle(_index);
    OpenVolumeMesh::FaceHandle      fh = _mesh->face_handle(hfh);
    if (hfh == _mesh->halfface_handle(fh, 0))
741
        faceNormals[fh] = _normal;
742
    else
743
        faceNormals[fh] = -_normal;
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 908 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 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 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

}

template <typename MeshT>
int getCellType(MeshT& _mesh, OpenVolumeMesh::CellHandle _cellHandle)
{
    int incidentFaces = _mesh.cell(_cellHandle).halffaces().size();
    int incidentVertices = 0;
    for (OpenVolumeMesh::CellVertexIter cvit = OpenVolumeMesh::CellVertexIter(_cellHandle, &_mesh); cvit.valid(); ++cvit)
        incidentVertices++;

    if      ((incidentFaces == 4) && (incidentVertices == 4))
        return 10; // tetra
    else if ((incidentFaces == 6) && (incidentVertices == 8))
        return 12; // hexahedron
    else if ((incidentFaces == 5) && (incidentVertices == 6))
        return 13; // wedge
    else if ((incidentFaces == 5) && (incidentVertices == 5))
        return 14; // pyramid
    else
        return -1;
}

template <typename MeshT>
int getCellType(MeshT& _mesh, OpenVolumeMesh::FaceHandle _faceHandle)
{
    std::vector<OpenVolumeMesh::HalfEdgeHandle> halfedges = _mesh.face(_faceHandle).halfedges();
    if (halfedges.size() == 3)
        return 5; // triangle;
    else
        return 7; // polygon
}

template <typename MeshT>
std::vector<int> getCellVertexIndices(MeshT& _mesh, OpenVolumeMesh::CellHandle _cellHandle, int _cellType)
{
    if (_cellType == 10) //tetra
    {
        // first three vertices are the three vertices of an arbitrary face
        // the last vertex is the one that is left
        OpenVolumeMesh::OpenVolumeMeshCell cell = _mesh.cell(_cellHandle);
        OpenVolumeMesh::OpenVolumeMeshFace face = _mesh.halfface(cell.halffaces()[0]);
        std::vector<OpenVolumeMesh::HalfEdgeHandle> halfedges = face.halfedges();
        std::vector<int> indices;
        for (unsigned int i = 0; i < halfedges.size(); i++)
            indices.push_back(_mesh.halfedge(halfedges[i]).from_vertex().idx());
        for (OpenVolumeMesh::CellVertexIter cvit = OpenVolumeMesh::CellVertexIter(_cellHandle, &_mesh); cvit.valid(); ++cvit)
            if ((cvit->idx() != indices[0]) && ((*cvit).idx() != indices[1]) && ((*cvit).idx() != indices[2]))
                indices.push_back(cvit->idx());
        return indices;
    }
    else if (_cellType == 12) // hexahedron
    {
        // take an arbitrary face and add its vertices
        OpenVolumeMesh::OpenVolumeMeshCell cell = _mesh.cell(_cellHandle);
        OpenVolumeMesh::HalfFaceHandle hfh = cell.halffaces()[0];
        OpenVolumeMesh::OpenVolumeMeshFace face = _mesh.halfface(hfh);
        OpenVolumeMesh::HalfEdgeHandle heh = face.halfedges()[0];
        std::vector<int> indices;
        for (unsigned int i = 0; i < 4; i++)
        {
            OpenVolumeMesh::OpenVolumeMeshEdge edge = _mesh.halfedge(heh);
            indices.push_back(edge.from_vertex().idx());
            heh = _mesh.next_halfedge_in_halfface(heh, hfh);
        }
        // we now added four vertices and heh is a handle to the edge coming out of the first added vertex
        // we will now navigate to the oppsite face
        OpenVolumeMesh::HalfFaceHandle intermediateHalfFaceHandle = _mesh.adjacent_halfface_in_cell(hfh, heh);
        heh = _mesh.opposite_halfedge_handle(heh);
        heh = _mesh.next_halfedge_in_halfface(heh, intermediateHalfFaceHandle);
        heh = _mesh.next_halfedge_in_halfface(heh, intermediateHalfFaceHandle);
        OpenVolumeMesh::HalfFaceHandle oppositeHalfFaceHandle = _mesh.adjacent_halfface_in_cell(intermediateHalfFaceHandle, heh);
        heh = _mesh.opposite_halfedge_handle(heh);
        // heh is now the halfedge pointing to vertex 4 and lies in the opposite half face.
        // we now have to add the four vertices of that face but in clockwise order
        for (unsigned int i = 0; i < 4; i++)
        {
            OpenVolumeMesh::OpenVolumeMeshEdge edge = _mesh.halfedge(heh);
            indices.push_back(edge.to_vertex().idx());
            heh = _mesh.prev_halfedge_in_halfface(heh, oppositeHalfFaceHandle);
        }
        return indices;
    }
    else if (_cellType == 13) // wedge
    {
        // take a face with three vertices and add its vertices in clockwise order
        OpenVolumeMesh::OpenVolumeMeshCell cell = _mesh.cell(_cellHandle);
        OpenVolumeMesh::HalfFaceHandle hfh;
        for (unsigned int i = 0; i < cell.halffaces().size(); i++)
            if (_mesh.halfface(cell.halffaces()[i]).halfedges().size() == 3)
                hfh = cell.halffaces()[i];
        OpenVolumeMesh::OpenVolumeMeshFace face = _mesh.halfface(hfh);
        OpenVolumeMesh::HalfEdgeHandle heh = face.halfedges()[0];
        std::vector<int> indices;
        for (unsigned int i = 0; i < 3; i++)
        {
            OpenVolumeMesh::OpenVolumeMeshEdge edge = _mesh.halfedge(heh);
            indices.push_back(edge.from_vertex().idx());
            heh = _mesh.prev_halfedge_in_halfface(heh, hfh);
        }
        // we now added three vertices and heh is a handle to the edge coming out of the first added vertex
        // we will now navigate to the oppsite face
        OpenVolumeMesh::HalfFaceHandle intermediateHalfFaceHandle = _mesh.adjacent_halfface_in_cell(hfh, heh);
        heh = _mesh.opposite_halfedge_handle(heh);
        heh = _mesh.next_halfedge_in_halfface(heh, intermediateHalfFaceHandle);
        heh = _mesh.next_halfedge_in_halfface(heh, intermediateHalfFaceHandle);
        OpenVolumeMesh::HalfFaceHandle oppositeHalfFaceHandle = _mesh.adjacent_halfface_in_cell(intermediateHalfFaceHandle, heh);
        heh = _mesh.opposite_halfedge_handle(heh);
        // heh is now the halfedge pointing to vertex 3 and lies in the opposite half face.
        // we now have to add the three vertices of that face but in counter clockwise order
        for (unsigned int i = 0; i < 3; i++)
        {
            OpenVolumeMesh::OpenVolumeMeshEdge edge = _mesh.halfedge(heh);
            indices.push_back(edge.to_vertex().idx());
            heh = _mesh.next_halfedge_in_halfface(heh, oppositeHalfFaceHandle);
        }
        return indices;

    }
    else if (_cellType == 14) // pyramid
    {
        // the first four vertices are the for vertices of the face with for vertices
        // the other vertex is the one that is left
        OpenVolumeMesh::OpenVolumeMeshCell cell = _mesh.cell(_cellHandle);
        std::vector<OpenVolumeMesh::HalfFaceHandle> halffaces = cell.halffaces();
        OpenVolumeMesh::OpenVolumeMeshFace face = _mesh.halfface(halffaces[0]);
        for (unsigned int i = 0; i < halffaces.size(); i++)
            if (_mesh.halfface(halffaces[i]).halfedges().size() == 4)
                face = _mesh.halfface(halffaces[i]);
        std::vector<OpenVolumeMesh::HalfEdgeHandle> halfedges = face.halfedges();
        std::vector<int> indices;
        for (unsigned int i = 0; i < halfedges.size(); i++)
            indices.push_back(_mesh.halfedge(halfedges[i]).from_vertex().idx());
        for (OpenVolumeMesh::CellVertexIter cvit = OpenVolumeMesh::CellVertexIter(_cellHandle, &_mesh); cvit.valid(); ++cvit)
            if ((cvit->idx() != indices[0]) && ((*cvit).idx() != indices[1]) && ((*cvit).idx() != indices[2]) && ((*cvit).idx() != indices[3]))
                indices.push_back(cvit->idx());
        return indices;
    }
    else // unsupported type
        return std::vector<int>();
}

template <typename MeshT>
bool FileVTKPlugin::writeASCIIDataOfOpenVolumeMesh(std::ostream& _out, MeshT& _mesh)
{
    if ( !OpenFlipper::Options::savingSettings() && saveOptions_ != 0)
        _out.precision(savePrecision_->value());

    _out << "DATASET UNSTRUCTURED_GRID\n";


    // save all vertices

    OpenVolumeMesh::VertexIter vit = _mesh.vertices_begin();
    OpenVolumeMesh::VertexIter end_vit = _mesh.vertices_end();
    _out << "POINTS " << _mesh.n_vertices() << " float\n";
    for (; vit != end_vit; ++vit) {
        // Write vertex p[0] p[1] p[2]
        ACG::Vec3d p = _mesh.vertex(*vit);
        _out << p[0] << " " << p[1] << " " << p[2];
        _out << "\n";
    }



    // Remember which faces have been added, so we can later save the isolated faces.
    OpenVolumeMesh::FacePropertyT<bool> fpAlreadyStored = _mesh.template request_face_property<bool>();

    // Remember which edges have been added, so we can later save the isolated edges;
    OpenVolumeMesh::EdgePropertyT<bool> epAlreadyStored = _mesh.template request_edge_property<bool>();

    int cellCount = 0;

    // count the cell list size (for each cell: 1 + adjacent vertices)

    quint32 listSize = 0;
    for (OpenVolumeMesh::CellIter cit = _mesh.cells_begin(); cit != _mesh.cells_end(); ++cit)
    {
        int cellType = getCellType(_mesh, *cit);

        if (cellType == 10 )
            listSize += 1 + 4;
        else if (cellType == 12 )
            listSize += 1 + 8;
        else if (cellType == 13 )
            listSize += 1 + 6;
        else if (cellType == 14 )
            listSize += 1 + 5;
        else // type not supported by vtk file -> ignore
            continue;

        cellCount++;

        std::vector<OpenVolumeMesh::HalfFaceHandle> halffaces = _mesh.cell(*cit).halffaces();
        for (unsigned int i = 0; i < halffaces.size(); i++)
        {
            OpenVolumeMesh::FaceHandle fh = _mesh.face_handle(halffaces[i]);
            if (!(fpAlreadyStored[fh]))
            {
                // mark this face and its edges as already stored
                // if the user wants to save face normals we cannot skip adding the faces
                if (!(userWriteOptions_ & FileVTKPlugin::FACENORMALS))
                    fpAlreadyStored[fh] = true;
                //mark the edges as already added.
                OpenVolumeMesh::OpenVolumeMeshFace face = _mesh.halfface(halffaces[i]);
                for (std::vector<OpenVolumeMesh::HalfEdgeHandle>::const_iterator heit = face.halfedges().begin();
                     heit != face.halfedges().end();
                     ++heit)
                {
                    epAlreadyStored[_mesh.edge_handle(*heit)] = true;
                }
            }
        }
    }

    for (OpenVolumeMesh::FaceIter fit = _mesh.faces_begin(); fit != _mesh.faces_end(); ++fit)
    {
        if (!(fpAlreadyStored[*fit]))
        {
            //mark edges as already stored
            std::vector<OpenVolumeMesh::HalfEdgeHandle> halfedges = _mesh.face(*fit).halfedges();
            for (unsigned int i = 0; i < halfedges.size(); i++)
                epAlreadyStored[_mesh.edge_handle(halfedges[i])] = true;

            // number of incident vertices == number of incident halfedges
            listSize += 1 + halfedges.size();

            cellCount++;
        }
    }

    for (OpenVolumeMesh::EdgeIter eit = _mesh.edges_begin(); eit != _mesh.edges_end(); ++eit)
    {
        if (!(epAlreadyStored[*eit]))
        {
            listSize += 1 + 2;
            cellCount++;
        }
    }

    _out << "CELLS " << cellCount << " " << listSize << "\n";


    // save all cellCells.

    for (OpenVolumeMesh::CellIter cit = _mesh.cells_begin(); cit != _mesh.cells_end(); ++cit)
    {
        //std::vector<OpenVolumeMesh::VertexHandle> vertices;

        int cellType = getCellType(_mesh, *cit);

        // TODO:
        if (cellType == 10 )
            listSize += 1 + 4;
        else if (cellType == 12 )
            listSize += 1 + 8;
        else if (cellType == 13 )
            listSize += 1 + 6;
        else if (cellType == 14 )
            listSize += 1 + 5;
        else // type not supported by vtk file -> ignore
            continue;

        if (cellType == -1)// type not supported by vtk file -> ignore
            continue;
        else
        {
            std::vector<int> indices = getCellVertexIndices(_mesh, *cit, cellType);
            _out << indices.size();
            for (unsigned int i = 0; i < indices.size(); i++)
                _out << " " << indices[i];
            _out << "\n";
        }

    }

    // save isolated faces

    for (OpenVolumeMesh::FaceIter fit = _mesh.faces_begin(); fit != _mesh.faces_end(); ++fit)
    {
        if (!(fpAlreadyStored[*fit]))
        {
            std::vector<OpenVolumeMesh::HalfEdgeHandle> halfedges = _mesh.face(*fit).halfedges();

            _out << halfedges.size();
            for (unsigned int i = 0; i < halfedges.size(); i++)
            {
                OpenVolumeMesh::HalfEdgeHandle heh = halfedges[i];
                OpenVolumeMesh::OpenVolumeMeshEdge edge = _mesh.halfedge(heh);
                _out << " " << edge.from_vertex().idx();
            }
            _out << "\n";
        }
    }


    // save isolated edges


    for (OpenVolumeMesh::EdgeIter eit = _mesh.edges_begin(); eit != _mesh.edges_end(); ++eit)
    {
        if (!(epAlreadyStored[*eit]))
        {
            OpenVolumeMesh::OpenVolumeMeshEdge edge = _mesh.edge(*eit);
            _out << "2";
            _out << " " << edge.from_vertex().idx();
            _out << " " << edge.to_vertex().idx();
            _out << "\n";
        }
    }



    // write cell types to file

    _out << "CELL_TYPES " << cellCount << "\n";

    // cell cellTypes
    for (OpenVolumeMesh::CellIter cit = _mesh.cells_begin(); cit != _mesh.cells_end(); ++cit)
    {
        int cellType = getCellType(_mesh, *cit);
        if (cellType == -1) //type not supported by vtk file, so this cell was not added
            continue;
        else
            _out << cellType << "\n";
    }

    // face cell types

    for (OpenVolumeMesh::FaceIter fit = _mesh.faces_begin(); fit != _mesh.faces_end(); ++fit)
    {
        if (!(fpAlreadyStored[*fit]))
        {
            int cellType = getCellType(_mesh,*fit);
            if (cellType == -1) //type not supported by vtk file, so this cell was not added
                continue;
            else
                _out << cellType << "\n";
        }
    }


    // edge cell type
    for (OpenVolumeMesh::EdgeIter eit = _mesh.edges_begin(); eit != _mesh.edges_end(); ++eit)
    {
        if (!(epAlreadyStored[*eit]))
        {
        // all edges have type 3
            _out << "2\n";
        }
    }



    //*************//
    //OPTIONAL DATA//
    //*************//

    //writing of tex coords also not supported yet.


    //Write vertex normals
    if ((userWriteOptions_ & FileVTKPlugin::VERTEXNORMALS))
    {
        _out << "POINT_DATA "<< _mesh.n_vertices() << "\n";

        OpenVolumeMesh::VertexPropertyT< typename OpenMesh::Vec3d > vertexNormals = _mesh.template request_vertex_property< typename OpenMesh::Vec3d >("vertex_normals");
        _out << "NORMALS vertex_normals float\n";
        for (OpenVolumeMesh::VertexIter vit = _mesh.vertices_begin(); vit != _mesh.vertices_end(); ++vit) {
            typename OpenMesh::Vec3d n = vertexNormals[*vit];
            _out << n[0] << " " << n[1] << " " << n[2];
            _out << "\n";
        }
    }


    //Write face normals
    if ((userWriteOptions_ & FileVTKPlugin::FACENORMALS))
    {
        _out << "CELL_DATA "<< cellCount << "\n";
        _out << "NORMALS face_normals float\n";
        // write dummy normal for cells

        for (OpenVolumeMesh::CellIter cit = _mesh.cells_begin(); cit != _mesh.cells_end(); ++cit)
        {
            int cellType = getCellType(_mesh, *cit);

            if (cellType == -1 )// type not supported by vtk file -> ignore
                continue;
            else
            {
                _out << 1 << " " << 0 << " " << 0;
                _out << "\n";
            }
        }


        // write face normals
        OpenVolumeMesh::FacePropertyT< typename OpenMesh::Vec3d > faceNormals = _mesh.template request_face_property< typename OpenMesh::Vec3d >("face_normals");

        for (OpenVolumeMesh::FaceIter fit = _mesh.faces_begin(); fit != _mesh.faces_end(); ++fit) {
            typename OpenMesh::Vec3d n = faceNormals[*fit];
            _out << n[0] << " " << n[1] << " " << n[2];
            _out << "\n";
        }


        // write dummy normals for edges
        for (OpenVolumeMesh::EdgeIter eit = _mesh.edges_begin(); eit != _mesh.edges_end(); ++eit)
        {
            if (!(epAlreadyStored[*eit]))
            {
                _out << 1 << " " << 0 << " " << 0;
                _out << "\n";
            }
        }


    }

    return true;
}

#endif //ENABLE_OPENVOLUMEMESH_SUPPORT

1169
#ifdef ENABLE_HEXAHEDRALMESH_SUPPORT
1170 1171 1172 1173 1174
int FileVTKPlugin::addTetraCell(HexahedralMesh*& _mesh, const std::vector<quint32>& indices)                 { return addTetraCellToOpenVolumeMesh(_mesh, indices);              }
int FileVTKPlugin::addHexaCell(HexahedralMesh*& _mesh, const std::vector<quint32>& indices)                  { return addHexaCellToOpenVolumeMesh(_mesh, indices);               }
int FileVTKPlugin::addWedgeCell(HexahedralMesh*& _mesh, const std::vector<quint32>& indices)                 { return addWedgeCellToOpenVolumeMesh(_mesh, indices);              }
int FileVTKPlugin::addPyramidCell(HexahedralMesh*& _mesh, const std::vector<quint32>& indices)               { return addPyramidCellToOpenVolumeMesh(_mesh, indices);            }
int FileVTKPlugin::addFace(HexahedralMesh*& _mesh, const std::vector<quint32>& indices)                      { return addFaceToOpenVolumeMesh(_mesh, indices);                   }
1175 1176 1177 1178
int FileVTKPlugin::addFace(HexahedralMesh*& _mesh, quint32 _index1, quint32 _index2, quint32 _index3) { return addFaceToOpenVolumeMesh(_mesh, _index1, _index2, _index3); }
void FileVTKPlugin::addVertexNormal(HexahedralMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)  { addVertexNormalToOpenVolumeMesh(_mesh, _index, _normal);          }
void FileVTKPlugin::addFaceNormal(HexahedralMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)    { addFaceNormalToOpenVolumeMesh(_mesh, _index, _normal);            }
bool FileVTKPlugin::writeASCIIData(std::ostream& _out, HexahedralMesh& _mesh)                         { return writeASCIIDataOfOpenVolumeMesh(_out, _mesh);               }
1179
#endif //ENABLE_HEXAHEDRALMESH_SUPPORT
1180 1181


1182
#ifdef ENABLE_POLYHEDRALMESH_SUPPORT
Jan Möbius's avatar
Jan Möbius committed
1183 1184 1185 1186 1187
int FileVTKPlugin::addTetraCell(PolyhedralMesh*& _mesh, const std::vector<quint32>& indices)                 { return addTetraCellToOpenVolumeMesh(_mesh, indices);              }
int FileVTKPlugin::addHexaCell(PolyhedralMesh*& _mesh, const std::vector<quint32>& indices)                  { return addHexaCellToOpenVolumeMesh(_mesh, indices);               }
int FileVTKPlugin::addWedgeCell(PolyhedralMesh*& _mesh, const std::vector<quint32>& indices)                 { return addWedgeCellToOpenVolumeMesh(_mesh, indices);              }
int FileVTKPlugin::addPyramidCell(PolyhedralMesh*& _mesh, const std::vector<quint32>& indices)               { return addPyramidCellToOpenVolumeMesh(_mesh, indices);            }
int FileVTKPlugin::addFace(PolyhedralMesh*& _mesh, const std::vector<quint32>& indices)                      { return addFaceToOpenVolumeMesh(_mesh, indices);                   }
1188 1189 1190 1191
int FileVTKPlugin::addFace(PolyhedralMesh*& _mesh, quint32 _index1, quint32 _index2, quint32 _index3) { return addFaceToOpenVolumeMesh(_mesh, _index1, _index2, _index3); }
void FileVTKPlugin::addVertexNormal(PolyhedralMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)  { addVertexNormalToOpenVolumeMesh(_mesh, _index, _normal);          }
void FileVTKPlugin::addFaceNormal(PolyhedralMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)    { addFaceNormalToOpenVolumeMesh(_mesh, _index, _normal);            }
bool FileVTKPlugin::writeASCIIData(std::ostream& _out, PolyhedralMesh& _mesh)                         { return writeASCIIDataOfOpenVolumeMesh(_out, _mesh);               }
1192
#endif //ENABLE_POLYHEDRALMESH_SUPPORT
1193

Max Lyon's avatar
Max Lyon committed
1194

1195
#ifdef ENABLE_TETRAHEDRALMESH_SUPPORT
Jan Möbius's avatar
Jan Möbius committed
1196 1197 1198 1199 1200
int FileVTKPlugin::addTetraCell(TetrahedralMesh*& _mesh, const std::vector<quint32>& indices)                 { return addTetraCellToOpenVolumeMesh(_mesh, indices);              }
int FileVTKPlugin::addHexaCell(TetrahedralMesh*& _mesh, const std::vector<quint32>& indices)                  { return addHexaCellToOpenVolumeMesh(_mesh, indices);               }
int FileVTKPlugin::addWedgeCell(TetrahedralMesh*& _mesh, const std::vector<quint32>& indices)                 { return addWedgeCellToOpenVolumeMesh(_mesh, indices);              }
int FileVTKPlugin::addPyramidCell(TetrahedralMesh*& _mesh, const std::vector<quint32>& indices)               { return addPyramidCellToOpenVolumeMesh(_mesh, indices);            }
int FileVTKPlugin::addFace(TetrahedralMesh*& _mesh, const std::vector<quint32>& indices)                      { return addFaceToOpenVolumeMesh(_mesh, indices);                   }
Max Lyon's avatar
Max Lyon committed
1201 1202 1203 1204
int FileVTKPlugin::addFace(TetrahedralMesh*& _mesh, quint32 _index1, quint32 _index2, quint32 _index3) { return addFaceToOpenVolumeMesh(_mesh, _index1, _index2, _index3); }
void FileVTKPlugin::addVertexNormal(TetrahedralMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)  { addVertexNormalToOpenVolumeMesh(_mesh, _index, _normal);          }
void FileVTKPlugin::addFaceNormal(TetrahedralMesh*& _mesh, quint32 _index, OpenMesh::Vec3d _normal)    { addFaceNormalToOpenVolumeMesh(_mesh, _index, _normal);            }
bool FileVTKPlugin::writeASCIIData(std::ostream& _out, TetrahedralMesh& _mesh)                         { return writeASCIIDataOfOpenVolumeMesh(_out, _mesh);               }
1205
#endif //ENABLE_TETRAHEDRALMESH_SUPPORT
Max Lyon's avatar
Max Lyon committed
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
//-----------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
//----------------------------------- end of cool helper function -------------------------------------
//-----------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------

FileVTKPlugin::BestMeshType FileVTKPlugin::findBestObjectType(QString _filename)
{
    QFile file(_filename);

    if ( !file.open(QIODevice::ReadOnly) ) {
      return BMT_None;
    }

    QTextStream in(&file);

    QString line = in.readLine();

    QStringList header = line.split(" ",QString::SkipEmptyParts);
    if ( header.size() != 5 ) {
      return BMT_None;
    }

    QString version = header[4];

    header.removeLast();

    QString magic = header.join(" ");

    if ( magic != "# vtk DataFile Version" ) {
      return BMT_None;
    }

    QString description = in.readLine();

    QString fileTypeStr = in.readLine();

    fileTypeStr = fileTypeStr.simplified();

    if ( fileTypeStr.toLower() == "binary" ) {
      binary_ = true;
    } else if ( fileTypeStr.toLower() == "ascii" ) {
      binary_ = false;
    } else {
      return BMT_None;
    }

    line = "";

    while ( line.simplified() == "" )
      line = in.readLine();

    QStringList datasetList =  line.split(" ",QString::SkipEmptyParts);

    if ( datasetList.size() != 2 ) {
      return BMT_None;
    }

    Dataset dataset;

    datasetList[1] = datasetList[1].simplified();

    if ( datasetList[1] == "STRUCTURED_POINTS" )
      dataset = STRUCTURED_POINTS;
    else if ( datasetList[1] == "STRUCTURED_GRID" )
      dataset = STRUCTURED_GRID;
    else if ( datasetList[1] == "RECTILINEAR_GRID" )
      dataset = RECTILINEAR_GRID;
    else if ( datasetList[1] == "POLYDATA" )
      dataset = POLYDATA;
    else if ( datasetList[1] == "UNSTRUCTURED_GRID" )
      dataset = UNSTRUCTURED_GRID;
    else {
      return BMT_None;
    }


1284
    if ((dataset == STRUCTURED_POINTS) || (dataset == STRUCTURED_GRID) || (dataset == RECTILINEAR_GRID) )
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    {
        // Just points so every type is ok. Just use TriMesh. (Apperently these aren't even supported.)
        return BMT_TriMesh;
    }
    else if (dataset == POLYDATA)
    {
        // The file could contain vertices, lines, polygons, or triangle strips.
        // So we will use either TriMesh or PolyMesh.
        //
        // Test if all polygons are triangles

        line = in.readLine();

        // Search for line "POLYGONS n size"
        while ( !line.contains("POLYGONS") ) {

            // stop at end of file!
            if ( in.atEnd() ) {
                // we didn't find polygons -> all primitives are either vertices, lines or trianglestrips
                return BMT_TriMesh;
            }

            line = in.readLine();
        }

        QStringList polygonsLine = line.split(" ",QString::SkipEmptyParts);

        // It has to contain the Keyword POLYGONS , the number of polygons to read and the total number of values to read ( each polygon: 1 + valence )
        if ( polygonsLine.size() != 3 ) {
            emit log(LOGERR,tr("Expected to get Points line with exactly 3 entries, but %1 found!").arg(polygonsLine.size()));
            return BMT_None;
        }

        bool ok = true;

        // Number of polygons to read
        quint32 polygoncount = polygonsLine[1].toUInt(&ok);

        if ( ! ok) {
            emit log(LOGERR,tr("Expected to get number of points and entries, but read %1 !").arg(polygonsLine.join(" ")));
            return BMT_None;
        }

        quint32 read = 0;
        while ( read < polygoncount) {

            // Read first integer describing number of indices
            quint32 valence;
            if ( !binary_ )
                in >> valence;
            else
                 in.device()->read((char*)&valence,sizeof(quint32));

            if (valence != 3)
            {
                // Polygone with more than 3 vertices found -> TriMesh not possible
                return BMT_PolyMesh;
            }

            // read rest
            quint32 index;

            for ( unsigned int i = 0 ; i < valence; ++i ) {

                // Read one index
                if ( !binary_ )
                    in >> index;
                else
                    in.device()->read((char*)&valence,sizeof(quint32));
            }
            ++read;
        }

        // if we reach this point, all polygons were triangles
        return BMT_TriMesh;

    }
    else /*if (dataset == UNSTRUCTURED_GRID)*/
    {
        // The file could contain all different kind of primitives.
        // We need to check if all of them are triangles.
        // If OpenVolumeMesh is supported we additionally check whether there are
        // Cell primitives, and if so, whether all of them are hexaherdral.

        line = in.readLine();

        // Search for line "CELL_TYPES n"
        while ( !line.contains("CELL_TYPES") ) {

            // stop at end of file!
            if ( in.atEnd() ) {
                // we didn't find the line "CELL_TYPES n" -> bad file
                return BMT_None;
            }

            line = in.readLine();
        }

        // Split the header line into components
        QStringList cellLine = line.split(" ",QString::SkipEmptyParts);

        // It has to contain the Keyword CELL_TYPES , the number of cells to read
        if ( cellLine.size() != 2 ) {
          emit log(LOGERR,tr("Expected to get CELL_TYPES line with exactly 2 entries, but %1 found!").arg(cellLine.size()));
          return BMT_None;
        }

        bool ok = true;
1393

1394 1395
        // Number of cells to read
        quint32 cellCountTypes = cellLine[1].toUInt(&ok);
1396

1397 1398 1399 1400
        if ( ! ok) {
          emit log(LOGERR,tr("Expected to get number of cell types, but read %1 !").arg(cellLine[1]));
          return BMT_None;
        }
1401

1402 1403 1404
        bool triMeshPossible = true;
        bool polyMeshPossible = true;

1405
#ifndef ENABLE_HEXAHEDRALMESH_SUPPORT
1406 1407 1408
        bool hexahedralMeshPossible = false;
#else
        bool hexahedralMeshPossible = true;
1409
#endif
1410
#ifndef ENABLE_POLYHEDRALMESH_SUPPORT
1411 1412 1413
        bool polyhedralMeshPossible = false;
#else
        bool polyhedralMeshPossible = true;
1414
#endif
1415
#ifndef ENABLE_TETRAHEDRALMESH_SUPPORT
Max Lyon's avatar
Max Lyon committed
1416 1417 1418 1419
        bool tetrahedralMeshPossible = false;
#else
        bool tetrahedralMeshPossible = true;
#endif
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434

        quint32 read = 0;
        while ( read < cellCountTypes) {

          // Read first integer describing number of indizes
          quint32 type;
          if ( !binary_ )
            in >> type;
          else
            in.device()->read((char*)&type,sizeof(quint32));


          if      (( 1 <= type ) && (type <=  6 ))
          {
              // vertex, poly vertex, line, poly line, triangle, triangle strip
Max Lyon's avatar
Max Lyon committed
1435 1436 1437
              // all mesh types possible except hexahedral mesh and tetrahedral mesh
            hexahedralMeshPossible = false;
            tetrahedralMeshPossible = false;
1438 1439 1440 1441
          }
          else if (( 7 <= type ) && (type <=  9 ))
          {
              // polygone, pixel (axis alligned quad), quad -> triMesh not possible
Max Lyon's avatar
Max Lyon committed
1442 1443
              // while polygon could be a triangle as well, we assume that it's not because
              // we hope the file author would have chosen type == 5 in that case
1444 1445
              triMeshPossible = false;
              hexahedralMeshPossible = false;
Max Lyon's avatar
Max Lyon committed
1446
              tetrahedralMeshPossible = false;
1447 1448
          }
          // TODO: ignore if no OpenVolumeMesh support
Max Lyon's avatar
Max Lyon committed
1449
          else if ( 10 == type )
1450
          {
Max Lyon's avatar
Max Lyon committed
1451 1452 1453 1454 1455 1456 1457 1458
              // tetra
              triMeshPossible = false;
              polyMeshPossible = false;
              hexahedralMeshPossible = false;
          }
          else if (( 13 == type ) || (type ==  14 ))
          {
              // wedge, pyramid
1459 1460 1461 1462
              // cannot be represented by anything other than polyhedral mesh
              triMeshPossible = false;
              polyMeshPossible = false;
              hexahedralMeshPossible = false;
Max Lyon's avatar
Max Lyon committed
1463 1464
              tetrahedralMeshPossible = false;

1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
          }
          else if (( 11 == type ) || ( 12 == type ))
          {
              // voxel, hexahedron
              // cannot be represented by open mesh
              triMeshPossible = false;
              polyMeshPossible = false;
          }


Jan Möbius's avatar
Jan Möbius committed
1475
          if ( in.status() != QTextStream::Ok ) {
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
            emit log(LOGERR,tr("Read corrupted cell type data!"));
            return BMT_None;
          }
          ++read;
        }

        if (triMeshPossible)
            return BMT_TriMesh;
        else if (polyMeshPossible)
            return BMT_PolyMesh;
        else if (hexahedralMeshPossible)
            return BMT_HexahedralMesh;
Max Lyon's avatar
Max Lyon committed
1488 1489
        else if (tetrahedralMeshPossible)
            return BMT_TetrahedralMesh;
1490 1491 1492 1493
        else if (polyhedralMeshPossible)
            return BMT_PolyhedralMesh;
        else
            return BMT_None;
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503

    }



}

int FileVTKPlugin::loadObject(QString _filename) {
  std::cerr << "Loading vtk file" << std::endl;

1504 1505
  BestMeshType bestType = findBestObjectType(_filename);

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
  QFile file(_filename);

  if ( !file.open(QIODevice::ReadOnly) ) {
    emit log(LOGERR,"Unable to open vtk file!");
    return -1;
  }

  QTextStream in(&file);

  std::cerr << "File is open!" << std::endl;

  QString line = in.readLine();

  std::cerr << "Got line: " << std::endl;
  std::cerr << line.toStdString() << std::endl;

  QStringList header = line.split(" ",QString::SkipEmptyParts);

  if ( header.size() != 5 ) {
    emit log(LOGERR,tr("Bad VTK header? ") + line);
    return -1;
  }

  QString version = header[4];

  header.removeLast();

  QString magic = header.join(" ");

  if ( magic != "# vtk DataFile Version" ) {
    emit log(LOGERR,tr("Bad VTK header magic? ") + magic);
    return -1;
  }

  QString description = in.readLine();

  QString fileTypeStr = in.readLine();

  fileTypeStr = fileTypeStr.simplified();

  if ( fileTypeStr.toLower() == "binary" ) {
    binary_ = true;
    emit log(LOGINFO,tr("Loading VTK binary file of version %1.").arg(version));
    emit log(LOGERR,tr("Not yet implemented!"));
  } else if ( fileTypeStr.toLower() == "ascii" ) {
    binary_ = false;
    emit log(LOGINFO,tr("Loading VTK ascii file of version %1.").arg(version));
  } else {
    emit log(LOGERR,tr("Bad VTK type? ") + fileTypeStr);
    return -1;
  }

  emit log(LOGINFO,description);

  line = "";

  while ( line.simplified() == "" )
    line = in.readLine();

  QStringList datasetList =  line.split(" ",QString::SkipEmptyParts);

  if ( datasetList.size() != 2 ) {
    emit log(LOGERR,tr("Bad dataset specification!"));
    return -1;
  }

  Dataset dataset;

  datasetList[1] = datasetList[1].simplified();

  if ( datasetList[1] == "STRUCTURED_POINTS" )
    dataset = STRUCTURED_POINTS;
  else if ( datasetList[1] == "STRUCTURED_GRID" )
    dataset = STRUCTURED_GRID;
  else if ( datasetList[1] == "RECTILINEAR_GRID" )
    dataset = RECTILINEAR_GRID;
  else if ( datasetList[1] == "POLYDATA" )
    dataset = POLYDATA;
  else if ( datasetList[1] == "UNSTRUCTURED_GRID" )
    dataset = UNSTRUCTURED_GRID;
  else {
    emit log(LOGERR,tr("Unknown dataset specification! %1").arg(datasetList[1]));
    return -1;
  }

1591 1592
  BaseObjectData* baseObj = 0;
  bool is_OpenVolumeMesh = false;
1593

1594
  if ( (forceTriangleMesh_) || (bestType == BMT_TriMesh) ){
1595

1596 1597 1598
    // add a triangle mesh
    int id = -1;
    emit addEmptyObject(DATA_TRIANGLE_MESH, id);
1599

1600
    TriMeshObject* object(0);
1601

1602
    if(PluginFunctions::getObject( id, object)){
1603

1604 1605
      TriMesh* _mesh;
      PluginFunctions::getMesh(id,_mesh);
1606

1607 1608 1609 1610
      if ( _mesh != 0 ) {
        if ( !loadMesh(in,_mesh,dataset) ) {
          emit log(LOGERR,"Unable to load mesh!");
          return -1;
1611
        }
1612 1613 1614 1615
      } else {
        emit log(LOGERR,"Unable to add empty triangle mesh!");
        return -1;
      }
1616

1617
      baseObj = object;
1618
    }
1619

1620 1621 1622 1623 1624
  }
  // If no type can represent the object in the file just use PolyMesh
  // and load as much as possible
  else if ((bestType == BMT_PolyMesh) || (bestType == BMT_None))
  {
1625

1626 1627
    int id = -1;
    emit addEmptyObject(DATA_POLY_MESH, id);
1628 1629


1630
    PolyMeshObject* object(0);
1631

1632
    if(PluginFunctions::getObject( id, object)){
1633

1634 1635
      PolyMesh* _mesh(0);
      PluginFunctions::getMesh(id, _mesh);
1636

1637 1638 1639 1640
      if ( _mesh != 0 ) {
        if ( !loadMesh(in,_mesh,dataset) ) {
          emit log(LOGERR,"Unable to load mesh!");
          return -1;
1641
        }
1642 1643 1644 1645
      } else {
        emit log(LOGERR,"Unable to add empty poly mesh!");
        return -1;
      }
1646

1647
      baseObj = object;
1648

1649 1650 1651
    }


1652
  }
1653
#ifdef ENABLE_POLYHEDRALMESH_SUPPORT
1654 1655 1656
  else if (bestType == BMT_PolyhedralMesh)
  {
    // add a Polyhedral mesh
1657
    is_OpenVolumeMesh = true;
1658 1659
    int id = -1;
    emit addEmptyObject(DATA_POLYHEDRAL_MESH, id);
1660

1661
    PolyhedralMeshObject* object(0);
1662

1663
    if(PluginFunctions::getObject( id, object)){
1664

1665 1666
      PolyhedralMesh* _mesh;
      _mesh = PluginFunctions::polyhedralMesh(object);
1667

1668 1669 1670 1671
      if ( _mesh != 0 ) {
        if ( !loadMesh(in,_mesh,dataset) ) {
          emit log(LOGERR,"Unable to load mesh!");
          return -1;
1672
        }
1673 1674 1675 1676
      } else {
        emit log(LOGERR,"Unable to add empty polyhedral mesh!");
        return -1;
      }
1677

1678
      baseObj = object;
1679
    }
1680 1681

  }
1682 1683
#endif //ENABLE_POLYHEDRALMESH_SUPPORT
#ifdef ENABLE_HEXAHEDRALMESH_SUPPORT
1684 1685
  else if (bestType == BMT_HexahedralMesh)
  {
Max Lyon's avatar
Max Lyon committed
1686
    // add a hexahedral mesh
1687
    is_OpenVolumeMesh = true;
1688 1689
    int id = -1;
    emit addEmptyObject(DATA_HEXAHEDRAL_MESH, id);
1690

1691
    HexahedralMeshObject* object(0);
1692

1693
    if(PluginFunctions::getObject( id, object)){
1694

1695 1696
      HexahedralMesh* _mesh;
      _mesh = PluginFunctions::hexahedralMesh(object);
1697

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
      if ( _mesh != 0 ) {
        if ( !loadMesh(in,_mesh,dataset) ) {
          emit log(LOGERR,"Unable to load mesh!");
          return -1;
        }
      } else {
        emit log(LOGERR,"Unable to add empty hexahedral mesh!");
        return -1;
      }
      baseObj = object;
    }
1709

1710
  }
1711 1712
#endif //ENABLE_HEXAHEDRALMESH_SUPPORT
#ifdef ENABLE_TETRAHEDRALMESH_SUPPORT
Max Lyon's avatar
Max Lyon committed
1713 1714 1715
  else if (bestType == BMT_TetrahedralMesh)
  {
    // add a tetrahedral mesh
1716
    is_OpenVolumeMesh = true;
Max Lyon's avatar
Max Lyon committed
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
    int id = -1;
    emit addEmptyObject(DATA_TETRAHEDRAL_MESH, id);

    TetrahedralMeshObject* object(0);

    if(PluginFunctions::getObject( id, object)){

      TetrahedralMesh* _mesh;
      _mesh = PluginFunctions::tetrahedralMesh(object);

      if ( _mesh != 0 ) {
        if ( !loadMesh(in,_mesh,dataset) ) {
          emit log(LOGERR,"Unable to load mesh!");
          return -1;
        }
      } else {
        emit log(LOGERR,"Unable to add empty tetrahedral mesh!");
        return -1;
      }
      baseObj = object;
    }

  }
1740
#endif //ENABLE_TETRAHEDRALMESH_SUPPORT
1741

1742 1743 1744 1745
  if (baseObj)
  {
    baseObj->setFromFileName(_filename);
    baseObj->setName(baseObj->filename());
1746

1747 1748 1749 1750 1751
    if (is_OpenVolumeMesh)
    {
      // Go into solid flat shaded mode
      baseObj->setObjectDrawMode(ACG::SceneGraph::DrawModes::getDrawMode("Cells (flat shaded)"));
    }
1752

1753
    emit updatedObject(baseObj->id(), UPDATE_ALL);
1754

1755 1756
    //general stuff
    emit openedFile( baseObj->id() );
1757

1758 1759
    return baseObj->id();
  }
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925

  emit log(LOGERR,tr("Error in load mesh!"));

  return -1;


}

template <typename MeshT>
bool FileVTKPlugin::loadMeshPoints(QString _spec, QTextStream& _in,MeshT*& _mesh){

  std::cerr << "loadMeshPoints" << std::endl;

  bool ok = true;

  // Split the header line into components
  QStringList pointsLine = _spec.split(" ",QString::SkipEmptyParts);

  // It has to contain the Keyword POINTS , the number of points to read and the datatype of the points
  if ( pointsLine.size() != 3 ) {
    emit log(LOGERR,tr("Expected to get Points line with exactly 3 entries, but %1 found!").arg(pointsLine.size()));
    return false;
  }

  // Get the number of points to read
  quint32 points = pointsLine[1].toUInt(&ok);

  if ( ! ok) {
    emit log(LOGERR,tr("Expected to get number of points, but read %1 !").arg(pointsLine[1]));
    return false;
  }

  // In OpenMesh we use doubles for the point representation
  OpenMesh::Vec3d vec;

  quint32 read = 0;
  while ( read < points ) {


    if ( binary_ ) {

      // Read binary float values
      if ( pointsLine[2] == "float" ) {
        // Read floats
        OpenMesh::Vec3f vecf;
        _in.device()->read((char*)&vecf[0],sizeof(float));
        _in.device()->read((char*)&vecf[1],sizeof(float));
        _in.device()->read((char*)&vecf[2],sizeof(float));

        // convert
        vec = vecf;
      } else {
        emit log(LOGERR,tr("Not implemented data type %1 !").arg(pointsLine[2]));
        return false;
      }

    } else {
      // Don't care about original type, as we read text and convert it anyway.
      _in >> vec[0] >> vec[1] >> vec[2];
    }

    // Next point to read
    ++read;

    // Check if the stream is still ok
    if ( _in.status() == QTextStream::Ok ) {
      _mesh->add_vertex(vec);
    } else {
      emit log(LOGERR,tr("Read corrupted point data!"));
      return false;
    }

  }

  if (binary_) {
    if ( pointsLine[2] == "float" ) {
      // Reposition text stream. We read points * 3 * sizeof(float)
      // For the text stream we calculate the position in charactersso convert it witth 1.0 / sizeof(char)
      _in.seek(_in.pos() + read * 3 * sizeof(float) / sizeof(char) );
    }
  }

  return true;

}

template <typename MeshT>
bool FileVTKPlugin::loadMeshLines(QString _spec,QTextStream& _in,MeshT*& _mesh) {
  std::cerr << "loadMeshLines" << std::endl;

  bool ok = true;

  // Split the header line into components
  QStringList linesLine = _spec.split(" ",QString::SkipEmptyParts);

  // It has to contain the Keyword LINES , the number of polygons to read and the total number of values to read ( each line: 1 + valence )
  if ( linesLine.size() != 3 ) {
    emit log(LOGERR,tr("Expected to get LINES line with exactly 3 entries, but %1 found!").arg(linesLine.size()));
    return false;
  }

  // umber of lines to read
  quint32 linecount = linesLine[1].toUInt(&ok);

  // number of ints in the whole line description!
  quint32 entrycount = linesLine[2].toUInt(&ok);

  if ( ! ok) {
    emit log(LOGERR,tr("Expected to get number of lines and entries, but read %1 !").arg(linesLine.join(" ")));
    return false;
  }

  quint32 read = 0;

  while ( read < linecount) {

    // Read first integer describing number of indizes in the current line
    quint32 valence;

    if ( !binary_ )
      _in >> valence;
    else
      _in.device()->read((char*)&valence,sizeof(quint32));


    quint32 index;

    if ( _in.status() == QTextStream::Ok ) {

      if ( !binary_ ) {
        for ( unsigned int i = 0 ; i < valence; ++i )
          _in >> index;
      } else {
        for ( unsigned int i = 0 ; i < valence; ++i )
          _in.device