FileOBJ.cc 66.2 KB
Newer Older
Dirk Wilden's avatar
Dirk Wilden committed
1
/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
2
3
*                                                                            *
*                              OpenFlipper                                   *
Jan Möbius's avatar
Jan Möbius committed
4
*      Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen       *
Jan Möbius's avatar
Jan Möbius committed
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
*                           www.openflipper.org                              *
*                                                                            *
*--------------------------------------------------------------------------- *
*  This file is part of OpenFlipper.                                         *
*                                                                            *
*  OpenFlipper is free software: you can redistribute it and/or modify       *
*  it under the terms of the GNU Lesser General Public License as            *
*  published by the Free Software Foundation, either version 3 of            *
*  the License, or (at your option) any later version with the               *
*  following exceptions:                                                     *
*                                                                            *
*  If other files instantiate templates or use macros                        *
*  or inline functions from this file, or you compile this file and          *
*  link it with other files to produce an executable, this file does         *
*  not by itself cause the resulting executable to be covered by the         *
*  GNU Lesser General Public License. This exception does not however        *
*  invalidate any other reasons why the executable file might be             *
*  covered by the GNU Lesser General Public License.                         *
*                                                                            *
*  OpenFlipper is distributed in the hope that it will be useful,            *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of            *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
*  GNU Lesser General Public License for more details.                       *
*                                                                            *
*  You should have received a copy of the GNU LesserGeneral Public           *
*  License along with OpenFlipper. If not,                                   *
*  see <http://www.gnu.org/licenses/>.                                       *
*                                                                            *
Dirk Wilden's avatar
Dirk Wilden committed
33
34
35
\*===========================================================================*/

/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
36
37
38
39
40
*                                                                            *
*   $Revision$                                                       *
*   $LastChangedBy$                                                *
*   $Date$                     *
*                                                                            *
Dirk Wilden's avatar
Dirk Wilden committed
41
\*===========================================================================*/
42
43
44
45
#include <ACG/GL/GLState.hh>

#include "OpenFlipper/BasePlugin/PluginFunctions.hh"
#include "OpenFlipper/common/GlobalOptions.hh"
Dirk Wilden's avatar
Dirk Wilden committed
46

47
48
49
50
#include <OpenMesh/Core/IO/IOManager.hh>

#include <OpenFlipper/ACGHelper/DrawModeConverter.hh>
#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
Matthias Möller's avatar
Matthias Möller committed
51
52
53
54
55
56
57

#if QT_VERSION >= 0x050000 
  #include <QtWidgets>
#else
  #include <QtGui>
#endif

Dirk Wilden's avatar
Dirk Wilden committed
58
59
60
61
62
63
64
65
66
#include <QFileInfo>
#include <QSettings>
#include <QPushButton>

#include "FileOBJ.hh"

#include <iostream>


67
68
69
70
71
72
// Defines for the type handling drop down box
#define TYPEAUTODETECT 0
#define TYPEASK        1
#define TYPEPOLY       2
#define TYPETRIANGLE   3

Dirk Wilden's avatar
Dirk Wilden committed
73
74
75
76
/// Constructor
FileOBJPlugin::FileOBJPlugin()
: loadOptions_(0),
  saveOptions_(0),
77
78
79
80
81
82
83
84
85
  saveBinary_(0),
  saveVertexColor_(0),
  saveFaceColor_(0),
  saveAlpha_(0),
  saveNormals_(0),
  saveTexCoords_(0),
  saveTextures_(0),
  saveCopyTextures_(0),
  saveCreateTexFolder_(0),
86
87
  savePrecisionLabel_(0),
  savePrecision_(0),
88
  saveDefaultButton_(0),
Dirk Wilden's avatar
Dirk Wilden committed
89
  triMeshHandling_(0),
90
91
92
93
94
95
96
  loadVertexColor_(0),
  loadFaceColor_(0),
  loadAlpha_(0),
  loadNormals_(0),
  loadTexCoords_(0),
  loadTextures_(0),
  loadDefaultButton_(0),
Dirk Wilden's avatar
Dirk Wilden committed
97
  forceTriangleMesh_(false),
98
99
  forcePolyMesh_(false),
  textureIndexPropFetched_(false)
Dirk Wilden's avatar
Dirk Wilden committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
{
}

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

void FileOBJPlugin::initializePlugin() {
}

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

QString FileOBJPlugin::getLoadFilters() {
    return QString( tr("Alias/Wavefront ( *.obj )") );
};

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

QString FileOBJPlugin::getSaveFilters() {
    return QString( tr("Alias/Wavefront ( *.obj )") );
};

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

