File: vtkmesh.cc

package info (click to toggle)
mia 2.4.7-16
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 17,332 kB
  • sloc: cpp: 162,690; python: 1,317; sh: 321; xml: 127; makefile: 41; csh: 24; ansic: 9
file content (328 lines) | stat: -rw-r--r-- 11,410 bytes parent folder | download | duplicates (2)
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
/* -*- mia-c++  -*-
 *
 * This file is part of MIA - a toolbox for medical image analysis
 * Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
 *
 * MIA is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MIA; if not, see <http://www.gnu.org/licenses/>.
 *
 */


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <vtkPolyData.h>
#include <vtkCellArray.h>
#include <vtkFloatArray.h>
#include <vtkPointData.h>
#include <vtkSmartPointer.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>


#include <vtk/vtkmesh.hh>
#include <mia/mesh/triangulate.hh>


NS_BEGIN(vtkmia)
using namespace mia;
using namespace std;

CVtkMeshIO::CVtkMeshIO():
       CMeshIOPlugin("vtk")
{
       add_suffix(".vtk");
       add_suffix(".VTK");
       add_suffix(".vtkmesh");
       add_suffix(".VTKMESH");
}

const char *const  CVtkMeshIO::s_scale_array = "scale";
const char *const  CVtkMeshIO::s_normal_array = "normals";
const char *const  CVtkMeshIO::s_color_array = "colors";


static CVtkMeshIO::PVertexfield read_vertices( /*const*/ vtkPolyData& mesh)
{
       auto n_vertices = mesh.GetNumberOfPoints();
       cvdebug() << "Got " << n_vertices << " vertices \n";
       auto vertices = CVtkMeshIO::PVertexfield(new CVtkMeshIO::CVertexfield(n_vertices));
       // copy all vertices
       auto iv = vertices->begin();

       for (auto i = 0; i < n_vertices; i++, ++iv) {
              double p[3];
              mesh.GetPoint(i, p);
              iv->x = p[0];
              iv->y = p[1];
              iv->z = p[2];
       }

       return vertices;
}

static CVtkMeshIO::PTrianglefield read_triangles(const CVtkMeshIO::CVertexfield& /*vertices*/, /*const*/ vtkPolyData& mesh)
{
       // read all cells, if a cell is formed of more than 3 corners, then triangulate,
       // if it hes less then 3 corners, ignore it (no wireframes supported here
       auto triangles = CVtkMeshIO::PTrianglefield(new CVtkMeshIO::CTrianglefield ());
       vtkIdType npts;
       vtkIdType const *pts;
       auto strips = mesh.GetStrips();

       while (strips->GetNextCell(npts, pts)) {
              cvdebug() << "Read cell of " << npts << " vertices\n";

              if (npts == 3) {
                     CVtkMeshIO::CTrianglefield::value_type t(pts[0], pts[1], pts[2]);
                     triangles->push_back(t);
              } else { // this is a real triangle strip
                     if (npts < 3) {
                            cvinfo() << "ignoring a" << ((npts == 2) ? "n edge " : " point") << "\n";
                            continue;
                     }

                     for (int i = 2; i < npts; ++i)  {
                            CVtkMeshIO::CTrianglefield::value_type t;
                            t.x = pts[i - 2];

                            // in triangle strips, every other triangle is winded in the other direction
                            // misses test to see if we got it right
                            if (i & 1) {
                                   t.z = pts[i - 1];
                                   t.y = pts[i];
                            } else {
                                   t.y = pts[i - 1];
                                   t.z = pts[i];
                            }

                            triangles->push_back(t);
                     }
              }
       }

       // we may also read polygons using the triangulator
       // TPolyTriangulator<CVtkMeshIO::CVertexfield, vector<vtkIdType>> triangulator(vertices);
       cvdebug() << "Got " << triangles->size() << " triangles \n";
       return triangles;
}

static void read_scalars(CTriangleMesh& mesh, /*const*/ vtkPointData& point_data)
{
       auto abstract_scalars = point_data.GetScalars();

       if (!abstract_scalars)
              return;

       auto scales = dynamic_cast<vtkFloatArray *>(abstract_scalars);

       if (!scales) {
              cvinfo() << " got scales field, but is not of type 'vtkFloatArray'\n";
              return;
       }

       if (scales->GetNumberOfComponents() != 1)  {
              cvinfo() << " got scales field, but it has " << scales->GetNumberOfComponents() << " "
                       << " instead of one.\n";
              return;
       }

       auto n_scale = scales->GetNumberOfTuples();

       if (n_scale != mesh.vertices_size()) {
              cverr() << "Have " << mesh.vertices_size() << " but got " << n_scale
                      << " scale values, ignoring the scales\n";
              return;
       }

       auto is = mesh.scale_begin();

       for (auto i = 0; i < n_scale; ++i, ++is)
              *is = scales->GetValue(i);
}

static void read_normals(CTriangleMesh& mesh, /*const*/ vtkPointData& point_data)
{
       auto abstract_normals = point_data.GetNormals();

       if (!abstract_normals)
              return;

       auto normals = dynamic_cast<vtkFloatArray *>(abstract_normals);

       if (!normals) {
              cvinfo() << " got normals field, but is not of type 'vtkFloatArray'\n";
              return;
       }

       if (normals->GetNumberOfComponents() != 3)  {
              cvinfo() << " got normals field, but it has " << normals->GetNumberOfComponents() << " "
                       << " instead of three.\n";
              return;
       }

       auto n_normals = normals->GetNumberOfTuples();

       if (n_normals != mesh.vertices_size()) {
              cverr() << "Have " << mesh.vertices_size() << " but got " << n_normals
                      << " normals values, ignoring the normals\n";
              return;
       }

       auto is = mesh.normals_begin();

       for (auto i = 0; i < n_normals; ++i, ++is) {
              normals->GetTypedTuple(i, &is->x);
              cvdebug() << i << ": read normal " << *is << "\n";
       }
}

