OBJImporter.cc 38.1 KB
Newer Older
1
/*===========================================================================*\
Martin Schultz's avatar
Martin Schultz committed
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
 *                                                                           *
 *                             OpenFlipper                                   *
 *           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.              *
 *                                                                           *
40
41
\*===========================================================================*/

Jan Möbius's avatar
Jan Möbius committed
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

#include "OBJImporter.hh"

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

/// base class needs virtual destructor
OBJImporter::~OBJImporter(){
  
}

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

/// add a vertex with coordinate \c _point
VertexHandle OBJImporter::addVertex(const Vec3f& _point){
  vertices_.push_back( _point );
  
  return vertices_.size()-1;
}

/// get vertex with given index
Vec3f OBJImporter::vertex(unsigned int _index){
  
  if ( vertices_.size() > _index )
    return vertices_[ _index ];
  else
    return Vec3f();
}

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

/// add texture coordinates
int OBJImporter::addTexCoord(const Vec2f& _coord){
  texCoords_.push_back( _coord );
  
  return texCoords_.size()-1;
}

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

/// add a normal
int OBJImporter::addNormal(const Vec3f& _normal){
  normals_.push_back( _normal );
  
  return normals_.size()-1;
}

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

/// set degree U direction
void OBJImporter::setDegreeU(int _degree){
  degreeU_ = _degree;
}

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

/// set degree V direction
void OBJImporter::setDegreeV(int _degree){
  degreeV_ = _degree;
}


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

/// get current degree
int OBJImporter::degreeU(){
  return degreeU_;
}

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

/// get current degree
int OBJImporter::degreeV(){
  return degreeV_;
}

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

/// add a mesh
void OBJImporter::setObject(BaseObject* _object, int _groupId) {

    if((unsigned int)_groupId >= triMeshes_.size()) {
        std::cerr << "Error: Group does not exist!" << std::endl;
        return;
    }

    if(PluginFunctions::polyMeshObject(_object->id()) != NULL) {

        polyMeshes_[_groupId] = PluginFunctions::polyMeshObject(_object->id());
        addUsedVertices(_groupId);

    } else if(PluginFunctions::triMeshObject(_object->id()) != NULL) {

        triMeshes_[_groupId] = PluginFunctions::triMeshObject(_object->id());
        addUsedVertices(_groupId);
    }
#ifdef ENABLE_BSPLINECURVE_SUPPORT
    else if(PluginFunctions::bsplineCurveObject(PluginFunctions::baseObjectData(_object)) != NULL) {

        bSplineCurves_[_groupId] = PluginFunctions::bsplineCurveObject(PluginFunctions::baseObjectData(_object));
    }
#endif
#ifdef ENABLE_BSPLINESURFACE_SUPPORT
    else if(PluginFunctions::bsplineSurfaceObject(PluginFunctions::baseObjectData(_object)) != NULL) {

        bSplineSurfaces_[_groupId] = PluginFunctions::bsplineSurfaceObject(PluginFunctions::baseObjectData(_object));
    }
#endif
    else {
        std::cerr << "Error: Cannot add object. Type is unknown!" << std::endl;
    }
}

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

/// get id of the active object
int OBJImporter::currentObject(){

    return currentGroup_;
}

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

/// get the active polyMesh
PolyMesh* OBJImporter::currentPolyMesh(){

    return polyMeshes_[currentGroup_]->mesh();
}

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

/// get the active triMesh
TriMesh* OBJImporter::currentTriMesh(){

    return triMeshes_[currentGroup_]->mesh();
}

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

#ifdef ENABLE_BSPLINECURVE_SUPPORT

BSplineCurve* OBJImporter::currentCurve(){

    return bSplineCurves_[currentGroup_]->splineCurve();
}
  
#endif

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

#ifdef ENABLE_BSPLINESURFACE_SUPPORT

BSplineSurface* OBJImporter::currentSurface(){

    return bSplineSurfaces_[currentGroup_]->splineSurface();
}
  
#endif

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