DataType  FileOBJPlugin::supportedType() {
123
    DataType type = DATA_POLY_MESH | DATA_TRIANGLE_MESH | DATA_GROUP;
124

Dirk Wilden's avatar
Dirk Wilden committed
125
126
127
128
129
130
131
132
    #ifdef ENABLE_BSPLINECURVE_SUPPORT
      type |= DATA_BSPLINE_CURVE;
    #endif

    #ifdef ENABLE_BSPLINESURFACE_SUPPORT
      type |= DATA_BSPLINE_SURFACE;
    #endif

Dirk Wilden's avatar
Dirk Wilden committed
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
    return type;
}

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

void trimString( std::string& _string) {
  // Trim Both leading and trailing spaces

  size_t start = _string.find_first_not_of(" \t\r\n");
  size_t end   = _string.find_last_not_of(" \t\r\n");

  if(( std::string::npos == start ) || ( std::string::npos == end))
    _string = "";
  else
    _string = _string.substr( start, end-start+1 );
}

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

bool FileOBJPlugin::readMaterial(QString _filename, OBJImporter& _importer)
{
  std::string line;
  std::string keyWrd;
  std::string textureName;

  std::string matName;
  Material    mat;
  float       f1,f2,f3;
  bool        insideDefintion = false;
  int         textureId = 1;
163
164


Dirk Wilden's avatar
Dirk Wilden committed
165
  //open stream
Jan Möbius's avatar
Jan Möbius committed
166
  std::fstream matStream( _filename.toUtf8(), std::ios_base::in );
Dirk Wilden's avatar
Dirk Wilden committed
167
168

  if ( !matStream ){
Dirk Wilden's avatar
Dirk Wilden committed
169
    emit log(LOGERR, tr("readMaterial : cannot open file %1").arg(_filename) );
Dirk Wilden's avatar
Dirk Wilden committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    return false;
  }

  //clear temp material
  mat.cleanup();

  //parse material file
  while( matStream && !matStream.eof() )
  {
    std::getline(matStream,line);
    if ( matStream.bad() ){
      emit log(LOGERR, tr("readMaterial : Warning! Could not read file properly!"));
      return false;
    }

    if ( line.empty() )
      continue;

    std::stringstream stream(line);

    stream >> keyWrd;

192
    if( ( isspace(line[0]) && line[0] != '\t' ) || line[0] == '#' )
Dirk Wilden's avatar
Dirk Wilden committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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
    {
      if (insideDefintion && !matName.empty() && mat.is_valid())
      {
        _importer.materials()[matName] = mat;
        mat.cleanup();
      }
    }

    else if (keyWrd == "newmtl") // begin new material definition
    {
      stream >> matName;
      insideDefintion = true;
    }

    else if (keyWrd == "Kd") // diffuse color
    {
      stream >> f1; stream >> f2; stream >> f3;

      if( !stream.fail() )
        mat.set_Kd(f1,f2,f3);
    }

    else if (keyWrd == "Ka") // ambient color
    {
      stream >> f1; stream >> f2; stream >> f3;

      if( !stream.fail() )
        mat.set_Ka(f1,f2,f3);
    }

    else if (keyWrd == "Ks") // specular color
    {
      stream >> f1; stream >> f2; stream >> f3;

      if( !stream.fail() )
        mat.set_Ks(f1,f2,f3);
    }
#if 0
    else if (keyWrd == "illum") // diffuse/specular shading model
    {
      ; // just skip this
    }

    else if (keyWrd == "Ns") // Shininess [0..200]
    {
      ; // just skip this
    }

    else if (keyWrd == "map_") // map images
    {
      // map_Ks, specular map
      // map_Ka, ambient map
      // map_Bump, bump map
      // map_d,  opacity map
      ; // just skip this
    }
#endif
    else if (keyWrd == "map_Kd" ) {
      // Get the rest of the line, removing leading or trailing spaces
      // This will define the filename of the texture
      std::getline(stream,textureName);
      trimString(textureName);
      if ( ! textureName.empty() )
        mat.set_map_Kd( textureName, textureId++ );
    }
    else if (keyWrd == "Tr") // transparency value
    {
      stream >> f1;

      if( !stream.fail() )
        mat.set_Tr(f1);
    }
    else if (keyWrd == "d") // transparency value
    {
      stream >> f1;

      if( !stream.fail() )
        mat.set_Tr(f1);
    }

    if ( matStream && insideDefintion && mat.is_valid() && !matName.empty())
      _importer.materials()[matName] = mat;
  }


//   for ( MaterialList::iterator material = _importer.materials().begin(); material != _importer.materials().end(); material++ )
//   {
//     emit log("Material:" + QString(((*material).first).c_str()) );
//   }

  emit log( tr("%1 materials loaded.").arg( _importer.materials().size() ) );

  return true;
}

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

