File: vtkOBJExporter.cxx

package info (click to toggle)
paraview 5.11.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 497,236 kB
  • sloc: cpp: 3,171,290; ansic: 1,315,072; python: 134,290; xml: 103,324; sql: 65,887; sh: 5,286; javascript: 4,901; yacc: 4,383; java: 3,977; perl: 2,363; lex: 1,909; f90: 1,255; objc: 143; makefile: 119; tcl: 59; pascal: 50; fortran: 29
file content (470 lines) | stat: -rw-r--r-- 14,011 bytes parent folder | download
1
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
40
41
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
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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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
438
439
440
441
442
443
444
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
470
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOBJExporter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkOBJExporter.h"

#include "vtkActorCollection.h"
#include "vtkAssemblyNode.h"
#include "vtkAssemblyPath.h"
#include "vtkCellArray.h"
#include "vtkDataSet.h"
#include "vtkFloatArray.h"
#include "vtkGeometryFilter.h"
#include "vtkImageData.h"
#include "vtkImageFlip.h"
#include "vtkMapper.h"
#include "vtkNew.h"
#include "vtkNumberToString.h"
#include "vtkObjectFactory.h"
#include "vtkPNGWriter.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkProperty.h"
#include "vtkRenderWindow.h"
#include "vtkRendererCollection.h"
#include "vtkTexture.h"
#include "vtkTransform.h"

#include "vtksys/FStream.hxx"
#include "vtksys/SystemTools.hxx"

#include <sstream>

VTK_ABI_NAMESPACE_BEGIN
vtkStandardNewMacro(vtkOBJExporter);

vtkOBJExporter::vtkOBJExporter()
{
  this->FilePrefix = nullptr;
  this->OBJFileComment = nullptr;
  this->MTLFileComment = nullptr;
  this->FlipTexture = false;
  this->SetOBJFileComment("wavefront obj file written by the visualization toolkit");
  this->SetMTLFileComment("wavefront mtl file written by the visualization toolkit");
}

vtkOBJExporter::~vtkOBJExporter()
{
  delete[] this->OBJFileComment;
  delete[] this->MTLFileComment;
  delete[] this->FilePrefix;
}

void vtkOBJExporter::WriteData()
{
  // make sure the user specified a filename
  if (this->FilePrefix == nullptr)
  {
    vtkErrorMacro(<< "Please specify file prefix to use");
    return;
  }

  vtkRenderer* ren = this->ActiveRenderer;
  if (!ren)
  {
    ren = this->RenderWindow->GetRenderers()->GetFirstRenderer();
  }

  // make sure it has at least one actor
  if (ren->GetActors()->GetNumberOfItems() < 1)
  {
    vtkErrorMacro(<< "no actors found for writing .obj file.");
    return;
  }

  // try opening the files
  std::string objFilePath = std::string(this->FilePrefix) + ".obj";
  std::string filePrefix(this->FilePrefix);
  // get the model name which isthe last component of the FilePrefix
  std::string modelName;
  if (filePrefix.find_last_of('/') != std::string::npos)
  {
    modelName = filePrefix.substr(filePrefix.find_last_of('/') + 1);
  }
  else
  {
    modelName = filePrefix;
  }

  vtksys::ofstream fpObj(objFilePath.c_str(), ios::out);
  if (!fpObj)
  {
    vtkErrorMacro(<< "unable to open " << objFilePath);
    return;
  }
  std::string mtlFilePath = std::string(this->FilePrefix) + ".mtl";
  vtksys::ofstream fpMtl(mtlFilePath.c_str(), ios::out);
  if (!fpMtl)
  {
    fpMtl.close();
    vtkErrorMacro(<< "unable to open .mtl files ");
    return;
  }

  //
  //  Write header
  //
  vtkDebugMacro("Writing wavefront files");
  if (this->GetOBJFileComment())
  {
    fpObj << "#  " << this->GetOBJFileComment() << "\n\n";
  }

  std::string mtlFileName = vtksys::SystemTools::GetFilenameName(mtlFilePath);
  fpObj << "mtllib " << mtlFileName << "\n\n";
  if (this->GetMTLFileComment())
  {
    fpMtl << "# " << this->GetMTLFileComment() << "\n\n";
  }

  vtkActorCollection* allActors = ren->GetActors();
  vtkCollectionSimpleIterator actorsIt;
  vtkActor* anActor;
  int idStart = 1;
  for (allActors->InitTraversal(actorsIt); (anActor = allActors->GetNextActor(actorsIt));)
  {
    vtkAssemblyPath* aPath;
    for (anActor->InitPathTraversal(); (aPath = anActor->GetNextPath());)
    {
      vtkActor* aPart = vtkActor::SafeDownCast(aPath->GetLastNode()->GetViewProp());
      this->WriteAnActor(aPart, fpObj, fpMtl, modelName, idStart);
    }
  }
  // Write texture files
  for (auto t : this->TextureFileMap)
  {
    std::stringstream fullFileName;
    fullFileName << this->FilePrefix << t.first;
    auto writeTexture = vtkSmartPointer<vtkPNGWriter>::New();
    if (this->FlipTexture)
    {
      auto flip = vtkSmartPointer<vtkImageFlip>::New();
      flip->SetInputData(t.second->GetInput());
      flip->SetFilteredAxis(1);
      flip->Update();
      writeTexture->SetInputData(flip->GetOutput());
    }
    else
    {
      writeTexture->SetInputData(t.second->GetInput());
    }
    writeTexture->SetFileName(fullFileName.str().c_str());
    writeTexture->Write();
  }
  fpObj.close();
  fpMtl.close();
}