/// add all vertices that are used to the mesh (in correct order)
void OBJImporter::addUsedVertices(int _groupId) {

    if (isTriangleMesh(_groupId)) {

        //handle triangle meshes
        TriMesh* curMesh = triMeshes_[_groupId]->mesh();
        if (curMesh == NULL)
            return;

        // add all vertices to the mesh

216
        if(usedVertices_.size() <= static_cast<size_t>(_groupId)) return;
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

        for(std::map<int, VertexHandle>::const_iterator it = usedVertices_[_groupId].begin();
                it != usedVertices_[_groupId].end(); ++it) {

            if (it->first >= (int)vertices_.size()) {
                std::cerr << "Error: Vertex ID too large" << std::endl;
                continue;
            }

            if (vertexMapTri_[_groupId].find(it->first) == vertexMapTri_[_groupId].end()) {
                vertexMapTri_[_groupId].insert(std::pair<int, TriMesh::VertexHandle>(it->first, curMesh->add_vertex((TriMesh::Point)vertices_[it->first])));
            }
        }

    } else if (isPolyMesh(_groupId)) {

        //handle triangle meshes
        PolyMesh* curMesh = polyMeshes_[_groupId]->mesh();
        if (curMesh == NULL)
            return;

        //add all vertices to the mesh

240
        if(usedVertices_.size() <= static_cast<size_t>(_groupId)) return;
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383

        for(std::map<int, VertexHandle>::const_iterator it = usedVertices_[_groupId].begin();
                it != usedVertices_[_groupId].end(); ++it) {

            if (it->first >= (int)vertices_.size()) {
                std::cerr << "Error: Vertex ID too large" << std::endl;
                continue;
            }

            if (vertexMapPoly_[_groupId].find(it->first) == vertexMapPoly_[_groupId].end()) {
                vertexMapPoly_[_groupId].insert(std::pair<int, PolyMesh::VertexHandle>(it->first, curMesh->add_vertex((PolyMesh::Point)vertices_[it->first])));
            }
        }
    }
}

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

/// set vertex texture coordinate
void OBJImporter::setVertexTexCoord(VertexHandle _vh, int _texCoordID){
  
  if ( isTriangleMesh( currentObject() ) ){
  
    //handle triangle meshes
    if ( !currentTriMesh() ) return;
    
    if ( _texCoordID < (int) texCoords_.size() ){
    
      //perhaps request texCoords for the mesh
      if ( !currentTriMesh()->has_vertex_texcoords2D() )
        currentTriMesh()->request_vertex_texcoords2D();
      
      //set the texCoords
      if ( vertexMapTri_[currentGroup_].find( _vh ) != vertexMapTri_[currentGroup_].end() )
        currentTriMesh()->set_texcoord2D( vertexMapTri_[currentGroup_][_vh], texCoords_[ _texCoordID ] );

    }else{
      std::cerr << "Error: TexCoord ID too large" << std::endl;
    }
  
  } else if ( isPolyMesh( currentObject() ) ){
    
    //handle poly meshes
    if ( !currentPolyMesh() ) return;
    
    if ( _texCoordID < (int) texCoords_.size() ){

      //perhaps request texCoords for the mesh
      if ( !currentPolyMesh()->has_vertex_texcoords2D() )
        currentPolyMesh()->request_vertex_texcoords2D();
      
      //set the texCoords
      if ( vertexMapPoly_[currentGroup_].find( _vh ) != vertexMapPoly_[currentGroup_].end() )
        currentPolyMesh()->set_texcoord2D( vertexMapPoly_[currentGroup_][_vh], texCoords_[ _texCoordID ] );

    }else{
      std::cerr << "Error: TexCoord ID too large" << std::endl;
    }
  }
}

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

/// set vertex normal
void OBJImporter::setNormal(int _index, int _normalID){
  
  if ( isTriangleMesh( currentObject() ) ){
  
    //handle triangle meshes
    if ( !currentTriMesh() ) return;
    
    if ( _normalID < (int) normals_.size() )
    {
      if ( vertexMapTri_[currentGroup_].find( _index ) != vertexMapTri_[currentGroup_].end() )
      {
        TriMesh::VertexHandle vh = vertexMapTri_[currentGroup_][_index];
        TriMesh::Normal normal =  static_cast<TriMesh::Normal>( normals_[ _normalID ] );
        TriMesh* currentMesh = currentTriMesh();
        currentMesh->set_normal( vh , normal );
        objectOptions_[ currentGroup_ ] |= NORMALS;

        storedTriHENormals_[vh] = normal;
      }

    }else{
      std::cerr << "Error: normal ID too large" << std::endl;
    }
  
  } else if ( isPolyMesh( currentObject() ) ){
    
    //handle poly meshes
    if ( !currentPolyMesh() ) return;
    
    if ( _normalID < (int) normals_.size() )
    {
      if ( vertexMapPoly_[currentGroup_].find( _index ) != vertexMapPoly_[currentGroup_].end() )
      {
        PolyMesh::VertexHandle vh = vertexMapPoly_[currentGroup_][_index];
        PolyMesh::Point normal =  static_cast<PolyMesh::Point>( normals_[ _normalID ] );
        PolyMesh* currentMesh = currentPolyMesh();
        currentMesh->set_normal( vh , normal );
        objectOptions_[ currentGroup_ ] |= NORMALS;

        storedPolyHENormals_[vh] = normal;
      }

    }else{
      std::cerr << "Error: normal ID too large" << std::endl;
    }
    
  }
}

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