290
291
void FileOBJPlugin::createAllGroupObjects(OBJImporter& _importer) {

292
    for(unsigned int i = 0; i < _importer.numGroups(); ++i) {
Dirk Wilden's avatar
Dirk Wilden committed
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
        // Get group name
        QString name = _importer.groupName(i);
        convertToOBJName(name);

        if ( _importer.isTriangleMesh( i )  ){

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

            BaseObjectData* object(0);

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

                _importer.setObject(object, i);

                object->setPath(_importer.path());
                object->setName(name);
            }

        } else if (_importer.isPolyMesh( i )) {

            int id = -1;
            emit addEmptyObject(DATA_POLY_MESH, id);

            BaseObjectData* object(0);

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

                _importer.setObject(object, i);

                object->setPath(_importer.path());
                object->setName(name);
            }
        }
Dirk Wilden's avatar
Dirk Wilden committed
329

Dirk Wilden's avatar
Dirk Wilden committed
330
331
#ifdef ENABLE_BSPLINECURVE_SUPPORT

332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
        else if (_importer.isCurve( i )) {

            int id = -1;
            emit addEmptyObject(DATA_BSPLINE_CURVE, id);

            BaseObjectData* object(0);

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

                _importer.setObject(object, i);

                object->setPath(_importer.path());
                object->setName(name);
            }
        }

Dirk Wilden's avatar
Dirk Wilden committed
348
349
350
351
#endif

#ifdef ENABLE_BSPLINESURFACE_SUPPORT

352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
        else if (_importer.isSurface( i )) {

            int id = -1;
            emit addEmptyObject(DATA_BSPLINE_SURFACE, id);

            BaseObjectData* object(0);

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

                _importer.setObject(object, i);

                object->setPath(_importer.path());
                object->setName(name);
            }
        }

Dirk Wilden's avatar
Dirk Wilden committed
368
#endif
369
370
371
372
373
374
375
376
377
378
379
380
381
382

        //force gui settings
        if (OpenFlipper::Options::gui() && loadOptions_ != 0) {

            if (!loadFaceColor_->isChecked())
                _importer.objectOptions()[ i ] |= OBJImporter::FORCE_NOCOLOR;

            if (!loadNormals_->isChecked())
                _importer.objectOptions()[ i ] |= OBJImporter::FORCE_NONORMALS;

            if (!loadTexCoords_->isChecked() || !loadTextures_->isChecked())
                _importer.objectOptions()[ i ] |= OBJImporter::FORCE_NOTEXTURES;
        }
    }
Dirk Wilden's avatar
Dirk Wilden committed
383
384
}

Mike Kremer's avatar
Mike Kremer committed
385
void FileOBJPlugin::convertToOBJName(QString& _name) {
386

Mike Kremer's avatar
Mike Kremer committed
387
    QFileInfo fi(_name);
388

Mike Kremer's avatar
Mike Kremer committed
389
    QString n = fi.baseName();
390

Mike Kremer's avatar
Mike Kremer committed
391
392
393
    _name = n.trimmed() + ".obj";
}

394
395
396
397
398
399
400
401
402
403
404
405
/// creates a backup of the original per vertex/face texture coordinates
template <class MeshT>
void FileOBJPlugin::backupTextureCoordinates(MeshT& _mesh) {

    // Create a backup of the original per Vertex texture Coordinates
    if (_mesh.has_vertex_texcoords2D()) {

      OpenMesh::VPropHandleT< typename MeshT::TexCoord2D > oldVertexCoords;
      if (!_mesh.get_property_handle(oldVertexCoords, "Original Per Vertex Texture Coords"))
        _mesh.add_property(oldVertexCoords, "Original Per Vertex Texture Coords");

      for (typename MeshT::VertexIter v_it = _mesh.vertices_begin(); v_it != _mesh.vertices_end(); ++v_it)
Matthias Möller's avatar
Matthias Möller committed
406
        _mesh.property(oldVertexCoords, *v_it) =  _mesh.texcoord2D(*v_it);
407
408
409
410
411
412
413
414
415
416
417

    }

    // Create a backup of the original per Face texture Coordinates
    if (_mesh.has_halfedge_texcoords2D()) {

      OpenMesh::HPropHandleT< typename MeshT::TexCoord2D > oldHalfedgeCoords;
      if (!_mesh.get_property_handle(oldHalfedgeCoords,"Original Per Face Texture Coords"))
        _mesh.add_property(oldHalfedgeCoords,"Original Per Face Texture Coords");

      for (typename MeshT::HalfedgeIter he_it = _mesh.halfedges_begin(); he_it != _mesh.halfedges_end(); ++he_it)
Matthias Möller's avatar
Matthias Möller committed
418
        _mesh.property(oldHalfedgeCoords, *he_it) =  _mesh.texcoord2D(*he_it);
419
420
421
422

    }
}

