STLReader.cc 12.7 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
/* ========================================================================= *
Jan Möbius's avatar
Jan Möbius committed
2
3
 *                                                                           *
 *                               OpenMesh                                    *
Jan Möbius's avatar
Jan Möbius committed
4
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
Jan Möbius's avatar
Typo    
Jan Möbius committed
5
 *           Department of Computer Graphics and Multimedia                  *
Jan Möbius's avatar
Jan Möbius committed
6
7
 *                          All rights reserved.                             *
 *                            www.openmesh.org                               *
Jan Möbius's avatar
Jan Möbius committed
8
 *                                                                           *
9
 *---------------------------------------------------------------------------*
Jan Möbius's avatar
Jan Möbius committed
10
11
 * This file is part of OpenMesh.                                            *
 *---------------------------------------------------------------------------*
12
 *                                                                           *
Jan Möbius's avatar
Jan Möbius committed
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
 * 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.              *
Jan Möbius's avatar
Jan Möbius committed
39
40
 *                                                                           *
 * ========================================================================= */
41
42

/*===========================================================================*\
43
 *                                                                           *
44
45
 *   $Revision$                                                         *
 *   $Date$                   *
Jan Möbius's avatar
Jan Möbius committed
46
47
48
49
50
51
52
53
54
55
56
 *                                                                           *
\*===========================================================================*/


//== INCLUDES =================================================================


// STL
#include <map>

#include <float.h>
57
#include <fstream>
Jan Möbius's avatar
Jan Möbius committed
58
59
60
61
62
63

// OpenMesh
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/reader/STLReader.hh>
#include <OpenMesh/Core/IO/IOManager.hh>

64
65
66
67
68
69
70
//comppare strings crossplatform ignorign case
#ifdef _WIN32
  #define strnicmp _strnicmp
#else
  #define strnicmp strncasecmp
#endif

Jan Möbius's avatar
Jan Möbius committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

//=== NAMESPACES ==============================================================


namespace OpenMesh {
namespace IO {


//=== INSTANCIATE =============================================================


// register the STLReader singleton with MeshReader
_STLReader_  __STLReaderInstance;
_STLReader_&  STLReader() { return __STLReaderInstance; }


//=== IMPLEMENTATION ==========================================================


_STLReader_::
91
_STLReader_()
Jan Möbius's avatar
Jan Möbius committed
92
93
  : eps_(FLT_MIN)
{
94
  IOManager().register_module(this);
Jan Möbius's avatar
Jan Möbius committed
95
96
97
98
99
100
}


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


101
bool
Jan Möbius's avatar
Jan Möbius committed
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
_STLReader_::
read(const std::string& _filename, BaseImporter& _bi, Options& _opt)
{
  bool result = false;

  STL_Type file_type = NONE;

  if ( check_extension( _filename, "stla" ) )
  {
    file_type = STLA;
  }

  else if ( check_extension( _filename, "stlb" ) )
  {
    file_type = STLB;
  }

  else if ( check_extension( _filename, "stl" ) )
  {
    file_type = check_stl_type(_filename);
  }


  switch (file_type)
  {
    case STLA:
    {
129
      result = read_stla(_filename, _bi, _opt);
Jan Möbius's avatar
Jan Möbius committed
130
131
132
      _opt -= Options::Binary;
      break;
    }
133

Jan Möbius's avatar
Jan Möbius committed
134
135
    case STLB:
    {
136
      result = read_stlb(_filename, _bi, _opt);
Jan Möbius's avatar
Jan Möbius committed
137
138
139
      _opt += Options::Binary;
      break;
    }
140
141

    default:
Jan Möbius's avatar
Jan Möbius committed
142
143
144
145
146
147
148
149
150
151
    {
      result = false;
      break;
    }
  }


  return result;
}

152
153
154
155
156
157
bool
_STLReader_::read(std::istream& _is,
		 BaseImporter& _bi,
		 Options& _opt)
{

158
159
160
  bool result = false;

  if (_opt & Options::Binary)
161
    result = read_stlb(_is, _bi, _opt);
162
  else
163
    result = read_stla(_is, _bi, _opt);
164

165
  return result;
166
167
}

Jan Möbius's avatar
Jan Möbius committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181

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


#ifndef DOXY_IGNORE_THIS

class CmpVec
{
public:

  CmpVec(float _eps=FLT_MIN) : eps_(_eps) {}