bool OBJImporter::addFace(const VHandles& _indices, OpenMesh::FaceHandle &_outFH, std::vector< TriMesh::VertexHandle > &_outTriVertices, std::vector< PolyMesh::VertexHandle > &_outPolyVertices)
{
  if ( isTriangleMesh( currentObject() ) ){

    //handle triangle meshes
    if ( !currentTriMesh() ) return false;

    addedFacesTri_[currentGroup_].clear();

    for (unsigned int i=0; i < _indices.size(); i++){

      if ( vertexMapTri_[currentGroup_].find( _indices[i] ) != vertexMapTri_[currentGroup_].end() ){

        _outTriVertices.push_back( vertexMapTri_[currentGroup_][ _indices[i] ] );

      }else{
        std::cerr << "Error: cannot add face. undefined index (" <<  _indices[i] << ")" << std::endl;
        return false;
      }
    }

    size_t n_faces = currentTriMesh()->n_faces();

    OpenMesh::FaceHandle fh = currentTriMesh()->add_face( _outTriVertices );

    //remember all new faces
    if(!fh.is_valid()) {
      // Store non-manifold face
384
      invalidFaces_[currentGroup_].push_back(_outTriVertices);
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399

    } else {
      // Store recently added face
      for( size_t i=0; i < currentTriMesh()->n_faces()-n_faces; ++i )
        addedFacesTri_[currentGroup_].push_back( TriMesh::FaceHandle(n_faces+i) );

      //write stored normals into the half edges
      if (!currentTriMesh()->has_halfedge_normals())
        currentTriMesh()->request_halfedge_normals();

      //iterate over all incoming haldedges of the added face
      for (TriMesh::FaceHalfedgeIter fh_iter = currentTriMesh()->fh_begin(fh);
          fh_iter != currentTriMesh()->fh_end(fh); ++fh_iter)
      {
        //and write the normals to it
400
        TriMesh::HalfedgeHandle heh = *fh_iter;
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
        TriMesh::VertexHandle vh = currentTriMesh()->to_vertex_handle(heh);
        std::map<TriMesh::VertexHandle,TriMesh::Normal>::iterator iter = storedTriHENormals_.find(vh);
        if (iter != storedTriHENormals_.end())
          currentTriMesh()->set_normal(heh,iter->second);
      }
      storedTriHENormals_.clear();
    }

    _outFH = fh;
    return true;

  } else if ( isPolyMesh( currentObject() ) ){

    //handle poly meshes
    if ( !currentPolyMesh() ) return false;

    for (unsigned int i=0; i < _indices.size(); i++){

      if ( vertexMapPoly_[currentGroup_].find( _indices[i] ) != vertexMapPoly_[currentGroup_].end() ){

        _outPolyVertices.push_back( vertexMapPoly_[currentGroup_][ _indices[i] ] );

      }else{
        std::cerr << "Error: cannot add face. undefined index (" <<  _indices[i] << ")" << std::endl;
        return false;
      }
    }

    if(!vertexListIsManifold(_outPolyVertices)) {
      std::cerr << "Face consists of multiple occurrences of the same vertex!" << std::endl;
      return false;
    }

    OpenMesh::FaceHandle fh = currentPolyMesh()->add_face( _outPolyVertices );

    if(!fh.is_valid()) {
      // Store non-manifold face
438
      invalidFaces_[currentGroup_].push_back(_outPolyVertices);
439
440
441
442
443
444
445
446
447
448
449
450
    } else {
      addedFacePoly_ = fh;

      //write stored normals into the half edges
      if (!currentPolyMesh()->has_halfedge_normals())
        currentPolyMesh()->request_halfedge_normals();

      //iterate over all incoming haldedges of the added face
      for (PolyMesh::FaceHalfedgeIter fh_iter = currentPolyMesh()->fh_begin(fh);
          fh_iter != currentPolyMesh()->fh_end(fh); ++fh_iter)
      {
        //and write the normals to it
451
        PolyMesh::HalfedgeHandle heh = *fh_iter;
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
486
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        PolyMesh::VertexHandle vh = currentPolyMesh()->to_vertex_handle(heh);
        std::map<PolyMesh::VertexHandle,PolyMesh::Normal>::iterator iter = storedTriHENormals_.find(vh);
        if (iter != storedTriHENormals_.end())
          currentPolyMesh()->set_normal(heh,iter->second);
      }
      storedPolyHENormals_.clear();

    }

    _outFH = fh;
    return true;
  }
  return false;
}