void vtkOBJExporter::WriteAnActor(
  vtkActor* anActor, std::ostream& fpObj, std::ostream& fpMtl, std::string& modelName, int& idStart)
{
  vtkDataSet* ds;
  vtkNew<vtkPolyData> pd;
  vtkPointData* pntData;
  vtkPoints* points;
  vtkDataArray* tcoords;
  int i, i1, i2, idNext;
  vtkProperty* prop;
  double* tempd;
  double* p;
  vtkCellArray* cells;
  vtkNew<vtkTransform> trans;
  vtkIdType npts = 0;
  const vtkIdType* indx = nullptr;

  // see if the actor has a mapper. it could be an assembly
  if (anActor->GetMapper() == nullptr)
  {
    return;
  }
  // write out the material properties to the mat file
  prop = anActor->GetProperty();
  if (anActor->GetVisibility() == 0)
  {
    return;
  }
  vtkNumberToString convert;
  double temp;
  fpMtl << "newmtl mtl" << idStart << "\n";
  tempd = prop->GetAmbientColor();
  temp = prop->GetAmbient();
  fpMtl << "Ka " << convert(temp * tempd[0]) << " " << convert(temp * tempd[1]) << " "
        << convert(temp * tempd[2]) << "\n";
  tempd = prop->GetDiffuseColor();
  temp = prop->GetDiffuse();
  fpMtl << "Kd " << convert(temp * tempd[0]) << " " << convert(temp * tempd[1]) << " "
        << convert(temp * tempd[2]) << "\n";
  tempd = prop->GetSpecularColor();
  temp = prop->GetSpecular();
  fpMtl << "Ks " << convert(temp * tempd[0]) << " " << convert(temp * tempd[1]) << " "
        << convert(temp * tempd[2]) << "\n";
  fpMtl << "Ns " << convert(prop->GetSpecularPower()) << "\n";
  fpMtl << "Tr " << convert(prop->GetOpacity()) << "\n";
  fpMtl << "illum 3\n";

  // Actor has the texture
  bool hasTexture = anActor->GetTexture() != nullptr;

  // Actor's property has the texture. We choose the albedo texture
  // since it seems to be similar to the texture we expect
  auto allTextures = prop->GetAllTextures();
  bool hasTextureProp = allTextures.find("albedoTex") != allTextures.end();
  if (hasTexture)
  {
    std::stringstream textureFileName;
    textureFileName << "texture" << idStart << ".png";
    fpMtl << "map_Kd " << modelName << textureFileName.str() << "\n\n";
    this->TextureFileMap[textureFileName.str()] = anActor->GetTexture();
  }
  else if (hasTextureProp)
  {
    std::stringstream textureFileName;
    textureFileName << "albedoTex"
                    << "_" << idStart << ".png";
    fpMtl << "map_Kd " << modelName << textureFileName.str() << "\n\n";
    auto albedoTexture = allTextures.find("albedoTex");
    this->TextureFileMap[textureFileName.str()] = albedoTexture->second;
    this->FlipTexture = true;
  }

  // get the mappers input and matrix
  ds = anActor->GetMapper()->GetInput();
  // see if the mapper has an input.
  if (ds == nullptr)
  {
    return;
  }
  anActor->GetMapper()->GetInputAlgorithm()->Update();
  trans->SetMatrix(anActor->vtkProp3D::GetMatrix());

  // we really want polydata
  if (ds->GetDataObjectType() != VTK_POLY_DATA)
  {
    vtkNew<vtkGeometryFilter> gf;
    gf->SetInputConnection(anActor->GetMapper()->GetInputConnection(0, 0));
    gf->Update();
    pd->DeepCopy(gf->GetOutput());
  }
  else
  {
    pd->DeepCopy(ds);
  }

  // write out the points
  points = vtkPoints::New();
  trans->TransformPoints(pd->GetPoints(), points);
  for (i = 0; i < points->GetNumberOfPoints(); i++)
  {
    p = points->GetPoint(i);
    fpObj << "v " << convert(p[0]) << " " << convert(p[1]) << " " << convert(p[2]) << "\n";
  }
  idNext = idStart + static_cast<int>(points->GetNumberOfPoints());
  points->Delete();

  // write out the point data
  pntData = pd->GetPointData();
  if (pntData->GetNormals())
  {
    vtkNew<vtkFloatArray> normals;
    normals->SetNumberOfComponents(3);
    trans->TransformNormals(pntData->GetNormals(), normals);
    for (i = 0; i < normals->GetNumberOfTuples(); i++)
    {
      p = normals->GetTuple(i);
      fpObj << "vn " << convert(p[0]) << " " << convert(p[1]) << " " << convert(p[2]) << "\n";
    }
  }

  tcoords = pntData->GetTCoords();
  if (tcoords)
  {
    for (i = 0; i < tcoords->GetNumberOfTuples(); i++)
    {
      p = tcoords->GetTuple(i);
      fpObj << "vt " << convert(p[0]) << " " << convert(p[1]) << " " << 0.0 << "\n";
    }
  }

  // write out a group name and material
  fpObj << "\ng grp" << idStart << "\n";
  fpObj << "usemtl mtl" << idStart << "\n";
  // write out verts if any
  if (pd->GetNumberOfVerts() > 0)
  {
    cells = pd->GetVerts();
    for (cells->InitTraversal(); cells->GetNextCell(npts, indx);)
    {
      fpObj << "p ";
      for (i = 0; i < npts; i++)
      {
        // treating vtkIdType as int
        fpObj << static_cast<int>(indx[i]) + idStart << " ";
      }
      fpObj << "\n";
    }
  }

  // write out lines if any
  if (pd->GetNumberOfLines() > 0)
  {
    cells = pd->GetLines();
    for (cells->InitTraversal(); cells->GetNextCell(npts, indx);)
    {
      fpObj << "l ";
      if (tcoords)
      {
        for (i = 0; i < npts; i++)
        {
          // treating vtkIdType as int
          fpObj << static_cast<int>(indx[i]) + idStart << "/"
                << static_cast<int>(indx[i]) + idStart;
        }
      }
      else
      {
        for (i = 0; i < npts; i++)
        {
          // treating vtkIdType as int
          fpObj << static_cast<int>(indx[i]) + idStart << " ";
        }
      }
      fpObj << "\n";
    }
  }
  // write out polys if any
  if (pd->GetNumberOfPolys() > 0)
  {
    cells = pd->GetPolys();
    for (cells->InitTraversal(); cells->GetNextCell(npts, indx);)
    {
      fpObj << "f ";
      for (i = 0; i < npts; i++)
      {
        if (pntData->GetNormals())
        {
          if (tcoords)
          {
            // treating vtkIdType as int
            fpObj << static_cast<int>(indx[i]) + idStart << "/"
                  << static_cast<int>(indx[i]) + idStart << "/"
                  << static_cast<int>(indx[i]) + idStart << " ";
          }
          else
          {
            // treating vtkIdType as int
            fpObj << static_cast<int>(indx[i]) + idStart << "//"
                  << static_cast<int>(indx[i]) + idStart << " ";
          }
        }
        else
        {
          if (tcoords)
          {
            // treating vtkIdType as int
            fpObj << static_cast<int>(indx[i]) + idStart << "/"
                  << static_cast<int>(indx[i]) + idStart << " ";
          }
          else
          {
            // treating vtkIdType as int
            fpObj << static_cast<int>(indx[i]) + idStart << " ";
          }
        }
      }
      fpObj << "\n";
    }
  }

  // write out tstrips if any
  if (pd->GetNumberOfStrips() > 0)
  {
    cells = pd->GetStrips();
    for (cells->InitTraversal(); cells->GetNextCell(npts, indx);)
    {
      for (i = 2; i < npts; i++)
      {
        if (i % 2 == 0)
        {
          i1 = i - 2;
          i2 = i - 1;
        }
        else
        {
          i1 = i - 1;
          i2 = i - 2;
        }
        if (pntData->GetNormals())
        {
          if (tcoords)
          {
            // treating vtkIdType as int
            fpObj << "f " << static_cast<int>(indx[i1]) + idStart << "/"
                  << static_cast<int>(indx[i1]) + idStart << "/"
                  << static_cast<int>(indx[i1]) + idStart << " ";
            fpObj << static_cast<int>(indx[i2]) + idStart << "/"
                  << static_cast<int>(indx[i2]) + idStart << "/"
                  << static_cast<int>(indx[i2]) + idStart << " ";
            fpObj << static_cast<int>(indx[i]) + idStart << "/"
                  << static_cast<int>(indx[i]) + idStart << "/"
                  << static_cast<int>(indx[i]) + idStart << "\n";
          }
          else
          {
            // treating vtkIdType as int
            fpObj << "f " << static_cast<int>(indx[i1]) + idStart << "//"
                  << static_cast<int>(indx[i1]) + idStart << " ";
            fpObj << static_cast<int>(indx[i2]) + idStart << "//"
                  << static_cast<int>(indx[i2]) + idStart << " ";
            fpObj << static_cast<int>(indx[i]) + idStart << "//"
                  << static_cast<int>(indx[i]) + idStart << "\n";
          }
        }
        else
        {
          if (tcoords)
          {
            // treating vtkIdType as int
            fpObj << "f " << static_cast<int>(indx[i1]) + idStart << "/"
                  << static_cast<int>(indx[i1]) + idStart << " ";
            fpObj << static_cast<int>(indx[i2]) + idStart << "/"
                  << static_cast<int>(indx[i2]) + idStart << " ";
            fpObj << static_cast<int>(indx[i]) + idStart << "/"
                  << static_cast<int>(indx[i]) + idStart << "\n";
          }
          else
          {
            // treating vtkIdType as int
            fpObj << "f " << static_cast<int>(indx[i1]) + idStart << " "
                  << static_cast<int>(indx[i2]) + idStart << " "
                  << static_cast<int>(indx[i]) + idStart << "\n";
          }
        }
      }
    }
  }

  idStart = idNext;
}

void vtkOBJExporter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "FilePrefix: " << (this->FilePrefix ? this->FilePrefix : "(null)") << "\n";
  os << indent << "OBJFileComment: " << (this->OBJFileComment ? this->OBJFileComment : "(null)")
     << "\n";
  os << indent << "MTLFileComment: " << (this->MTLFileComment ? this->MTLFileComment : "(null)")
     << "\n";
}
VTK_ABI_NAMESPACE_END