OMWriter.cc 15.6 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1 2 3
/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
Jan Möbius's avatar
Jan Möbius committed
4
 *      Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen      *
Jan Möbius's avatar
Jan Möbius committed
5 6
 *                           www.openmesh.org                                *
 *                                                                           *
7
 *---------------------------------------------------------------------------*
8
 *  This file is part of OpenMesh.                                           *
Jan Möbius's avatar
Jan Möbius committed
9
 *                                                                           *
10
 *  OpenMesh is free software: you can redistribute it and/or modify         *
11 12 13 14
 *  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:                                                    *
Jan Möbius's avatar
Jan Möbius committed
15
 *                                                                           *
16 17 18 19 20 21 22
 *  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.                        *
Jan Möbius's avatar
Jan Möbius committed
23
 *                                                                           *
24 25 26 27
 *  OpenMesh 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.                      *
Jan Möbius's avatar
Jan Möbius committed
28
 *                                                                           *
29 30 31 32
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
33
\*===========================================================================*/
34 35

/*===========================================================================*\
36
 *                                                                           *
37 38
 *   $Revision$                                                         *
 *   $Date$                   *
Jan Möbius's avatar
Jan Möbius committed
39 40 41 42 43 44 45 46 47
 *                                                                           *
\*===========================================================================*/


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

#include <OpenMesh/Core/System/config.h>
// -------------------- STL
#if defined( OM_CC_MIPS )
Jan Möbius's avatar
Jan Möbius committed
48 49
  #include <time.h>
  #include <string.h>
Jan Möbius's avatar
Jan Möbius committed
50
#else
Jan Möbius's avatar
Jan Möbius committed
51 52
  #include <ctime>
  #include <cstring>
Jan Möbius's avatar
Jan Möbius committed
53
#endif
Jan Möbius's avatar
Jan Möbius committed
54

Jan Möbius's avatar
Jan Möbius committed
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
#include <fstream>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/OMFormat.hh>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/Utils/Endian.hh>
#include <OpenMesh/Core/IO/exporter/BaseExporter.hh>
#include <OpenMesh/Core/IO/writer/OMWriter.hh>

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