/// add a face with indices _indices refering to vertices
void OBJImporter::addFace(const VHandles& _indices){
  OpenMesh::FaceHandle fh;
  std::vector< TriMesh::VertexHandle > triVertices;
  std::vector< PolyMesh::VertexHandle > polyVertices;
  addFace(_indices,fh,triVertices,polyVertices);

}

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

bool OBJImporter::vertexListIsManifold(const std::vector<PolyMesh::VertexHandle>& _vertices) const {

    std::set<PolyMesh::VertexHandle> check;
    for(std::vector<PolyMesh::VertexHandle>::const_iterator v_it = _vertices.begin();
            v_it != _vertices.end(); ++v_it) {
        check.insert(*v_it);
    }

    return (check.size() == _vertices.size());
}

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

/// add face and texture coordinates
void OBJImporter::addFace(const VHandles& _indices, const std::vector<int>& _face_texcoords){
  
  
  OpenMesh::FaceHandle fh;
  std::vector< TriMesh::VertexHandle > triVertices;
  std::vector< PolyMesh::VertexHandle > polyVertices;
  if(!addFace(_indices, fh, triVertices, polyVertices) || !fh.is_valid())
    return;

  if ( isTriangleMesh(currentObject()) )
  {
    //perhaps request texCoords for the mesh
    if ( !currentTriMesh()->has_halfedge_texcoords2D() )
      currentTriMesh()->request_halfedge_texcoords2D();

    //now add texCoords

    // get first halfedge handle
    TriMesh::HalfedgeHandle cur_heh = currentTriMesh()->halfedge_handle( addedFacesTri_[currentGroup_][0] );
    TriMesh::HalfedgeHandle end_heh = currentTriMesh()->prev_halfedge_handle(cur_heh);

    // find start heh
    while( currentTriMesh()->to_vertex_handle(cur_heh) != triVertices[0] && cur_heh != end_heh )
      cur_heh = currentTriMesh()->next_halfedge_handle( cur_heh);

    for(unsigned int i=0; i<_face_texcoords.size(); ++i)
    {
      if ( _face_texcoords[i] < (int)texCoords_.size() ){

        PolyMesh::TexCoord2D tex = OpenMesh::vector_cast<TriMesh::TexCoord2D>( texCoords_[ _face_texcoords[i] ] );
        currentTriMesh()->set_texcoord2D(cur_heh, tex);

        cur_heh = currentTriMesh()->next_halfedge_handle(cur_heh);

      } else
        std::cerr << "Error: cannot set texture coordinates. undefined index." << std::endl;
    }
  }else if (isPolyMesh(currentObject()))
  {
    addedFacePoly_ = fh;

    //perhaps request texCoords for the mesh
    if ( !currentPolyMesh()->has_halfedge_texcoords2D() )
      currentPolyMesh()->request_halfedge_texcoords2D();

    //now add texCoords

    if ( addedFacePoly_.is_valid() ) {
      // get first halfedge handle
      PolyMesh::HalfedgeHandle cur_heh = currentPolyMesh()->halfedge_handle( addedFacePoly_ );
      PolyMesh::HalfedgeHandle end_heh = currentPolyMesh()->prev_halfedge_handle(cur_heh);

      // find start heh
      while( currentPolyMesh()->to_vertex_handle(cur_heh) != polyVertices[0] && cur_heh != end_heh )
        cur_heh = currentPolyMesh()->next_halfedge_handle( cur_heh);

      for(unsigned int i=0; i<_face_texcoords.size(); ++i)
      {
        if ( _face_texcoords[i] < (int)texCoords_.size() ){

          PolyMesh::TexCoord2D tex = OpenMesh::vector_cast<PolyMesh::TexCoord2D>( texCoords_[ _face_texcoords[i] ] );
          currentPolyMesh()->set_texcoord2D(cur_heh, tex);

          cur_heh = currentPolyMesh()->next_halfedge_handle(cur_heh);

        }else
          std::cerr << "Error: cannot set texture coordinates. undefined index." << std::endl;
      }
    }
  }
}

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