Dirk Wilden's avatar
Dirk Wilden committed
423
424
425
426
427
428
429
430

//add textures to the mesh
void FileOBJPlugin::addTextures(OBJImporter& _importer, int _objectID ){

  // TODO : If only one Texture, use single Texturing mode
  if ( true ) {

    BaseObject* object = _importer.object(_objectID);
431

Dirk Wilden's avatar
Dirk Wilden committed
432
433
    if (!object)
      return;
434

Dirk Wilden's avatar
Dirk Wilden committed
435
436
437
    std::map< int,int > newMapping;
    // zero ( no texture ) always maps to to zero
    newMapping[0]=0;
438

Dirk Wilden's avatar
Dirk Wilden committed
439
    const std::vector<std::string> matNames = _importer.usedMaterials( _objectID );
440

Jan Möbius's avatar
Jan Möbius committed
441
    for (unsigned int i=0; i < matNames.size(); i++){
442

Dirk Wilden's avatar
Dirk Wilden committed
443
      Material& material = _importer.materials()[ matNames[i] ];
444

Dirk Wilden's avatar
Dirk Wilden committed
445
      int textureId = -1;
446

Dirk Wilden's avatar
Dirk Wilden committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
      QString textureBlock = QString( material.map_Kd().c_str());


      QStringList options = textureBlock.split(" ",QString::SkipEmptyParts);

      while ( options.size() > 1 ) {
        if ( options[0] == "-blendu" ) {
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-blendv" ) {
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-cc" ) {
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-clamp" ) {
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-mm" ) {
          options.pop_front();
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-o" ) {
          options.pop_front();
          options.pop_front();
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-s" ) {
          options.pop_front();
          options.pop_front();
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-t" ) {
          options.pop_front();
          options.pop_front();
          options.pop_front();
          options.pop_front();
        } else if ( options[0] == "-texres" ) {
          options.pop_front();
          options.pop_front();
        } else  {
          break;
        }
      }

      QString fullName = _importer.path() + QDir::separator() + options.join(" ");

      QFileInfo info(fullName);
      if ( info.exists() )
Mike Kremer's avatar
Mike Kremer committed
496
        emit addMultiTexture("OBJ Data", info.baseName().trimmed(), fullName, object->id(), textureId );
Dirk Wilden's avatar
Dirk Wilden committed
497
498
499
500
      else {
        emit log(LOGWARN, tr("Unable to load texture image %1").arg( QString(material.map_Kd().c_str()) ) );
        addMultiTexture("OBJ Data","Unknown Texture image " + QString::number(textureId), "unknown.png", object->id(), textureId );
      }
501

Dirk Wilden's avatar
Dirk Wilden committed
502
503
      newMapping[ material.map_Kd_index() ] = textureId;
    }
504

Dirk Wilden's avatar
Dirk Wilden committed
505
    //now map all texture indices to the real texture indices used in OpenFlipper
506

Dirk Wilden's avatar
Dirk Wilden committed
507
    OpenMesh::FPropHandleT< int > indexProperty;
508

Dirk Wilden's avatar
Dirk Wilden committed
509
510
    //handle PolyMeshes
    PolyMeshObject* polyMeshObj = dynamic_cast< PolyMeshObject* > (object);
511

Dirk Wilden's avatar
Dirk Wilden committed
512
    if ( polyMeshObj ){
513

Dirk Wilden's avatar
Dirk Wilden committed
514
515
516
517
518
      PolyMesh& mesh = *(polyMeshObj->mesh());

      PolyMesh::FaceIter f_it;
      PolyMesh::FaceIter f_end = mesh.faces_end();

519
      if (! mesh.get_property_handle(indexProperty,TEXTUREINDEX) )
Dirk Wilden's avatar
Dirk Wilden committed
520
        return;
521

Dirk Wilden's avatar
Dirk Wilden committed
522
      for (f_it = mesh.faces_begin(); f_it != f_end; ++f_it)
Matthias Möller's avatar
Matthias Möller committed
523
        mesh.property(indexProperty, *f_it) = newMapping[ mesh.property(indexProperty, *f_it) ];
524

525
      backupTextureCoordinates(mesh);
526

Dirk Wilden's avatar
Dirk Wilden committed
527
528
      return;
    }
529

Dirk Wilden's avatar
Dirk Wilden committed
530
531
    //handle new TriMeshes
    TriMeshObject* triMeshObj = dynamic_cast< TriMeshObject* > (object);
532

Dirk Wilden's avatar
Dirk Wilden committed
533
    if ( triMeshObj ){
534

Dirk Wilden's avatar
Dirk Wilden committed
535
536
537
538
539
      TriMesh& mesh = *(triMeshObj->mesh());

      TriMesh::FaceIter f_it;
      TriMesh::FaceIter f_end = mesh.faces_end();

540
      if (! mesh.get_property_handle(indexProperty,TEXTUREINDEX) )
Dirk Wilden's avatar
Dirk Wilden committed
541
        return;
542

Dirk Wilden's avatar
Dirk Wilden committed
543
      for (f_it = mesh.faces_begin(); f_it != f_end; ++f_it)
Matthias Möller's avatar
Matthias Möller committed
544
        mesh.property(indexProperty, *f_it) = newMapping[ mesh.property(indexProperty, *f_it) ];
545

546
      backupTextureCoordinates(mesh);
547

Dirk Wilden's avatar
Dirk Wilden committed
548
549
550
551
552
553
554
      return;
    }
  }
}