  bool operator()( const Vec3f& _v0, const Vec3f& _v1 ) const
  {
182
    if (fabs(_v0[0] - _v1[0]) <= eps_)
Jan Möbius's avatar
Jan Möbius committed
183
    {
184
      if (fabs(_v0[1] - _v1[1]) <= eps_)
Jan Möbius's avatar
Jan Möbius committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
      {
	return (_v0[2] < _v1[2] - eps_);
      }
      else return (_v0[1] < _v1[1] - eps_);
    }
    else return (_v0[0] < _v1[0] - eps_);
  }

private:
  float eps_;
};

#endif


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

202
203
204
205
206
207
208
209
210
211
212
213
214
void trimStdString( 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 );
}

//-----------------------------------------------------------------------------
Jan Möbius's avatar
Jan Möbius committed
215

216
bool
Jan Möbius's avatar
Jan Möbius committed
217
_STLReader_::
218
read_stla(const std::string& _filename, BaseImporter& _bi, Options& _opt) const
Jan Möbius's avatar
Jan Möbius committed
219
{
220
221
  std::fstream in( _filename.c_str(), std::ios_base::in );

Jan Möbius's avatar
Jan Möbius committed
222
223
  if (!in)
  {
224
    omerr() << "[STLReader] : cannot not open file "
Jan Möbius's avatar
Jan Möbius committed
225
226
227
228
229
	  << _filename
	  << std::endl;
    return false;
  }

230
  bool res = read_stla(in, _bi, _opt);
Jan Möbius's avatar
Jan Möbius committed
231

232
  if (in)
233
    in.close();
Jan Möbius's avatar
Jan Möbius committed
234

235
  return res;
Jan Möbius's avatar
Jan Möbius committed
236
237
238
239
}

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

240
241
bool
_STLReader_::
242
read_stla(std::istream& _in, BaseImporter& _bi, Options& _opt) const
243
244
245
246
247
248
249
250
251
252
253
254
255
{

  unsigned int               i;
  OpenMesh::Vec3f            v;
  OpenMesh::Vec3f            n;
  BaseImporter::VHandles     vhandles;

  CmpVec comp(eps_);
  std::map<Vec3f, VertexHandle, CmpVec>            vMap(comp);
  std::map<Vec3f, VertexHandle, CmpVec>::iterator  vMapIt;

  std::string line;

Martin Schultz's avatar
Martin Schultz committed
256
257
  std::string        garbage;
  std::stringstream  strstream;
258

259
  bool facet_normal(false);
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274

  while( _in && !_in.eof() ) {

    // Get one line
    std::getline(_in, line);
    if ( _in.bad() ){
      omerr() << "  Warning! Could not read stream properly!\n";
      return false;
    }

    // Trim Both leading and trailing spaces
    trimStdString(line);

    // Normal found?
    if (line.find("facet normal") != std::string::npos) {
275
276
      strstream.str(line);
      strstream.clear();
277
278
279
280
281
282
283
284
285
286
287

      // facet
      strstream >> garbage;

      // normal
      strstream >> garbage;

      strstream >> n[0];
      strstream >> n[1];
      strstream >> n[2];

288
      facet_normal = true;
289
290
291
292
293
294
295
296
297
298
299
300
    }

    // Detected a triangle
    if ( (line.find("outer") != std::string::npos) ||  (line.find("OUTER") != std::string::npos ) ) {

      vhandles.clear();

      for (i=0; i<3; ++i) {
        // Get one vertex
        std::getline(_in, line);
        trimStdString(line);

301
302
        strstream.str(line);
        strstream.clear();
303
304
305
306
307
308
309
310
311
312
313

        strstream >> garbage;

        strstream >> v[0];
        strstream >> v[1];
        strstream >> v[2];

        // has vector been referenced before?
        if ((vMapIt=vMap.find(v)) == vMap.end())
        {
          // No : add vertex and remember idx/vector mapping
314
315
316
          VertexHandle handle = _bi.add_vertex(v);
          vhandles.push_back(handle);
          vMap[v] = handle;
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
        }
        else
          // Yes : get index from map
          vhandles.push_back(vMapIt->second);

      }

      // Add face only if it is not degenerated
      if ((vhandles[0] != vhandles[1]) &&
          (vhandles[0] != vhandles[2]) &&
          (vhandles[1] != vhandles[2])) {


        FaceHandle fh = _bi.add_face(vhandles);

332
333
334
        // set the normal if requested
        // if a normal was requested but could not be found we unset the option
        if (facet_normal) {
335
          if (fh.is_valid() && _opt.face_has_normal())
336
337
338
            _bi.set_normal(fh, n);
        } else
          _opt -= Options::FaceNormal;
339
340
      }

341
      facet_normal = false;
342
343
344
345
346
347
348
    }
  }

  return true;
}

//-----------------------------------------------------------------------------
Jan Möbius's avatar
Jan Möbius committed
349

350
bool
Jan Möbius's avatar
Jan Möbius committed
351
_STLReader_::
352
read_stlb(const std::string& _filename, BaseImporter& _bi, Options& _opt) const
Jan Möbius's avatar
Jan Möbius committed
353
{
354
355
  std::fstream in( _filename.c_str(), std::ios_base::in | std::ios_base::binary);

Jan Möbius's avatar
Jan Möbius committed
356
357
  if (!in)
  {
358
    omerr() << "[STLReader] : cannot not open file "
Jan Möbius's avatar
Jan Möbius committed
359
360
361
362
363
	  << _filename
	  << std::endl;
    return false;
  }

364
  bool res = read_stlb(in, _bi, _opt);
Jan Möbius's avatar
Jan Möbius committed
365

366
367
  if (in)
    in.close();
368

369
  return res;
Jan Möbius's avatar
Jan Möbius committed
370
371
372
373
}

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

374
375
bool
_STLReader_::
376
read_stlb(std::istream& _in, BaseImporter& _bi, Options& _opt) const
377
378
379
380
{
  char                       dummy[100];
  bool                       swapFlag;
  unsigned int               i, nT;
381
  OpenMesh::Vec3f            v, n;
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
  BaseImporter::VHandles     vhandles;

  std::map<Vec3f, VertexHandle, CmpVec>  vMap;
  std::map<Vec3f, VertexHandle, CmpVec>::iterator vMapIt;


  // check size of types
  if ((sizeof(float) != 4) || (sizeof(int) != 4)) {
    omerr() << "[STLReader] : wrong type size\n";
    return false;
  }

  // determine endian mode
  union { unsigned int i; unsigned char c[4]; } endian_test;
  endian_test.i = 1;
  swapFlag = (endian_test.c[3] == 1);

  // read number of triangles
  _in.read(dummy, 80);
  nT = read_int(_in, swapFlag);

  // read triangles
  while (nT)
  {
    vhandles.clear();

408
409
410
411
    // read triangle normal
    n[0] = read_float(_in, swapFlag);
    n[1] = read_float(_in, swapFlag);
    n[2] = read_float(_in, swapFlag);
412
413
414
415
416
417
418
419
420
421
422

    // triangle's vertices
    for (i=0; i<3; ++i)
    {
      v[0] = read_float(_in, swapFlag);
      v[1] = read_float(_in, swapFlag);
      v[2] = read_float(_in, swapFlag);

      // has vector been referenced before?
      if ((vMapIt=vMap.find(v)) == vMap.end())
      {
423
424
425
426
        // No : add vertex and remember idx/vector mapping
        VertexHandle handle = _bi.add_vertex(v);
        vhandles.push_back(handle);
        vMap[v] = handle;
427
428
      }
      else
429
430
        // Yes : get index from map
        vhandles.push_back(vMapIt->second);
431
432
433
434
435
436
    }


    // Add face only if it is not degenerated
    if ((vhandles[0] != vhandles[1]) &&
	(vhandles[0] != vhandles[2]) &&
437
438
439
	(vhandles[1] != vhandles[2])) {
      FaceHandle fh = _bi.add_face(vhandles);

440
      if (fh.is_valid() && _opt.face_has_normal())
441
442
        _bi.set_normal(fh, n);
    }
443
444
445
446
447
448
449
450
451

    _in.read(dummy, 2);
    --nT;
  }

  return true;
}

//-----------------------------------------------------------------------------
Jan Möbius's avatar
Jan Möbius committed
452
453
454
455
456
457
458

_STLReader_::STL_Type
_STLReader_::
check_stl_type(const std::string& _filename) const
{

  // open file
459
460
461
462
463
464
  std::ifstream ifs (_filename.c_str(), std::ifstream::binary);
  if(!ifs.good())
  {
    omerr() << "could not open file" << _filename << std::endl;
    return NONE;
  }
Jan Möbius's avatar
Jan Möbius committed
465

466
467
468
469
470
471
472
473
  //find first non whitespace character
  std::string line = "";
  std::size_t firstChar;
  while(line.empty() && ifs.good())
  {
    std::getline(ifs,line);
    firstChar = line.find_first_not_of("\t ");
  }
Jan Möbius's avatar
Jan Möbius committed
474

475
476
477
478
479
  //check for ascii keyword solid
  if(strnicmp("solid",&line[firstChar],5) == 0)
  {
    return STLA;
  }
Jan Möbius's avatar
Jan Möbius committed
480

481
482
  //if the file does not start with solid it is STLB
  return STLB;
Jan Möbius's avatar
Jan Möbius committed
483
484
485
486
487
488
489
}


//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================