void OBJImporter::addMaterial(std::string _materialName){

  
  if ( isTriangleMesh( currentObject() ) ){
  
    //handle triangle meshes
    if ( !currentTriMesh() ) return;
    
  
    if ( materials_.find( _materialName ) != materials_.end() ){
      
      Material& mat = materials_[ _materialName ];

      //get textureIndex Property
      OpenMesh::FPropHandleT< int > indexProperty;

Weizhen Huang's avatar
Weizhen Huang committed
582
583
      BaseObjectData* triMeshObj = PluginFunctions::baseObjectData(object(currentObject()));

584
585
586
587
588
589
590
591
592
593
594
595
      if ( hasTexture( currentObject() ) ){

        bool textureAllowed = ! ( objectOptions_[ currentObject() ] & FORCE_NOTEXTURES );
        
        if ( textureAllowed ){
        
          // Add texture index property if it doesn't exist yet
          if (! currentTriMesh()->get_property_handle(indexProperty,TEXTUREINDEX) )
            currentTriMesh()->add_property(indexProperty,TEXTUREINDEX);
        }
      }

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
      // set materialNode color
      if (mat.has_Ka()) {
          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Ka());
          triMeshObj->materialNode()->set_ambient_color(color);
      }

      if (mat.has_Kd()) {
          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Kd());
          triMeshObj->materialNode()->set_diffuse_color(color);
      }

      if (mat.has_Ks()) {
          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Ks());
          triMeshObj->materialNode()->set_specular_color(color);
      }

      if (mat.has_Ke()) {
          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Ke());
          triMeshObj->materialNode()->set_emission(color);
      }

      if (mat.has_Ni()) {
          float Ni = mat.Ni();
          triMeshObj->materialNode()->set_indexOfRefraction(Ni);
      }

      if (mat.has_Ns()) {
          float shininess = mat.Ns();
          triMeshObj->materialNode()->set_shininess(shininess);
      }

      if (mat.has_illum()) {
          triMeshObj->materialNode()->set_refractive(mat.isRefractive());
      }


632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
      for (unsigned int i=0; i < addedFacesTri_[currentGroup_].size(); i++){
      
        if ( mat.has_Kd() ) {
          bool colorAllowed = ! ( objectOptions_[ currentObject() ] & FORCE_NOCOLOR );
          
          if ( currentTriMesh()->has_face_colors() && colorAllowed ){

            TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Kd() );

            // Get alpha if available
            if (mat.has_Tr() ) {
              color[3] = mat.Tr();
            } else {
              color[3] = 1.0;
            }
            currentTriMesh()->set_color(addedFacesTri_[currentGroup_][i], color  );
            objectOptions_[ currentObject() ] |= FACECOLOR;
          }
        }

        bool textureAllowed = ! ( objectOptions_[ currentObject() ] & FORCE_NOTEXTURES );

        // Set the texture index in the face index property
        if ( mat.has_Texture() ) {

          if ( hasTexture( currentObject() ) && textureAllowed )
            currentTriMesh()->property(indexProperty, addedFacesTri_[currentGroup_][i]) = mat.map_Kd_index();

        } else {
          // If we don't have the info, set it to no texture
          if ( hasTexture( currentObject() ) && textureAllowed )
            currentTriMesh()->property(indexProperty, addedFacesTri_[currentGroup_][i]) = 0;
        }
665