void FileOBJPlugin::readOBJFile(QString _filename, OBJImporter& _importer)
{
555

Dirk Wilden's avatar
Dirk Wilden committed
556
  QString path = QFileInfo(_filename).absolutePath();
557

Dirk Wilden's avatar
Dirk Wilden committed
558
  //setup filestream
559

Jan Möbius's avatar
Jan Möbius committed
560
  std::fstream input( _filename.toUtf8(), std::ios_base::in );
Dirk Wilden's avatar
Dirk Wilden committed
561
562

  if ( !input.is_open() || !input.good() ){
Dirk Wilden's avatar
Dirk Wilden committed
563
    emit log(LOGERR, tr("readOBJFile : cannot open file %1").arg(_filename) );
Dirk Wilden's avatar
Dirk Wilden committed
564
565
566
    return;
  }

Dirk Wilden's avatar
Dirk Wilden committed
567
568
569
570
  QString currentFileName = QFileInfo(_filename).fileName() ;

  ReaderMode mode = NONE;

Dirk Wilden's avatar
Dirk Wilden committed
571
572
  std::string line;
  std::string keyWrd;
Dirk Wilden's avatar
Dirk Wilden committed
573
  std::string nextKeyWrd = "";
Dirk Wilden's avatar
Dirk Wilden committed
574

Jan Möbius's avatar
Jan Möbius committed
575
#ifdef ENABLE_BSPLINECURVE_SUPPORT
576
  unsigned int curveCount = 0;
Jan Möbius's avatar
Jan Möbius committed
577
578
579
#endif

#ifdef ENABLE_BSPLINESURFACE_SUPPORT
580
  unsigned int surfaceCount = 0;
Jan Möbius's avatar
Jan Möbius committed
581
#endif
582

Dirk Wilden's avatar
Dirk Wilden committed
583
  float x, y, z, u, v;
Jan Möbius's avatar
Jan Möbius committed
584
  int   deg;
Dirk Wilden's avatar
Dirk Wilden committed
585
586
587
588
589

  std::vector<VertexHandle> vhandles;
  std::vector<int>          face_texcoords;
  std::string               matname;

Matthias Möller's avatar
Matthias Möller committed
590
#if defined (ENABLE_BSPLINECURVE_SUPPORT) || defined (ENABLE_BSPLINESURFACE_SUPPORT)
Dirk Wilden's avatar
Dirk Wilden committed
591
592
  std::vector< int > cpIndices;
  std::vector< double > knotsU,knotsV;
Matthias Möller's avatar
Matthias Möller committed
593
#endif
594

Dirk Wilden's avatar
Dirk Wilden committed
595
  int faceCount = 0;
596

597
598
  // We have to keep track of the already read number of vertices to resolve relative (negative indices)
  int currentVertexCount = 0;
599

600
601
  // We have to keep track of the already read number of Texture coordinates to resolve relative (negative indices)
  int currentTextureCoordCount = 0;
602

603
604
  // We have to keep track of the already read number of normals to resolve relative (negative indices)
  int currentNormalCount = 0;
Dirk Wilden's avatar
Dirk Wilden committed
605

606
607
608
609
610
  // keeps track if faces belong to a group or the default group
  bool inGroup = false;
  // keeps track if the first face of a mesh has been read yet or not
  bool firstFace = true;

Dirk Wilden's avatar
Dirk Wilden committed
611
  _importer.setPath( path );
612

613
614
615
616
617
618
  // Set filename for default mesh
  _importer.setGroupName(0, currentFileName);

  // Now add all meshes for every group (if exists)
  createAllGroupObjects(_importer);

Dirk Wilden's avatar
Dirk Wilden committed
619
620
621
622
623
624
625
626
627
628
  while( input && !input.eof() )
  {
    std::getline(input,line);
    if ( input.bad() ){
      emit log(LOGERR, tr("readOBJFile : Warning! Could not read file properly!"));
      return;
    }

    // Trim Both leading and trailing spaces
    trimString(line);
629

Dirk Wilden's avatar
Dirk Wilden committed
630
    // comment
631
    if ( line.empty() || line[0] == '#' || isspace(line[0]) ) {
Dirk Wilden's avatar
Dirk Wilden committed
632
633
634
635
636
      continue;
    }

    std::stringstream stream(line);

Dirk Wilden's avatar
Dirk Wilden committed
637
638
639
640
641
642
643
644
    //unless the keyWrd for the new line is not determined by the previous line
    //read it from stream
    if (nextKeyWrd == "")
      stream >> keyWrd;
    else {
      keyWrd = nextKeyWrd;
      nextKeyWrd = "";
    }
Dirk Wilden's avatar
Dirk Wilden committed
645
646

    // material file
Dirk Wilden's avatar
Dirk Wilden committed
647
    if (mode == NONE && keyWrd == "mtllib")
Dirk Wilden's avatar
Dirk Wilden committed
648
649
650
651
652
    {
      std::string matString;

      // This will define the filename of the texture
      std::getline(stream,matString);
653

Dirk Wilden's avatar
Dirk Wilden committed
654
655
656
657
658
659
660
661
      QString matFile = path + QDir::separator() + QString( matString.c_str() ).trimmed();

      emit log( tr("Loading material file: %1").arg( matFile ) );

      readMaterial( matFile, _importer );
    }

    // usemtl
Dirk Wilden's avatar
Dirk Wilden committed
662
    else if (mode == NONE && keyWrd == "usemtl")
Dirk Wilden's avatar
Dirk Wilden committed
663
664
665
666
667
668
    {
      stream >> matname;
      if ( _importer.materials().find(matname)==_importer.materials().end() )
      {
        emit log( LOGERR, tr("Warning! Material '%1' not defined in material file").arg( QString(matname.c_str()) ) );
        matname="";
669

Dirk Wilden's avatar
Dirk Wilden committed
670
      }else{
671

Dirk Wilden's avatar
Dirk Wilden committed
672
        Material& mat = _importer.materials()[matname];
673

Mike Kremer's avatar
Mike Kremer committed
674
        if ( mat.has_Texture() ){
Dirk Wilden's avatar
Dirk Wilden committed
675
          //add object if not already there
676
677
678
//          if (_importer.currentObject() == -1) {
//            addNewObject(_importer, currentFileName );
//          }
Dirk Wilden's avatar
Dirk Wilden committed
679

Dirk Wilden's avatar
Dirk Wilden committed
680
          _importer.useMaterial( matname );
Dirk Wilden's avatar
Dirk Wilden committed
681
        }
Dirk Wilden's avatar
Dirk Wilden committed
682
      }
683
684
    }
    else if (mode == NONE && keyWrd == "v")
685
    {
686
687
688
     if (!firstFace)
       firstFace = true;

689
     currentVertexCount++;
Dirk Wilden's avatar
Dirk Wilden committed
690
691
    }
    // texture coord
Dirk Wilden's avatar
Dirk Wilden committed
692
    else if (mode == NONE && keyWrd == "vt")
Dirk Wilden's avatar
Dirk Wilden committed
693
    {
694
695
696
      if (!firstFace)
        firstFace = true;

697
698
      // New texture coordinate read so increase counter
      currentTextureCoordCount++;
699

Dirk Wilden's avatar
Dirk Wilden committed
700
701
702
703
704
705
706
707
      stream >> u; stream >> v;

      if ( !stream.fail() ){

        _importer.addTexCoord( OpenMesh::Vec2f(u, v) );

      }else{

708
        emit log( LOGERR, tr("Could not add TexCoord. Possible NaN or Inf?\nOnly single 2D texture coordinate per vertex allowed"));
Dirk Wilden's avatar
Dirk Wilden committed
709
710
711
712
713
      }
    }


    // normal
Dirk Wilden's avatar
Dirk Wilden committed
714
    else if (mode == NONE && keyWrd == "vn")
Dirk Wilden's avatar
Dirk Wilden committed
715
    {
716
717
718
      if (!firstFace)
        firstFace = true;

719
720
      // New normal read so increase counter
      currentNormalCount++;
721

Dirk Wilden's avatar
Dirk Wilden committed
722
723
724
725
      stream >> x; stream >> y; stream >> z;

      if ( !stream.fail() ){
        _importer.addNormal( OpenMesh::Vec3f(x,y,z) );
726
727
      }else{
        emit log( LOGERR, tr("Could not read normal. Possible NaN or Inf?"));
Dirk Wilden's avatar
Dirk Wilden committed
728
729
      }
    }
730

Dirk Wilden's avatar
Dirk Wilden committed
731
732
733
734
735
736
737
738
739
740
741
742
743
    // degree (for curves)
    else if (mode == NONE && keyWrd == "deg")
    {
      stream >> deg;

      if ( !stream.fail() )
        _importer.setDegreeU( deg );

      stream >> deg;

      if ( !stream.fail() )
        _importer.setDegreeV( deg );
    }
Dirk Wilden's avatar
Dirk Wilden committed
744
745

    // group
Dirk Wilden's avatar
Dirk Wilden committed
746
    else if (mode == NONE && keyWrd == "g"){
747
748
749
      if (!firstFace)
        firstFace = true;

Dirk Wilden's avatar
Dirk Wilden committed
750
      std::string groupName;
751
      std::getline(stream, groupName);
Dirk Wilden's avatar
Dirk Wilden committed
752

753
      if(faceCount == 0) {
Dirk Wilden's avatar
Dirk Wilden committed
754
        currentFileName = QString(groupName.c_str());
Mike Kremer's avatar
Mike Kremer committed
755
      }
Dirk Wilden's avatar
Dirk Wilden committed
756

757
758
759
760
761
762
      int id = _importer.groupId(groupName.c_str());
      if(id == -1) {
          std::cerr << "Error: Group has not been added before!" << std::endl;
          return;
      }
      _importer.setCurrentGroup(id);
763
      inGroup = true;
Dirk Wilden's avatar
Dirk Wilden committed
764
765
766
767
768

      faceCount = 0;
    }

    // face
Dirk Wilden's avatar
Dirk Wilden committed
769
    else if (mode == NONE && keyWrd == "f")
Dirk Wilden's avatar
Dirk Wilden committed
770
    {
771
772
773
774
775
776
777
      if (firstFace) {
        // store faces in the default Group if we aren't in a group already
        if (!inGroup)
          _importer.setCurrentGroup(0);

        firstFace = false;
      }
Dirk Wilden's avatar
Dirk Wilden committed
778
779
780
781
782
783

      int component(0), nV(0);
      int value;

      vhandles.clear();
      face_texcoords.clear();
784

Dirk Wilden's avatar
Dirk Wilden committed
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
      // read full line after detecting a face
      std::string faceLine;
      std::getline(stream,faceLine);
      std::stringstream lineData( faceLine );

      // work on the line until nothing left to read
      while ( !lineData.eof() )
      {
        // read one block from the line ( vertex/texCoord/normal )
        std::string vertex;
        lineData >> vertex;

        do{

          //get the component (vertex/texCoord/normal)
          size_t found=vertex.find("/");

          // parts are seperated by '/' So if no '/' found its the last component
          if( found != std::string::npos ){

            // read the index value
            std::stringstream tmp( vertex.substr(0,found) );

            // If we get an empty string this property is undefined in the file
            if ( vertex.substr(0,found).empty() ) {
              // Switch to next field
              vertex = vertex.substr(found+1);

              // Now we are at the next component
              ++component;

              // Skip further processing of this component
              continue;
            }

            // Read current value
            tmp >> value;

            // remove the read part from the string
            vertex = vertex.substr(found+1);

          } else {

            // last component of the vertex, read it.
            std::stringstream tmp( vertex );
            tmp >> value;

            // Clear vertex after finished reading the line
            vertex="";

            // Nothing to read here ( garbage at end of line )
            if ( tmp.fail() ) {
              continue;
            }
          }

          // store the component ( each component is referenced by the index here! )
          switch (component)
          {
            case 0: // vertex
              if ( value < 0 ) {
                // Calculation of index :
                // -1 is the last vertex in the list
                // As obj counts from 1 and not zero add +1
849
                value = currentVertexCount + value + 1;
Dirk Wilden's avatar
Dirk Wilden committed
850
851
852
853
854
855
856
857
858
859
860
              }

              // Obj counts from 1 and not zero .. array counts from zero therefore -1
              vhandles.push_back( value-1 );
              break;

            case 1: // texture coord
              if ( value < 0 ) {
                // Calculation of index :
                // -1 is the last vertex in the list
                // As obj counts from 1 and not zero add +1
861
                value = currentTextureCoordCount + value + 1;
Dirk Wilden's avatar
Dirk Wilden committed
862
              }
863
864
865
866
867
868
869
870
871
872
873
874
875

              if (vhandles.empty())
              {
                emit log (LOGWARN, tr("Texture coordinates defined, but no vertex coordinates found!"));
                break;
              }
              if ((unsigned int)(value-1) >= _importer.n_texCoords())
              {
                emit log (LOGWARN, tr("Too many texcoords defined, skipping the rest"));
                break;
              }

              if ( _importer.n_texCoords() > 0 ) {
Dirk Wilden's avatar
Dirk Wilden committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
                // Obj counts from 1 and not zero .. array counts from zero therefore -1
                _importer.setVertexTexCoord( vhandles.back(), value-1 );
                face_texcoords.push_back( value-1 );
              } else {
                emit log( LOGERR, tr("Error setting Texture coordinates") );
              }

              break;

            case 2: // normal
              if ( value < 0 ) {
                // Calculation of index :
                // -1 is the last vertex in the list
                // As obj counts from 1 and not zero add +1
890
                value = currentNormalCount + value + 1;
Dirk Wilden's avatar
Dirk Wilden committed
891
              }
892
893
894
895
896
897
898
899
900
901
902
903
904

              if (vhandles.empty())
              {
                emit log (LOGWARN, tr("Texture coordinates defined, but no vertex coordinates found!"));
                break;
              }

              if ((unsigned int)(value-1) >= _importer.n_normals())
              {
                emit log (LOGWARN, tr("Too many normals defined, skipping the rest"));
                break;
              }

Dirk Wilden's avatar
Dirk Wilden committed
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
              // Obj counts from 1 and not zero .. array counts from zero therefore -1
              _importer.setNormal(vhandles.back(), value-1);
              break;
          }

          // Prepare for reading next component
          ++component;

          // Read until line does not contain any other info
        } while ( !vertex.empty() );

        component = 0;
        nV++;
      }


      if( !vhandles.empty() ){
922

923
        if ( !face_texcoords.empty() )
Dirk Wilden's avatar
Dirk Wilden committed
924
925
926
927
          //if we have texCoords add face+texCoords
          _importer.addFace(vhandles, face_texcoords );
        else
          //otherwise just add the face
928
          _importer.addFace(vhandles);
Dirk Wilden's avatar
Dirk Wilden committed
929
930
931
932
933
934
935
936
937

        faceCount++;
      }


      //add material to the last added face(s)
      //if polygons get triangulated this can be more than one face
      _importer.addMaterial( matname );
    }
938

Dirk Wilden's avatar
Dirk Wilden committed
939
940
941
942
943
944
945
#ifdef ENABLE_BSPLINECURVE_SUPPORT
    // param
    else if ( (mode == CURVE && keyWrd == "parm") || (mode == CURVE && keyWrd == "parm_add") ){

      //get curve knots
      std::string paramLine;
      std::string tmp;
946

Dirk Wilden's avatar
Dirk Wilden committed
947
      std::getline(stream, paramLine);
948

Dirk Wilden's avatar
Dirk Wilden committed
949
950
951
952
953
      // value may contain a / as line separator
      if ( QString( paramLine.c_str() ).endsWith("\\")){
        paramLine = paramLine.substr(0, paramLine.length()-1);
        nextKeyWrd = "parm_add";
      }
954

Dirk Wilden's avatar
Dirk Wilden committed
955
956
957
958
959
960
961
962
      std::stringstream lineData( paramLine );

      if ( keyWrd != "parm_add")
        lineData >> tmp; //push the first u out

      // work on the line until nothing left to read
      while ( !lineData.eof() && !lineData.fail() )
      {
963

Jan Möbius's avatar
Jan Möbius committed
964
965
        double knot;

Dirk Wilden's avatar
Dirk Wilden committed
966
967
968
969
970
971
972
973
974
        lineData >> knot;

        if ( !lineData.fail() )
          knotsU.push_back( knot );
      }
    }

    // curve
    else if ( (mode == NONE && keyWrd == "curv") || (mode == CURVE && keyWrd == "curv_add") ){
975
976
977
978
      if (!firstFace)
        firstFace = true;

      inGroup = false;
Dirk Wilden's avatar
Dirk Wilden committed
979
980

      mode = CURVE;
981

982
983
      if ( keyWrd == "curv" ) {

984
985
          //int id = _importer.groupId(QString("spline_curve_%1").arg(curveCount));
          int id = _importer.getCurveGroupId(curveCount);
986
987
988
989
990
991
992
          if(id == -1) {
              std::cerr << "Error: Group has not been added before!" << std::endl;
              return;
          }
          _importer.setCurrentGroup(id);
          curveCount++;
      }
993

Dirk Wilden's avatar
Dirk Wilden committed
994
995
      //get curve control points
      std::string curveLine;
996

Dirk Wilden's avatar
Dirk Wilden committed
997
      std::getline(stream, curveLine);
998

Dirk Wilden's avatar
Dirk Wilden committed
999
1000
      // value may contain a / as line separator
      if ( QString( curveLine.c_str() ).endsWith("\\")){