static void read_colors(CTriangleMesh& mesh, /*const*/ vtkPointData& point_data)
{
       if (!point_data.HasArray(CVtkMeshIO::s_color_array))
              return;

       auto colors = dynamic_cast<vtkFloatArray *>(point_data.GetArray(CVtkMeshIO::s_color_array));

       if (!colors) {
              cvinfo() << " got colors field, but is not of type 'vtkFloatArray'\n";
              return;
       }

       if (colors->GetNumberOfComponents() != 3)  {
              cvinfo() << " got colors field, but it has " << colors->GetNumberOfComponents() << " "
                       << " instead of three.\n";
              return;
       }

       auto n_colors = colors->GetNumberOfTuples();

       if (n_colors != mesh.vertices_size()) {
              cverr() << "Have " << mesh.vertices_size() << " but got " << n_colors
                      << " colors values, ignoring the colors field\n";
              return;
       }

       auto is = mesh.color_begin();

       for (auto i = 0; i < n_colors; ++i, ++is)
              colors->GetTypedTuple(i, &is->x);
}

PTriangleMesh CVtkMeshIO::do_load(string const&   filename) const
{
       TRACE_FUNCTION;
       auto reader = vtkSmartPointer<vtkPolyDataReader>::New();
       reader->SetFileName(filename.c_str());
       reader->Update();
       auto mesh = reader->GetOutput();

       if (!mesh)
              return PTriangleMesh();

       auto vertices = read_vertices(*mesh);
       auto triangles = read_triangles(*vertices, *mesh);
       auto out_mesh = PTriangleMesh(new CTriangleMesh(triangles, vertices));
       // now check for scales, normals, and colors
       auto point_data = mesh->GetPointData();
       read_scalars(*out_mesh, *point_data);
       read_normals(*out_mesh, *point_data);
       read_colors(*out_mesh, *point_data);
       return out_mesh;
}

bool CVtkMeshIO::do_save(string const&   filename, const CTriangleMesh& mesh) const
{
       // construct VTK mesh
       auto points = vtkSmartPointer<vtkPoints>::New();
       for_each(mesh.vertices_begin(), mesh.vertices_end(),
       [&points](const CTriangleMesh::vertex_type & v) {
              points->InsertNextPoint(v.x, v.y, v.z);
       });
       auto triangles = vtkSmartPointer<vtkCellArray>::New();
       for_each(mesh.triangles_begin(), mesh.triangles_end(),
       [&triangles](const CTriangleMesh::triangle_type & x)->void {
              vtkIdType p[] = {
                     static_cast<int>(x.x),
                     static_cast<int>(x.y),
                     static_cast<int>(x.z)
              };
              triangles->InsertNextCell(3, p);
       });
       auto data = vtkSmartPointer<vtkPolyData>::New();
       data->SetPoints(points);
       data->SetStrips(triangles);
       auto point_data = data->GetPointData();

       // now convert the optional data
       if (mesh.get_available_data() & CTriangleMesh::ed_scale) {
              auto scales = vtkSmartPointer<vtkFloatArray>::New();
              scales->SetName(s_scale_array);
              for_each(mesh.scale_begin(), mesh.scale_end(),
              [&scales](CTriangleMesh::scale_type s) {
                     scales->InsertNextValue(s);
              });
              point_data->SetScalars(scales);
       }

       if (mesh.get_available_data() & CTriangleMesh::ed_color) {
              auto colors = vtkSmartPointer<vtkFloatArray>::New();
              colors->SetName(s_color_array);
              colors->SetNumberOfComponents (3);
              for_each(mesh.color_begin(), mesh.color_end(),
              [&colors](CTriangleMesh::color_type c) -> void {
                     colors->InsertNextTuple(&c.x);
              });
              point_data->AddArray(colors);
       }

       if (mesh.get_available_data() & CTriangleMesh::ed_normal) {
              auto normals = vtkSmartPointer<vtkFloatArray>::New();
              normals->SetName(s_normal_array);
              normals->SetNumberOfComponents (3);
              for_each(mesh.normals_begin(), mesh.normals_end(),
              [&normals](CTriangleMesh::normal_type n) -> void {
                     normals->InsertNextTuple(&n.x);
              });
              point_data->SetNormals(normals);
       }

       // write it
       auto writer = vtkSmartPointer<vtkPolyDataWriter>::New();
       writer->SetFileName(filename.c_str());
       writer->SetFileTypeToBinary();
#if  VTK_MAJOR_VERSION < 6
       writer->SetInput(data);
#else
       writer->SetInputData(data);
#endif
       return writer->Write();
}

const string  CVtkMeshIO::do_get_descr() const
{
       return "A subset of VTK mesh in-and output: Triangle meshes are written, and triangle "
              "meshes and triangle strips are read. Additional per-vertex attributes are supported: 'normals', "
              "'colors' for three component colors, and 'scale' for a scalar value attached to each vertex. "
              "The data is written by the vtkPolyDataWriter in binary format.";
}

extern "C" EXPORT CPluginBase *get_plugin_interface()
{
       //vista::prepare_vista_logging();
       return new CVtkMeshIO;
}

NS_END