666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
      }
    }
    
  } else if ( isPolyMesh( currentObject() ) ){
  
    //handle poly meshes
    if ( !currentPolyMesh() ) return;
    
    if ( materials_.find( _materialName ) != materials_.end() ){
      
      Material& mat = materials_[ _materialName ];
      
      //get textureIndex Property
      OpenMesh::FPropHandleT< int > indexProperty;

681
682
      BaseObjectData* polyMeshObj = PluginFunctions::baseObjectData(object(currentObject()));

683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
      if ( hasTexture( currentObject() ) ){

        bool textureAllowed = ! ( objectOptions_[ currentObject() ] & FORCE_NOTEXTURES );
        
        if ( textureAllowed ){

          if (! currentPolyMesh()->get_property_handle(indexProperty,TEXTUREINDEX) )
            currentPolyMesh()->add_property(indexProperty,TEXTUREINDEX);
        }
      }
      
      if ( mat.has_Kd() ) {
        bool colorAllowed = ! ( objectOptions_[ currentObject() ] & FORCE_NOCOLOR );
        
        if ( currentPolyMesh()->has_face_colors() && colorAllowed && addedFacePoly_.is_valid()  ){

          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Kd() );

          // Get alpha if available
          if (mat.has_Tr() ) {
            color[3] = mat.Tr();
          } else {
            color[3] = 1.0;
          }

          currentPolyMesh()->set_color(addedFacePoly_, color );
709
          polyMeshObj->materialNode()->set_diffuse_color(color);
710
711
712
713
          objectOptions_[ currentObject() ] |= FACECOLOR;
        }
      }

714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
      // set materialNode color
      if (mat.has_Ka()) {
          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Ka());
          polyMeshObj->materialNode()->set_ambient_color(color);
      }

      if (mat.has_Ks()) {
          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Ks());
          polyMeshObj->materialNode()->set_specular_color(color);
      }

      if (mat.has_Ke()) {
          TriMesh::Color color = OpenMesh::color_cast< OpenMesh::Vec4f >(mat.Ke());
          polyMeshObj->materialNode()->set_emission(color);
      }

      if (mat.has_Ni()) {
          float Ni = mat.Ni();
          polyMeshObj->materialNode()->set_indexOfRefraction(Ni);
      }

      if (mat.has_Ns()) {
          float shininess = mat.Ns();
          polyMeshObj->materialNode()->set_shininess(shininess);
      }

      if (mat.has_illum()) {
          polyMeshObj->materialNode()->set_refractive(mat.isRefractive());
      }

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
      bool textureAllowed = ! ( objectOptions_[ currentObject() ] & FORCE_NOTEXTURES );

      // Set the texture index in the face index property
      if ( mat.has_Texture() ) {

        if ( hasTexture( currentObject() ) && textureAllowed && addedFacePoly_.is_valid())
          currentPolyMesh()->property(indexProperty, addedFacePoly_) = mat.map_Kd_index();
        
      } else {
        // If we don't have the info, set it to no texture
        if ( hasTexture( currentObject() ) && textureAllowed && addedFacePoly_.is_valid())
          currentPolyMesh()->property(indexProperty, addedFacePoly_) = 0;
      }
    }
  }
}

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

// force all meshes to be opened with specific type
void OBJImporter::forceMeshType( ObjectOptions _meshType ){
  
  for (unsigned int i=0; i < objectOptions_.size(); i++){
    
    bool isMesh = (objectOptions_[i] & TRIMESH) | (objectOptions_[i] & POLYMESH);
    bool correctType = objectOptions_[i] & _meshType;
    
    if ( isMesh && !correctType )
      objectOptions_[i] = _meshType;
  }
}

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

bool OBJImporter::isTriangleMesh(int _objectID){
  return objectOptions_[ _objectID ] & TRIMESH;
}

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

bool OBJImporter::isPolyMesh(int _objectID){
  return objectOptions_[ _objectID ] & POLYMESH;
}

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

bool OBJImporter::isCurve(int _objectID){
  return objectOptions_[ _objectID ] & CURVE;
}

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

bool OBJImporter::isSurface(int _objectID){
  return objectOptions_[ _objectID ] & SURFACE;
}

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

bool OBJImporter::hasNormals(int _objectID){
  
  return objectOptions_[ _objectID ] & NORMALS;
}

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

bool OBJImporter::hasTexture(int _objectID){
  
  return objectOptions_[ _objectID ] & TEXTURE;
}

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

bool OBJImporter::hasTextureCoords(int _objectID){
  return objectOptions_[ _objectID ] & TEXCOORDS;
}

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

unsigned int OBJImporter::n_vertices(){
  return vertices_.size();
}

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

unsigned int OBJImporter::n_normals(){
  return normals_.size();
}

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

unsigned int OBJImporter::n_texCoords(){
  return texCoords_.size();
}

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

unsigned int OBJImporter::objectCount(){
  return groupNames_.size();
}

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

BaseObject* OBJImporter::object(int _objectID) {

  if (objectCount() == 0 || objectCount() <= (unsigned int)_objectID)
    return NULL;

  if(triMeshes_[_objectID] != NULL)             return triMeshes_[_objectID];
  else if(polyMeshes_[_objectID] != NULL)       return polyMeshes_[_objectID];
#ifdef ENABLE_BSPLINECURVE_SUPPORT
  else if(bSplineCurves_[_objectID] != NULL)    return bSplineCurves_[_objectID];
#endif
#ifdef ENABLE_BSPLINESURFACE_SUPPORT
  else if(bSplineSurfaces_[_objectID] != NULL)  return bSplineSurfaces_[_objectID];
#endif

  return NULL;
}

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

MaterialList& OBJImporter::materials(){
  return materials_;
}

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

QString OBJImporter::path(){
  return path_;
}

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

void OBJImporter::setPath(QString _path){
  path_ = _path;
}

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

void OBJImporter::setObjectOptions(ObjectOptions _options) {

    while((unsigned int)currentGroup_ >= objectOptions_.size()) {
        objectOptions_.push_back(NONE);
    }

    objectOptions_[currentGroup_] = _options;
}

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