namespace OpenMesh {
namespace IO {


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


// register the OMLoader singleton with MeshLoader
_OMWriter_  __OMWriterInstance;
_OMWriter_& OMWriter() { return __OMWriterInstance; }


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


const OMFormat::uchar _OMWriter_::magic_[3] = "OM";
const OMFormat::uint8 _OMWriter_::version_  = OMFormat::mk_version(1,2);


_OMWriter_::
86 87 88
_OMWriter_()
{
  IOManager().register_module(this);
Jan Möbius's avatar
Jan Möbius committed
89 90 91 92 93
}


bool
_OMWriter_::write(const std::string& _filename, BaseExporter& _be,
94
                   Options _opt, std::streamsize /*_precision*/) const
Jan Möbius's avatar
Jan Möbius committed
95 96 97 98 99
{
  // check whether exporter can give us an OpenMesh BaseKernel
  if (!_be.kernel()) return false;


100 101
  // check for om extension in filename, we can only handle OM
  if (_filename.rfind(".om") == std::string::npos)
Jan Möbius's avatar
Jan Möbius committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    return false;

  _opt += Options::Binary; // only binary format supported

  std::ofstream ofs(_filename.c_str(), std::ios::binary);

  // check if file is open
  if (!ofs.is_open())
  {
    omerr() << "[OMWriter] : cannot open file " << _filename << std::endl;
    return false;
  }

  // call stream save method
  bool rc = write(ofs, _be, _opt);
117

Jan Möbius's avatar
Jan Möbius committed
118 119 120 121 122 123 124 125 126 127 128
  // close filestream
  ofs.close();

  // return success/failure notice
  return rc;
}


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

bool
129
_OMWriter_::write(std::ostream& _os, BaseExporter& _be, Options _opt, std::streamsize /*_precision*/) const
Jan Möbius's avatar
Jan Möbius committed
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
{
//   std::clog << "[OMWriter]::write( stream )\n";

  // check exporter features
  if ( !check( _be, _opt ) )
  {
    omerr() << "[OMWriter]: exporter does not support wanted feature!\n";
    return false;
  }

  // Maybe an ascii version will be implemented in the future.
  // For now, support only a binary format
  if ( !_opt.check( Options::Binary ) )
    _opt += Options::Binary;

  // Ignore LSB/MSB bit. Always store in LSB (little endian)
  _opt += Options::LSB;
  _opt -= Options::MSB;

  return write_binary(_os, _be, _opt);
}


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


#ifndef DOXY_IGNORE_THIS
template <typename T> struct Enabler
{
  Enabler( T& obj ) : obj_(obj)
  {}

  ~Enabler() { obj_.enable(); }

  T& obj_;
};
#endif


bool _OMWriter_::write_binary(std::ostream& _os, BaseExporter& _be,
                               Options _opt) const
{
Jan Möbius's avatar
Jan Möbius committed
172 173 174
  #ifndef DOXY_IGNORE_THIS
    Enabler<mostream> enabler(omlog());
  #endif
Jan Möbius's avatar
Jan Möbius committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

  omlog() << "[OMWriter] : write binary file\n";

  size_t bytes = 0;

  bool swap = _opt.check(Options::Swap) || (Endian::local() == Endian::MSB);

  unsigned int i, nV, nF;
  Vec3f v;
  Vec2f t;
  std::vector<VertexHandle> vhandles;


  // -------------------- write header
  OMFormat::Header header;
190

Jan Möbius's avatar
Jan Möbius committed
191 192 193 194 195 196 197
  header.magic_[0]   = 'O';
  header.magic_[1]   = 'M';
  header.mesh_       = _be.is_triangle_mesh() ? 'T' : 'P';
  header.version_    = version_;
  header.n_vertices_ = _be.n_vertices();
  header.n_faces_    = _be.n_faces();
  header.n_edges_    = _be.n_edges();
198

Jan Möbius's avatar
Jan Möbius committed
199
  bytes += store( _os, header, swap );
200

Jan Möbius's avatar
Jan Möbius committed
201
  // ---------------------------------------- write chunks
202

Jan Möbius's avatar
Jan Möbius committed
203
  OMFormat::Chunk::Header chunk_header;
204 205


Jan Möbius's avatar
Jan Möbius committed
206
  // -------------------- write vertex data
207

Jan Möbius's avatar
Jan Möbius committed
208 209 210 211 212 213 214 215 216 217 218 219
  // ---------- write vertex position
  if (_be.n_vertices())
  {
    v = _be.point(VertexHandle(0));
    chunk_header.reserved_ = 0;
    chunk_header.name_     = false;
    chunk_header.entity_   = OMFormat::Chunk::Entity_Vertex;
    chunk_header.type_     = OMFormat::Chunk::Type_Pos;
    chunk_header.signed_   = OMFormat::is_signed(v[0]);
    chunk_header.float_    = OMFormat::is_float(v[0]);
    chunk_header.dim_      = OMFormat::dim(v);
    chunk_header.bits_     = OMFormat::bits(v[0]);
220

Jan Möbius's avatar
Jan Möbius committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    bytes += store( _os, chunk_header, swap );
    for (i=0, nV=_be.n_vertices(); i<nV; ++i)
      bytes += vector_store( _os, _be.point(VertexHandle(i)), swap );
  }


  // ---------- write vertex normal
  if (_be.n_vertices() && _opt.check( Options::VertexNormal ))
  {
    Vec3f n = _be.normal(VertexHandle(0));

    chunk_header.name_     = false;
    chunk_header.entity_   = OMFormat::Chunk::Entity_Vertex;
    chunk_header.type_     = OMFormat::Chunk::Type_Normal;
    chunk_header.signed_   = OMFormat::is_signed(n[0]);
    chunk_header.float_    = OMFormat::is_float(n[0]);
    chunk_header.dim_      = OMFormat::dim(n);
    chunk_header.bits_     = OMFormat::bits(n[0]);
239

Jan Möbius's avatar
Jan Möbius committed
240 241 242 243 244 245 246
    bytes += store( _os, chunk_header, swap );
    for (i=0, nV=_be.n_vertices(); i<nV; ++i)
      bytes += vector_store( _os, _be.normal(VertexHandle(i)), swap );
  }

  // ---------- write vertex color
  if (_opt.check( Options::VertexColor ) && _be.has_vertex_colors() )
247
  {
Jan Möbius's avatar
Jan Möbius committed
248
    Vec3uc c = _be.color(VertexHandle(0));
249

Jan Möbius's avatar
Jan Möbius committed
250 251 252 253 254 255
    chunk_header.name_     = false;
    chunk_header.entity_   = OMFormat::Chunk::Entity_Vertex;
    chunk_header.type_     = OMFormat::Chunk::Type_Color;
    chunk_header.signed_   = OMFormat::is_signed( c );
    chunk_header.float_    = OMFormat::is_float( c );
    chunk_header.dim_      = OMFormat::dim( c );
256
    chunk_header.bits_     = OMFormat::bits( c );
Jan Möbius's avatar
Jan Möbius committed
257 258 259 260 261 262 263

    bytes += store( _os, chunk_header, swap );
    for (i=0, nV=_be.n_vertices(); i<nV; ++i)
      bytes += vector_store( _os, _be.color(VertexHandle(i)), swap );
  }

  // ---------- write vertex texture coords
Jan Möbius's avatar
Jan Möbius committed
264 265
  if (_be.n_vertices() && _opt.check(Options::VertexTexCoord)) {

Jan Möbius's avatar
Jan Möbius committed
266 267
    t = _be.texcoord(VertexHandle(0));

Jan Möbius's avatar
Jan Möbius committed
268 269 270 271 272 273 274
    chunk_header.name_ = false;
    chunk_header.entity_ = OMFormat::Chunk::Entity_Vertex;
    chunk_header.type_ = OMFormat::Chunk::Type_Texcoord;
    chunk_header.signed_ = OMFormat::is_signed(t[0]);
    chunk_header.float_ = OMFormat::is_float(t[0]);
    chunk_header.dim_ = OMFormat::dim(t);
    chunk_header.bits_ = OMFormat::bits(t[0]);
275

Jan Möbius's avatar
Jan Möbius committed
276
    // std::clog << chunk_header << std::endl;
Jan Möbius's avatar
Jan Möbius committed
277 278 279 280
    bytes += store(_os, chunk_header, swap);

    for (i = 0, nV = _be.n_vertices(); i < nV; ++i)
      bytes += vector_store(_os, _be.texcoord(VertexHandle(i)), swap);
Jan Möbius's avatar
Jan Möbius committed
281 282 283 284 285 286 287 288 289 290 291 292 293

  }

  // -------------------- write face data

  // ---------- write topology
  {
    chunk_header.name_     = false;
    chunk_header.entity_   = OMFormat::Chunk::Entity_Face;
    chunk_header.type_     = OMFormat::Chunk::Type_Topology;
    chunk_header.signed_   = 0;
    chunk_header.float_    = 0;
    chunk_header.dim_      = OMFormat::Chunk::Dim_1D; // ignored
294
    chunk_header.bits_     = OMFormat::needed_bits(_be.n_vertices());
Jan Möbius's avatar
Jan Möbius committed
295 296 297 298 299 300

    bytes += store( _os, chunk_header, swap );

    for (i=0, nF=_be.n_faces(); i<nF; ++i)
    {
      if ( header.mesh_ == 'P' )
Jan Möbius's avatar
Jan Möbius committed
301
         bytes += store( _os, vhandles.size(),
Jan Möbius's avatar
Jan Möbius committed
302
			OMFormat::Chunk::Integer_16, swap );
303

Jan Möbius's avatar
Jan Möbius committed
304 305
      for (size_t j=0; j < vhandles.size(); ++j)
      {
Jan Möbius's avatar
Jan Möbius committed
306 307
         using namespace OMFormat;
         using namespace GenProg;
308

Jan Möbius's avatar
Jan Möbius committed
309
	    bytes += store( _os, vhandles[j].idx(),
Jan Möbius's avatar
Jan Möbius committed
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
			Chunk::Integer_Size(chunk_header.bits_), swap );
      }
    }
  }

  // ---------- write face normals

  if ( _be.has_face_normals() && _opt.check(Options::FaceNormal) )
  {
#define NEW_STYLE 0
#if NEW_STYLE
    const BaseProperty *bp = _be.kernel()._get_fprop("f:normals");

    if (bp)
    {
#endif
      Vec3f n = _be.normal(FaceHandle(0));

      chunk_header.name_     = false;
      chunk_header.entity_   = OMFormat::Chunk::Entity_Face;
      chunk_header.type_     = OMFormat::Chunk::Type_Normal;
      chunk_header.signed_   = OMFormat::is_signed(n[0]);
      chunk_header.float_    = OMFormat::is_float(n[0]);
      chunk_header.dim_      = OMFormat::dim(n);
      chunk_header.bits_     = OMFormat::bits(n[0]);
335

Jan Möbius's avatar
Jan Möbius committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
      bytes += store( _os, chunk_header, swap );
#if !NEW_STYLE
      for (i=0, nF=_be.n_faces(); i<nF; ++i)
        bytes += vector_store( _os, _be.normal(FaceHandle(i)), swap );
#else
      bytes += bp->store(_os, swap );
    }
    else
      return false;
#endif
#undef NEW_STYLE
  }


  // ---------- write face color

  if (_be.has_face_colors() && _opt.check( Options::FaceColor ))
353
  {
Jan Möbius's avatar
Jan Möbius committed
354 355 356
#define NEW_STYLE 0
#if NEW_STYLE
    const BaseProperty *bp = _be.kernel()._get_fprop("f:colors");
357

Jan Möbius's avatar
Jan Möbius committed
358 359 360 361
    if (bp)
    {
#endif
      Vec3uc c;
362

Jan Möbius's avatar
Jan Möbius committed
363 364 365 366 367 368 369
      chunk_header.name_     = false;
      chunk_header.entity_   = OMFormat::Chunk::Entity_Face;
      chunk_header.type_     = OMFormat::Chunk::Type_Color;
      chunk_header.signed_   = OMFormat::is_signed( c[0] );
      chunk_header.float_    = OMFormat::is_float( c[0] );
      chunk_header.dim_      = OMFormat::dim( c );
      chunk_header.bits_     = OMFormat::bits( c[0] );
370

Jan Möbius's avatar
Jan Möbius committed
371 372 373
      bytes += store( _os, chunk_header, swap );
#if !NEW_STYLE
      for (i=0, nF=_be.n_faces(); i<nF; ++i)
374
        bytes += vector_store( _os, _be.color(FaceHandle(i)), swap );
Jan Möbius's avatar
Jan Möbius committed
375 376 377 378 379 380 381 382 383 384
#else
      bytes += bp->store(_os, swap);
    }
    else
      return false;
#endif
  }

  // -------------------- write custom properties

385

Jan Möbius's avatar
Jan Möbius committed
386
  BaseKernel::const_prop_iterator prop;
387

Jan Möbius's avatar
Jan Möbius committed
388 389 390 391 392
  for (prop  = _be.kernel()->vprops_begin();
       prop != _be.kernel()->vprops_end(); ++prop)
  {
    if ( !*prop ) continue;
    if ( (*prop)->name()[1]==':') continue;
393
    bytes += store_binary_custom_chunk(_os, **prop,
Jan Möbius's avatar
Jan Möbius committed
394 395 396 397 398 399 400
				       OMFormat::Chunk::Entity_Vertex, swap );
  }
  for (prop  = _be.kernel()->fprops_begin();
       prop != _be.kernel()->fprops_end(); ++prop)
  {
    if ( !*prop ) continue;
    if ( (*prop)->name()[1]==':') continue;
401
    bytes += store_binary_custom_chunk(_os, **prop,
Jan Möbius's avatar
Jan Möbius committed
402 403 404 405 406 407 408
				       OMFormat::Chunk::Entity_Face, swap );
  }
  for (prop  = _be.kernel()->eprops_begin();
       prop != _be.kernel()->eprops_end(); ++prop)
  {
    if ( !*prop ) continue;
    if ( (*prop)->name()[1]==':') continue;
409
    bytes += store_binary_custom_chunk(_os, **prop,
Jan Möbius's avatar
Jan Möbius committed
410 411 412 413 414 415 416
				       OMFormat::Chunk::Entity_Edge, swap );
  }
  for (prop  = _be.kernel()->hprops_begin();
       prop != _be.kernel()->hprops_end(); ++prop)
  {
    if ( !*prop ) continue;
    if ( (*prop)->name()[1]==':') continue;
417
    bytes += store_binary_custom_chunk(_os, **prop,
Jan Möbius's avatar
Jan Möbius committed
418 419 420 421 422 423 424
				       OMFormat::Chunk::Entity_Halfedge, swap );
  }
  for (prop  = _be.kernel()->mprops_begin();
       prop != _be.kernel()->mprops_end(); ++prop)
  {
    if ( !*prop ) continue;
    if ( (*prop)->name()[1]==':') continue;
425
    bytes += store_binary_custom_chunk(_os, **prop,
Jan Möbius's avatar
Jan Möbius committed
426 427 428
				       OMFormat::Chunk::Entity_Mesh, swap );
  }

429
 std::clog << "#bytes written: " << bytes << std::endl;
Jan Möbius's avatar
Jan Möbius committed
430 431 432 433 434 435

  return true;
}

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

436
size_t _OMWriter_::store_binary_custom_chunk(std::ostream& _os,
Jan Möbius's avatar
Jan Möbius committed
437 438 439 440 441 442 443
					     const BaseProperty& _bp,
					     OMFormat::Chunk::Entity _entity,
					     bool _swap) const
{
  omlog() << "Custom Property " << OMFormat::as_string(_entity) << " property ["
	<< _bp.name() << "]" << std::endl;

444
  // Don't store if
Jan Möbius's avatar
Jan Möbius committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
  // 1. it is not persistent
  // 2. it's name is empty
  if ( !_bp.persistent() || _bp.name().empty() )
  {
    omlog() << "  skipped\n";
    return 0;
  }

  size_t bytes = 0;

  OMFormat::Chunk::esize_t element_size   = _bp.element_size();
  OMFormat::Chunk::Header  chdr;

  // set header
  chdr.name_     = true;
  chdr.entity_   = _entity;
  chdr.type_     = OMFormat::Chunk::Type_Custom;
  chdr.signed_   = 0;
  chdr.float_    = 0;
  chdr.dim_      = OMFormat::Chunk::Dim_1D; // ignored
  chdr.bits_     = element_size;


  // write custom chunk

470
  // 1. chunk header
Jan Möbius's avatar
Jan Möbius committed
471 472 473 474 475 476
  bytes += store( _os, chdr, _swap );

  // 2. property name
  bytes += store( _os, OMFormat::Chunk::PropertyName(_bp.name()), _swap );

  // 3. block size
477
  bytes += store( _os, _bp.size_of(), OMFormat::Chunk::Integer_32, _swap );
Jan Möbius's avatar
Jan Möbius committed
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
  omlog() << "  n_bytes = " << _bp.size_of() << std::endl;

  // 4. data
  {
    size_t b;
    bytes += ( b=_bp.store( _os, _swap ) );
    omlog() << "  b       = " << b << std::endl;
    assert( b == _bp.size_of() );
  }
  return bytes;
}

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

size_t _OMWriter_::binary_size(BaseExporter& /* _be */, Options /* _opt */) const
{
  // std::clog << "[OMWriter]: binary_size()" << std::endl;
  size_t bytes  = sizeof( OMFormat::Header );

  // !!!TODO!!!

  return bytes;
}

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