std::vector< OBJImporter::ObjectOptions >& OBJImporter::objectOptions(){
  return objectOptions_;
}

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

// check if object with given id has given option
bool OBJImporter::hasOption( unsigned int _id, ObjectOptions _option ){
  
  if (_id >= objectOptions_.size())
    return false;
  
  return objectOptions_[_id] & _option;
}

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

void OBJImporter::setObjectName(int _objectID, QString _name){

  BaseObject* obj = object( _objectID );
  
  if ( obj != 0 )
    obj->setName( _name );
}

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

int OBJImporter::addGroup(const QString& _groupName) {

    QString group = _groupName.trimmed();
    int id = groupId(group);
    if(id == -1) {
        groupNames_.push_back(group);
        vertexMapTri_.push_back(std::map<int,TriMesh::VertexHandle>());
        vertexMapPoly_.push_back(std::map<int,TriMesh::VertexHandle>());
929
        invalidFaces_.push_back(std::vector< OMVHandles >());
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
        addedFacesTri_.push_back(std::vector< TriMesh::FaceHandle>());

        triMeshes_.push_back(NULL);
        polyMeshes_.push_back(NULL);
#ifdef ENABLE_BSPLINECURVE_SUPPORT
        bSplineCurves_.push_back(NULL);
#endif
#ifdef ENABLE_BSPLINESURFACE_SUPPORT
        bSplineSurfaces_.push_back(NULL);
#endif
        return groupNames_.size() - 1;
    }
    return id;
}

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

int OBJImporter::groupId(const QString& _groupName) const {

    for(unsigned int i = 0; i < groupNames_.size(); ++i) {
        if(groupNames_[i] == _groupName.trimmed()) return i;
    }
    return -1;
}

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

const QString OBJImporter::groupName(const int _grpId) const {

    if((unsigned int)_grpId < groupNames_.size()) {
        return groupNames_[_grpId];
    }
    return QString();
}

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

void OBJImporter::setGroupName(const int _grp, const QString& _name) {

    if((unsigned int)_grp >= groupNames_.size()) return;

    groupNames_[_grp] = _name;
}

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

void OBJImporter::setCurrentGroup(const int _current) {

    currentGroup_ = _current;
}

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

int OBJImporter::currentGroup() const {

    return currentGroup_;
}

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

void OBJImporter::finish() {

	// Duplicate vertices of non-manifold faces
	// and add them as new isolated face
994
	if(invalidFaces_[currentGroup_].empty()) return;
995
996
997
998
999
1000

	if (isTriangleMesh(currentObject())) {

		// Handle triangle meshes
		if ( !currentTriMesh() ) return;

1001
1002
		for(std::vector<OMVHandles>::iterator it = invalidFaces_[currentGroup_].begin();
				it != invalidFaces_[currentGroup_].end(); ++it) {
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

			OMVHandles& vhandles = *it;

			// double vertices
			for (unsigned int j = 0; j < vhandles.size(); ++j)
			{
			  TriMesh::Point p = currentTriMesh()->point(vhandles[j]);
			  vhandles[j] = currentTriMesh()->add_vertex(p);
			  // DO STORE p, reference may not work since vertex array
			  // may be relocated after adding a new vertex !

			  // Mark vertices of failed face as non-manifold
			  if (currentTriMesh()->has_vertex_status()) {
				  currentTriMesh()->status(vhandles[j]).set_fixed_nonmanifold(true);
			  }
			}

			// add face
			OpenMesh::FaceHandle fh = currentTriMesh()->add_face(vhandles);

			// Mark failed face as non-manifold
			if (currentTriMesh()->has_face_status())
				currentTriMesh()->status(fh).set_fixed_nonmanifold(true);

			// Mark edges of failed face as non-two-manifold
			if (currentTriMesh()->has_edge_status()) {
				TriMesh::FaceEdgeIter fe_it = currentTriMesh()->fe_iter(fh);
Matthias Möller's avatar
Matthias Möller committed
1030
1031
				for(; fe_it.is_valid(); ++fe_it) {
					currentTriMesh()->status(*fe_it).set_fixed_nonmanifold(true);
1032
1033
1034
1035
1036
1037
1038
1039
1040
				}
			}
		}

	} else {

		// Handle Polymeshes
		if ( !currentPolyMesh() ) return;

1041
1042
		for(std::vector<OMVHandles>::iterator it = invalidFaces_[currentGroup_].begin();
				it != invalidFaces_[currentGroup_].end(); ++it) {
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

			OMVHandles& vhandles = *it;

			// double vertices
			for (unsigned int j = 0; j < vhandles.size(); ++j)
			{
			  PolyMesh::Point p = currentPolyMesh()->point(vhandles[j]);
			  vhandles[j] = currentPolyMesh()->add_vertex(p);
			  // DO STORE p, reference may not work since vertex array
			  // may be relocated after adding a new vertex !

			  // Mark vertices of failed face as non-manifold
			  if (currentPolyMesh()->has_vertex_status()) {
				  currentPolyMesh()->status(vhandles[j]).set_fixed_nonmanifold(true);
			  }
			}

			// add face
			OpenMesh::FaceHandle fh = currentPolyMesh()->add_face(vhandles);

			// Mark failed face as non-manifold
			if (currentPolyMesh()->has_face_status())
				currentPolyMesh()->status(fh).set_fixed_nonmanifold(true);

			// Mark edges of failed face as non-two-manifold
			if (currentPolyMesh()->has_edge_status()) {
				PolyMesh::FaceEdgeIter fe_it = currentPolyMesh()->fe_iter(fh);
Matthias Möller's avatar
Matthias Möller committed
1070
1071
				for(; fe_it.is_valid(); ++fe_it) {
					currentPolyMesh()->status(*fe_it).set_fixed_nonmanifold(true);
1072
1073
1074
1075
1076
1077
				}
			}
		}
	}

	// Clear faces
1078
	invalidFaces_[currentGroup_].clear();
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
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
}

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

#ifdef ENABLE_BSPLINECURVE_SUPPORT
void OBJImporter::setCurveGroupId(const unsigned int _count, const int _id) {
  curvesMap_[_count] = _id;
}
#endif

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

#ifdef ENABLE_BSPLINECURVE_SUPPORT
int OBJImporter::getCurveGroupId(const unsigned int _count) {
  return curvesMap_[_count];
}
#endif

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

#ifdef ENABLE_BSPLINECURVE_SUPPORT
void OBJImporter::setCurveParentId(const int _curveGroup, const int _parentGroup) {
  curveParentGroupMap_[_curveGroup] = _parentGroup;
}
#endif

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

#ifdef ENABLE_BSPLINECURVE_SUPPORT
int OBJImporter::getCurveParentId(const int _curveGroup) {
  return curveParentGroupMap_[_curveGroup];
}
#endif

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

#ifdef ENABLE_BSPLINESURFACE_SUPPORT
void OBJImporter::setSurfaceGroupId(const unsigned int _count, const int _id) {
  surfacesMap_[_count] = _id;
}
#endif

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

#ifdef ENABLE_BSPLINESURFACE_SUPPORT
int OBJImporter::getSurfaceGroupId(const unsigned int _count) {
  return surfacesMap_[_count];
}
#endif

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

#ifdef ENABLE_BSPLINESURFACE_SUPPORT
void OBJImporter::setSurfaceParentId(const int _surfaceGroup, const int _parentGroup) {
  surfaceParentGroupMap_[_surfaceGroup] = _parentGroup;
}
#endif

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

#ifdef ENABLE_BSPLINESURFACE_SUPPORT
int OBJImporter::getSurfaceParentId(const int _surfaceGroup) {
  return surfaceParentGroupMap_[_surfaceGroup];
}
#endif

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

//used materials
const std::vector<std::string> OBJImporter::usedMaterials(unsigned int _objectID){

  if (_objectID >= usedMaterials_.size())
    return std::vector<std::string>();
  else
    return usedMaterials_[ _objectID ];
}

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

void OBJImporter::useMaterial( std::string _materialName ){

  while( (int)usedMaterials_.size() - 1 < currentObject() )
    usedMaterials_.push_back( std::vector<std::string>() );
  
  //check that it is not added already
  for (unsigned int i=0; i < usedMaterials_[ currentObject() ].size(); i++ )
    if ( usedMaterials_[ currentObject() ][i] == _materialName )
      return;
  
  usedMaterials_[ currentObject() ].push_back( _materialName );
  
  objectOptions_[ currentObject() ] |= TEXTURE;
}

///used vertices
void OBJImporter::useVertex(int _vertex_index){

    while(currentGroup_ >= (int)usedVertices_.size()) {
        usedVertices_.push_back(std::map<int,VertexHandle>());
    }

    usedVertices_[currentGroup_].insert(std::pair<int,VertexHandle>(_vertex_index,-1));

//  while( (int)usedVertices_.size() - 1 < (int) objectOptions_.size() )
//    usedVertices_.push_back( std::set<VertexHandle>() );
//
//  usedVertices_[ objectOptions_.size() ].insert( _vertex );
}

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