-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathMesh.cpp
More file actions
1746 lines (1421 loc) · 52.9 KB
/
Mesh.cpp
File metadata and controls
1746 lines (1421 loc) · 52.9 KB
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
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Mesh.h"
// std
#include <math.h>
#include <tbb/parallel_for.h>
#include <algorithm>
#include <string>
#include <vector>
// libigl
#include <igl/cotmatrix.h>
#include <igl/exact_geodesic.h>
#include <igl/gaussian_curvature.h>
#include <igl/invert_diag.h>
#include <igl/massmatrix.h>
#include <igl/principal_curvature.h>
// vtk
#include <vtkAppendPolyData.h>
#include <vtkButterflySubdivisionFilter.h>
#include <vtkCenterOfMass.h>
#include <vtkCleanPolyData.h>
#include <vtkClipClosedSurface.h>
#include <vtkClipPolyData.h>
#include <vtkDoubleArray.h>
#include <vtkFeatureEdges.h>
#include <vtkFillHolesFilter.h>
#include <vtkGenericCell.h>
#include <vtkGradientFilter.h>
#include <vtkImageData.h>
#include <vtkImageStencil.h>
#include <vtkIncrementalPointLocator.h>
#include <vtkKdTreePointLocator.h>
#include <vtkLoopSubdivisionFilter.h>
#include <vtkNew.h>
#include <vtkOBJReader.h>
#include <vtkOBJWriter.h>
#include <vtkPLYReader.h>
#include <vtkPLYWriter.h>
#include <vtkPlaneCollection.h>
#include <vtkPointData.h>
#include <vtkPointLocator.h>
#include <vtkPolyDataConnectivityFilter.h>
#include <vtkPolyDataNormals.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataToImageStencil.h>
#include <vtkPolyDataWriter.h>
#include <vtkProbeFilter.h>
#include <vtkReverseSense.h>
#include <vtkSTLReader.h>
#include <vtkSTLWriter.h>
#include <vtkSelectEnclosedPoints.h>
#include <vtkSmoothPolyDataFilter.h>
#include <vtkStaticCellLocator.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkWindowedSincPolyDataFilter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLPolyDataWriter.h>
#include "FEFixMesh.h"
#include "Image.h"
#include "Libs/Optimize/Domain/MeshWrapper.h"
#include "Logging.h"
#include "MeshComputeThickness.h"
#include "MeshUtils.h"
#include "PreviewMeshQC/FEAreaCoverage.h"
#include "PreviewMeshQC/FEVTKExport.h"
#include "PreviewMeshQC/FEVTKImport.h"
#include "StringUtils.h"
// ACVD
#include <vtkIsotropicDiscreteRemeshing.h>
namespace shapeworks {
vtkSmartPointer<vtkPolyData> MeshReader::read(const std::string& pathname) {
if (pathname.empty()) {
throw std::invalid_argument("Empty pathname");
}
if (!ShapeWorksUtils::file_exists(pathname)) {
throw std::invalid_argument(pathname + " does not exist");
}
try {
if (StringUtils::hasSuffix(pathname, ".vtk")) {
auto reader = vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(pathname.c_str());
reader->SetReadAllScalars(1);
reader->Update();
return reader->GetOutput();
}
if (StringUtils::hasSuffix(pathname, ".vtp")) {
auto reader = vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName(pathname.c_str());
reader->Update();
return reader->GetOutput();
}
if (StringUtils::hasSuffix(pathname, ".stl")) {
auto reader = vtkSmartPointer<vtkSTLReader>::New();
reader->SetFileName(pathname.c_str());
reader->Update();
return reader->GetOutput();
}
if (StringUtils::hasSuffix(pathname, ".obj")) {
auto reader = vtkSmartPointer<vtkOBJReader>::New();
reader->SetFileName(pathname.c_str());
reader->Update();
return reader->GetOutput();
}
if (StringUtils::hasSuffix(pathname, ".ply")) {
auto reader = vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName(pathname.c_str());
reader->Update();
return reader->GetOutput();
}
throw std::invalid_argument("Unsupported file type");
} catch (const std::exception& exp) {
throw std::invalid_argument("Failed to read: " + pathname);
}
}
Mesh::Mesh(const Eigen::MatrixXd& points, const Eigen::MatrixXi& faces) {
this->poly_data_ = vtkSmartPointer<vtkPolyData>::New();
vtkNew<vtkPoints> vertices;
vtkNew<vtkCellArray> polys;
const int num_points = points.rows();
double p[3];
for (vtkIdType i = 0; i < num_points; ++i) {
p[0] = points(i, 0);
p[1] = points(i, 1);
p[2] = points(i, 2);
vertices->InsertNextPoint(p);
}
const int num_cells = faces.rows();
vtkIdType pts[3];
for (vtkIdType i = 0; i < num_cells; ++i) {
pts[0] = faces(i, 0);
pts[1] = faces(i, 1);
pts[2] = faces(i, 2);
polys->InsertNextCell(3, pts);
}
this->poly_data_->SetPoints(vertices);
this->poly_data_->SetPolys(polys);
this->computeNormals();
}
Mesh::Mesh(const std::string& pathname) : poly_data_(MeshReader::read(pathname)) { invalidateLocators(); }
Mesh& Mesh::write(const std::string& pathname, bool binaryFile) {
if (!this->poly_data_) {
throw std::invalid_argument("Mesh invalid");
}
if (pathname.empty()) {
throw std::invalid_argument("Empty pathname");
}
try {
if (StringUtils::hasSuffix(pathname, ".vtk")) {
auto writer = vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetFileVersion(42);
writer->SetFileName(pathname.c_str());
writer->SetInputData(this->poly_data_);
writer->WriteArrayMetaDataOff(); // needed for older readers to read these files
if (binaryFile)
writer->SetFileTypeToBinary();
else
writer->SetFileTypeToASCII();
writer->Update();
return *this;
}
if (StringUtils::hasSuffix(pathname, ".vtp")) {
auto writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New();
writer->SetFileName(pathname.c_str());
writer->SetInputData(this->poly_data_);
if (binaryFile)
writer->SetDataModeToBinary();
else
writer->SetDataModeToAscii();
writer->Update();
return *this;
}
if (StringUtils::hasSuffix(pathname, ".stl")) {
if (getFieldNames().size() > 0)
std::cerr << "WARNING: Trying to save mesh with new field. Only vtk and vtp files save associated fields\n";
auto writer = vtkSmartPointer<vtkSTLWriter>::New();
writer->SetFileName(pathname.c_str());
writer->SetInputData(this->poly_data_);
if (binaryFile)
writer->SetFileTypeToBinary();
else
writer->SetFileTypeToASCII();
writer->Update();
return *this;
}
if (StringUtils::hasSuffix(pathname, ".obj")) {
if (getFieldNames().size() > 0)
std::cerr << "WARNING: Trying to save mesh with new field. Only vtk and vtp files save associated fields\n";
auto writer = vtkSmartPointer<vtkOBJWriter>::New();
writer->SetFileName(pathname.c_str());
writer->SetInputData(this->poly_data_);
writer->Update();
return *this;
}
if (StringUtils::hasSuffix(pathname, ".ply")) {
if (getFieldNames().size() > 0)
std::cerr << "WARNING: Trying to save mesh with new field. Only vtk and vtp files save associated fields\n";
auto writer = vtkSmartPointer<vtkPLYWriter>::New();
writer->SetFileName(pathname.c_str());
writer->SetInputData(this->poly_data_);
if (binaryFile)
writer->SetFileTypeToBinary();
else
writer->SetFileTypeToASCII();
writer->Update();
return *this;
}
throw std::invalid_argument("Unsupported file type");
} catch (const std::exception& exp) {
throw std::invalid_argument("Failed to write mesh to " + pathname);
}
}
Mesh& Mesh::coverage(const Mesh& otherMesh, bool allowBackIntersections, double angleThreshold,
double backSearchRadius) {
FEVTKimport import;
std::shared_ptr<FEMesh> surf1{import.Load(this->poly_data_)};
std::shared_ptr<FEMesh> surf2{import.Load(otherMesh.poly_data_)};
if (surf1 == nullptr || surf2 == nullptr) {
throw std::invalid_argument("Mesh invalid");
}
FEAreaCoverage areaCoverage;
areaCoverage.AllowBackIntersection(allowBackIntersections);
areaCoverage.SetAngleThreshold(angleThreshold);
areaCoverage.SetBackSearchRadius(backSearchRadius);
vector<double> map1 = areaCoverage.Apply(surf1, surf2);
for (int i = 0; i < surf1->Nodes(); ++i) {
surf1->Node(i).m_ndata = map1[i];
}
FEVTKExport vtkOut;
VTKEXPORT ops = {false, true};
vtkOut.SetOptions(ops);
this->poly_data_ = vtkOut.ExportToVTK(*surf1);
this->invalidateLocators();
return *this;
}
Mesh& Mesh::smooth(int iterations, double relaxation) {
auto smoother = vtkSmartPointer<vtkSmoothPolyDataFilter>::New();
smoother->SetInputData(this->poly_data_);
smoother->SetNumberOfIterations(iterations);
if (relaxation) {
smoother->SetRelaxationFactor(relaxation);
smoother->FeatureEdgeSmoothingOff();
smoother->BoundarySmoothingOn();
}
smoother->Update();
this->poly_data_ = smoother->GetOutput();
// must regenerate normals after smoothing
computeNormals();
this->invalidateLocators();
return *this;
}
Mesh& Mesh::smoothSinc(int iterations, double passband) {
auto smoother = vtkSmartPointer<vtkWindowedSincPolyDataFilter>::New();
smoother->SetInputData(this->poly_data_);
// minimum of 2. See docs of vtkWindowedSincPolyDataFilter for explanation
iterations = std::max<int>(iterations, 2);
smoother->SetNumberOfIterations(iterations);
smoother->SetPassBand(passband);
smoother->Update();
this->poly_data_ = smoother->GetOutput();
// must regenerate normals after smoothing
computeNormals();
this->invalidateLocators();
return *this;
}
Mesh& Mesh::remesh(int numVertices, double adaptivity) {
// ACVD is very noisy to std::cout, even with console output set to zero
// setting the failbit on std::cout will silence this until it's cleared below
// std::cout.setstate(std::ios_base::failbit);
auto surf = vtkSmartPointer<vtkSurface>::New();
auto remesh = vtkSmartPointer<vtkQIsotropicDiscreteRemeshing>::New();
surf->CreateFromPolyData(this->poly_data_);
surf->GetCellData()->Initialize();
surf->GetPointData()->Initialize();
// surf->DisplayMeshProperties();
int subsamplingThreshold = 10; // subsampling threshold
numVertices = std::max<int>(numVertices, 1);
remesh->SetForceManifold(true);
remesh->SetInput(surf);
remesh->SetFileLoadSaveOption(0);
remesh->SetConsoleOutput(0);
remesh->SetSubsamplingThreshold(subsamplingThreshold);
remesh->GetMetric()->SetGradation(adaptivity);
remesh->SetDisplay(false);
remesh->SetUnconstrainedInitialization(1);
remesh->SetNumberOfClusters(numVertices);
remesh->Remesh();
// Restore std::cout
// std::cout.clear();
this->poly_data_ = remesh->GetOutput();
// must regenerate normals after smoothing
computeNormals();
this->invalidateLocators();
return *this;
}
Mesh& Mesh::remeshPercent(double percentage, double adaptivity) {
int numVertices = poly_data_->GetNumberOfPoints() * percentage;
return remesh(numVertices, adaptivity);
}
Mesh& Mesh::invertNormals() {
auto reverseSense = vtkSmartPointer<vtkReverseSense>::New();
reverseSense->SetInputData(this->poly_data_);
reverseSense->ReverseNormalsOff();
reverseSense->ReverseCellsOn();
reverseSense->Update();
this->poly_data_ = reverseSense->GetOutput();
return *this;
}
Mesh& Mesh::reflect(const Axis& axis, const Vector3& origin) {
Vector scale(makeVector({1, 1, 1}));
scale[axis] = -1;
MeshTransform transform = MeshTransform::New();
transform->Translate(-origin[0], -origin[1], -origin[2]);
transform->Scale(scale[0], scale[1], scale[2]);
transform->Translate(origin[0], origin[1], origin[2]);
this->invalidateLocators();
return invertNormals().applyTransform(transform);
}
MeshTransform Mesh::createTransform(const Mesh& target, Mesh::AlignmentType align, unsigned iterations) {
return createRegistrationTransform(target, align, iterations);
}
Mesh& Mesh::applyTransform(const MeshTransform transform) {
auto resampler = vtkSmartPointer<vtkTransformPolyDataFilter>::New();
resampler->SetTransform(transform);
resampler->SetInputData(this->poly_data_);
resampler->Update();
this->poly_data_ = resampler->GetOutput();
this->invalidateLocators();
return *this;
}
Mesh& Mesh::rotate(const double angle, const Axis axis) {
Vector rotation(makeVector({0, 0, 0}));
rotation[axis] = 1;
auto com = center();
MeshTransform transform = MeshTransform::New();
transform->Translate(com[0], com[1], com[2]);
transform->RotateWXYZ(angle, rotation[0], rotation[1], rotation[2]);
transform->Translate(-com[0], -com[1], -com[2]);
return applyTransform(transform);
}
Mesh& Mesh::fillHoles(double hole_size) {
auto filter = vtkSmartPointer<vtkFillHolesFilter>::New();
filter->SetInputData(this->poly_data_);
filter->SetHoleSize(hole_size);
filter->Update();
this->poly_data_ = filter->GetOutput();
auto origNormal = poly_data_->GetPointData()->GetNormals();
// Make the triangle window order consistent
computeNormals();
// Restore the original normals
poly_data_->GetPointData()->SetNormals(origNormal);
this->invalidateLocators();
return *this;
}
Mesh& Mesh::clean() {
auto clean = vtkSmartPointer<vtkCleanPolyData>::New();
clean->ConvertPolysToLinesOff();
clean->ConvertLinesToPointsOff();
clean->ConvertStripsToPolysOff();
clean->PointMergingOn();
clean->SetInputData(poly_data_);
clean->Update();
poly_data_ = clean->GetOutput();
invalidateLocators();
return *this;
}
Mesh& Mesh::probeVolume(const Image& image) {
auto probeFilter = vtkSmartPointer<vtkProbeFilter>::New();
probeFilter->SetInputData(this->poly_data_);
probeFilter->SetSourceData(image.getVTKImage());
probeFilter->Update();
this->poly_data_ = probeFilter->GetPolyDataOutput();
this->invalidateLocators();
return *this;
}
Mesh& Mesh::clip(const Plane plane) {
auto clipper = vtkSmartPointer<vtkClipPolyData>::New();
clipper->SetInputData(this->poly_data_);
clipper->SetClipFunction(plane);
clipper->Update();
this->poly_data_ = clipper->GetOutput();
this->invalidateLocators();
return *this;
}
Mesh& Mesh::translate(const Vector3& v) {
MeshTransform transform = MeshTransform::New();
transform->Translate(v[0], v[1], v[2]);
return applyTransform(transform);
}
Mesh& Mesh::scale(const Vector3& v) {
MeshTransform transform = MeshTransform::New();
transform->Scale(v[0], v[1], v[2]);
return applyTransform(transform);
}
PhysicalRegion Mesh::boundingBox() const {
PhysicalRegion bbox;
double bb[6];
poly_data_->GetBounds(bb);
for (int i = 0; i < 3; i++) {
bbox.min[i] = bb[2 * i];
bbox.max[i] = bb[2 * i + 1];
}
return bbox;
}
Mesh& Mesh::fixElement() {
FEVTKimport import;
FEMesh* meshFE = import.Load(this->poly_data_);
if (meshFE == nullptr) {
throw std::runtime_error("Unable to read mesh file");
}
FEFixMesh fix;
FEMesh* meshFix;
meshFix = fix.FixElementWinding(meshFE);
FEVTKExport vtkOut;
this->poly_data_ = vtkOut.ExportToVTK(*meshFix);
this->invalidateLocators();
return *this;
}
Mesh& Mesh::fixNonManifold() {
int count = 0;
while (count < 10) {
auto features = vtkSmartPointer<vtkFeatureEdges>::New();
features->SetInputData(this->poly_data_);
features->BoundaryEdgesOff();
features->FeatureEdgesOff();
features->NonManifoldEdgesOn();
features->ManifoldEdgesOff();
features->Update();
vtkSmartPointer<vtkPolyData> nonmanifold = features->GetOutput();
if (nonmanifold->GetNumberOfPoints() == 0 && nonmanifold->GetNumberOfCells() == 0) {
return *this;
}
SW_DEBUG("Number of non-manifold points: {}", nonmanifold->GetNumberOfPoints());
SW_DEBUG("Number of non-manifold cells: {}", nonmanifold->GetNumberOfCells());
SW_DEBUG("Attempting to fix non-manifold mesh");
std::vector<int> remove;
for (int j = 0; j < poly_data_->GetNumberOfPoints(); j++) {
double p2[3];
poly_data_->GetPoint(j, p2);
for (int i = 0; i < nonmanifold->GetNumberOfPoints(); i++) {
double p[3];
nonmanifold->GetPoint(i, p);
if (p[0] == p2[0] && p[1] == p2[1] && p[2] == p2[2]) {
remove.push_back(j);
}
}
}
SW_DEBUG("Removing {} non-manifold vertices", remove.size());
auto new_poly_data = vtkSmartPointer<vtkPolyData>::New();
auto vtk_pts = vtkSmartPointer<vtkPoints>::New();
auto vtk_triangles = vtkSmartPointer<vtkCellArray>::New();
double max_area = 0;
for (int i = 0; i < poly_data_->GetNumberOfCells(); i++) {
vtkSmartPointer<vtkIdList> list = vtkIdList::New();
poly_data_->GetCellPoints(i, list);
bool match = false;
for (int j = 0; j < list->GetNumberOfIds(); j++) {
int id = list->GetId(j);
for (unsigned int k = 0; k < remove.size(); k++) {
if (id == remove[k]) {
match = true;
}
}
}
if (match) {
// update max_area
double p0[3];
double p1[3];
double p2[3];
poly_data_->GetPoint(list->GetId(0), p0);
poly_data_->GetPoint(list->GetId(1), p1);
poly_data_->GetPoint(list->GetId(2), p2);
double area = vtkTriangle::TriangleArea(p0, p1, p2);
if (area > max_area) {
max_area = area;
}
poly_data_->DeleteCell(i);
}
}
poly_data_->RemoveDeletedCells();
fillHoles(max_area * 2.0);
vtkSmartPointer<vtkTriangleFilter> triangle_filter = vtkSmartPointer<vtkTriangleFilter>::New();
triangle_filter->SetInputData(poly_data_);
triangle_filter->Update();
poly_data_ = triangle_filter->GetOutput();
auto connectivityFilter = vtkSmartPointer<vtkPolyDataConnectivityFilter>::New();
connectivityFilter->SetExtractionModeToLargestRegion();
connectivityFilter->SetInputData(poly_data_);
connectivityFilter->Update();
poly_data_ = connectivityFilter->GetOutput();
// SW_DEBUG("done with fixing: ");
// detectNonManifold();
// SW_DEBUG("At end of fix non-manifold: ");
// detectTriangular();
this->invalidateLocators();
}
return *this;
}
bool Mesh::detectNonManifold() {
auto features = vtkSmartPointer<vtkFeatureEdges>::New();
features->SetInputData(this->poly_data_);
features->BoundaryEdgesOff();
features->FeatureEdgesOff();
features->NonManifoldEdgesOn();
features->ManifoldEdgesOff();
features->Update();
vtkSmartPointer<vtkPolyData> nonmanifold = features->GetOutput();
// SW_DEBUG("Detected Number of non-manifold points: {}", nonmanifold->GetNumberOfPoints());
// SW_DEBUG("Detected Number of non-manifold cells: {}", nonmanifold->GetNumberOfCells());
if (nonmanifold->GetNumberOfPoints() != 0 || nonmanifold->GetNumberOfCells() != 0) {
return true;
}
return false;
}
bool Mesh::detectTriangular() {
for (vtkIdType i = 0; i < poly_data_->GetNumberOfCells(); i++) {
vtkCell* cell = poly_data_->GetCell(i);
if (cell->GetNumberOfPoints() != 3) {
SW_WARN("Warning: non-triangular cell found (id = {}, n = {})", i, cell->GetNumberOfPoints());
return false;
}
}
return true;
}
std::vector<Field> Mesh::distance(const Mesh& target, const DistanceMethod method) const {
if (target.numPoints() == 0 || numPoints() == 0) {
throw std::invalid_argument("meshes must have points");
}
// allocate Arrays to store distances and ids from each point to target
auto distance = vtkSmartPointer<vtkDoubleArray>::New();
distance->SetNumberOfComponents(1);
distance->SetNumberOfTuples(numPoints());
distance->SetName("distance");
auto ids = vtkSmartPointer<vtkDoubleArray>::New();
ids->SetNumberOfComponents(1);
ids->SetNumberOfTuples(numPoints());
ids->SetName("ids");
// Find the nearest neighbors to each point and compute distance between them
Point3 currentPoint, closestPoint;
switch (method) {
case PointToPoint: {
// build point locator for target mesh
auto targetPointLocator = vtkSmartPointer<vtkKdTreePointLocator>::New();
targetPointLocator->SetDataSet(target.poly_data_);
targetPointLocator->BuildLocator();
for (int i = 0; i < numPoints(); i++) {
poly_data_->GetPoint(i, currentPoint.GetDataPointer());
vtkIdType closestPointId = targetPointLocator->FindClosestPoint(currentPoint.GetDataPointer());
target.poly_data_->GetPoint(closestPointId, closestPoint.GetDataPointer());
ids->SetValue(i, closestPointId);
distance->SetValue(i, length(currentPoint - closestPoint));
}
} break;
case PointToCell: {
// build cell locator for target mesh
auto targetCellLocator = vtkSmartPointer<vtkStaticCellLocator>::New();
targetCellLocator->SetDataSet(target.poly_data_);
targetCellLocator->BuildLocator();
double dist2;
auto cell = vtkSmartPointer<vtkGenericCell>::New();
vtkIdType cellId;
int subId;
for (int i = 0; i < numPoints(); i++) {
poly_data_->GetPoint(i, currentPoint.GetDataPointer());
targetCellLocator->FindClosestPoint(currentPoint.GetDataPointer(), closestPoint.GetDataPointer(), cell, cellId,
subId, dist2);
ids->SetValue(i, cellId);
distance->SetValue(i, std::sqrt(dist2));
}
} break;
case SymmetricPointToCell: {
/*
referenceMesh (point) -> targetMesh (cell) (and get closestPoint)
referenceMesh (cell) -> targetMesh (closestPoint)
*/
auto targetCellLocator = vtkSmartPointer<vtkCellLocator>::New();
targetCellLocator->SetDataSet(target.poly_data_);
targetCellLocator->BuildLocator();
auto refCellLocator = vtkSmartPointer<vtkCellLocator>::New();
refCellLocator->SetDataSet(poly_data_);
refCellLocator->BuildLocator();
double dist2_target, dist2_ref;
auto cell_target = vtkSmartPointer<vtkGenericCell>::New();
auto cell_ref = vtkSmartPointer<vtkGenericCell>::New();
vtkIdType cellId_target, cellId_ref;
int subId_target, subId_ref;
Point3 closestPoint_target, closestPoint_ref;
for (int i = 0; i < numPoints(); i++) {
poly_data_->GetPoint(i, currentPoint.GetDataPointer()); // ref point
// ref mesh point -> target mesh cell
targetCellLocator->FindClosestPoint(currentPoint.GetDataPointer(), closestPoint_target.GetDataPointer(), cell_target, cellId_target,
subId_target, dist2_target);
// target mesh closest point -> ref mesh cell
refCellLocator->FindClosestPoint(closestPoint_target.GetDataPointer(), closestPoint_ref.GetDataPointer(), cell_ref, cellId_ref,
subId_ref, dist2_ref);
ids->SetValue(i, cellId_target);
auto mean_sym_dist = (std::sqrt(dist2_target) + std::sqrt(dist2_ref))/2;
distance->SetValue(i, mean_sym_dist);
}
} break;
default:
throw std::invalid_argument("invalid distance method");
}
return std::vector<Field>{distance, ids};
}
// TODO^2: do the same thing for the other couple functions below that set a field and return the other field (they
// shouldn't be setting a field) (search for setField and you'll see the 2-3 places it needs to be done)
Mesh& Mesh::clipClosedSurface(const Plane plane) {
auto planeCollection = vtkSmartPointer<vtkPlaneCollection>::New();
planeCollection->AddItem(plane);
auto clipper = vtkSmartPointer<vtkClipClosedSurface>::New();
clipper->SetClippingPlanes(planeCollection);
clipper->SetInputData(this->poly_data_);
clipper->SetGenerateFaces(1);
clipper->Update();
this->poly_data_ = clipper->GetOutput();
this->invalidateLocators();
return *this;
}
Mesh& Mesh::computeNormals() {
auto normal = vtkSmartPointer<vtkPolyDataNormals>::New();
normal->SetInputData(this->poly_data_);
normal->ComputeCellNormalsOn();
normal->ComputePointNormalsOn();
normal->AutoOrientNormalsOn();
normal->SplittingOff();
normal->Update();
this->poly_data_ = normal->GetOutput();
return *this;
}
void Mesh::invalidateLocators() const {
this->cellLocator = nullptr;
this->pointLocator = nullptr;
}
void Mesh::updatePointLocator() const {
if (!this->pointLocator) {
this->pointLocator = vtkSmartPointer<vtkKdTreePointLocator>::New();
this->pointLocator->SetDataSet(this->poly_data_);
this->pointLocator->BuildLocator();
}
}
void Mesh::updateCellLocator() const {
if (!this->cellLocator) {
this->cellLocator = vtkSmartPointer<vtkStaticCellLocator>::New();
this->cellLocator->SetDataSet(this->poly_data_);
this->cellLocator->BuildLocator();
}
}
Point3 Mesh::closestPoint(const Point3 point, double& distance, vtkIdType& face_id) const {
this->updateCellLocator();
double dist2;
Point3 closestPoint;
auto cell = vtkSmartPointer<vtkGenericCell>::New();
int subId;
cellLocator->FindClosestPoint(point.GetDataPointer(), closestPoint.GetDataPointer(), cell, face_id, subId, dist2);
// distance from point to closest point
distance = sqrt(dist2);
return closestPoint;
}
int Mesh::closestPointId(const Point3 point) const {
this->updatePointLocator();
vtkIdType closestPointId = pointLocator->FindClosestPoint(point.GetDataPointer());
return closestPointId;
}
bool Mesh::isPointInside(const Point3 point) const {
// create point set
auto points = vtkSmartPointer<vtkPoints>::New();
points->InsertNextPoint(point.GetDataPointer());
auto polydata = vtkSmartPointer<vtkPolyData>::New();
polydata->SetPoints(points);
auto select = vtkSmartPointer<vtkSelectEnclosedPoints>::New();
select->SetInputData(polydata);
select->SetSurfaceData(this->poly_data_);
select->SetTolerance(0.0001);
select->Update();
return select->IsInside(0);
}
double Mesh::geodesicDistance(int source, int target) const {
if (source < 0 || target < 0 || numPoints() < source || numPoints() < target) {
throw std::invalid_argument("requested point ids outside range of points available in mesh");
}
MeshWrapper wrap(this->poly_data_, true);
return wrap.ComputeDistance(getPoint(source), -1, getPoint(target), -1);
}
Field Mesh::geodesicDistance(const Point3 landmark) const {
auto distance = vtkSmartPointer<vtkDoubleArray>::New();
distance->SetNumberOfComponents(1);
distance->SetNumberOfTuples(numPoints());
distance->SetName("GeodesicDistanceToLandmark");
MeshWrapper wrap(this->poly_data_, true);
for (int i = 0; i < numPoints(); i++) {
distance->SetValue(i, wrap.ComputeDistance(landmark, -1, getPoint(i), -1));
}
return distance;
}
Field Mesh::geodesicDistance(const std::vector<Point3> curve) const {
auto minDistance = vtkSmartPointer<vtkDoubleArray>::New();
minDistance->SetNumberOfComponents(1);
minDistance->SetNumberOfTuples(numPoints());
minDistance->SetName("GeodesicDistanceToCurve");
minDistance->Fill(1e20);
for (int i = 0; i < curve.size(); i++) {
Field distance = geodesicDistance(curve[i]);
for (int j = 0; j < numPoints(); j++) {
if (distance->GetTuple1(j) < minDistance->GetTuple1(j)) minDistance->SetValue(j, distance->GetTuple1(j));
}
}
return minDistance;
}
Field Mesh::curvature(const CurvatureType type) const {
Eigen::MatrixXd V = points();
Eigen::MatrixXi F = faces();
Eigen::MatrixXd PD1, PD2;
Eigen::VectorXd PV1, PV2;
Eigen::VectorXd C;
auto curv = vtkSmartPointer<vtkDoubleArray>::New();
curv->SetNumberOfComponents(1);
curv->SetNumberOfTuples(numPoints());
switch (type) {
case Principal: {
curv->SetName("principal curvature");
// returns maximal curvature value for each vertex
// igl::principal_curvature(V, F, PD1, PD2, PV1, PV2);
// returns minimal curvature value for each vertex
igl::principal_curvature(V, F, PD1, PD2, C, PV2);
break;
}
case Gaussian: {
curv->SetName("gaussian curvature");
igl::gaussian_curvature(V, F, C);
break;
}
case Mean: {
curv->SetName("mean curvature");
Eigen::MatrixXd HN;
Eigen::SparseMatrix<double> L, M, Minv;
igl::cotmatrix(V, F, L);
igl::massmatrix(V, F, igl::MASSMATRIX_TYPE_VORONOI, M);
igl::invert_diag(M, Minv);
// Laplace-Beltrami of position
HN = -Minv * (L * V);
// Extract magnitude as mean curvature
C = HN.rowwise().norm();
// Compute curvature directions via quadric fitting
igl::principal_curvature(V, F, PD1, PD2, PV1, PV2);
// mean curvature
C = 0.5 * (PV1 + PV2);
break;
}
default:
throw std::invalid_argument("Unknown Mesh::CurvatureType.");
}
for (int i = 0; i < numPoints(); i++) curv->SetValue(i, C[i]);
return curv;
}
void computeGradient(vtkDataSet* inputDataSet, const char* scalarFieldName, const char* gradientFieldName) {
vtkSmartPointer<vtkGradientFilter> gradientFilter = vtkSmartPointer<vtkGradientFilter>::New();
gradientFilter->SetInputData(inputDataSet);
gradientFilter->SetInputScalars(vtkDataSet::FIELD_ASSOCIATION_POINTS, scalarFieldName);
gradientFilter->SetResultArrayName(gradientFieldName);
gradientFilter->Update();
/*
vtkSmartPointer<vtkDoubleArray> gradientData = vtkSmartPointer<vtkDoubleArray>::New();
gradientData->SetNumberOfComponents(3);
gradientData->SetNumberOfTuples(inputDataSet->GetNumberOfPoints());
gradientData->SetName(gradientFieldName);
*/
vtkDoubleArray* gradPointArray = vtkArrayDownCast<vtkDoubleArray>(
vtkDataSet::SafeDownCast(gradientFilter->GetOutput())->GetPointData()->GetArray(gradientFieldName));
/*
for (vtkIdType pointId = 0; pointId < inputDataSet->GetNumberOfPoints(); ++pointId) {
double gradient[3];
gradientFilter->GetOutput()->GetPointData()->GetTuple(pointId, gradient);
gradientData->SetTuple(pointId, gradient);
}
*/
// inputDataSet->GetPointData()->AddArray(gradientData);
inputDataSet->GetPointData()->AddArray(gradPointArray);
}
void Mesh::computeFieldGradient(const std::string& field) const {
computeGradient(poly_data_, field.c_str(), (std::string("gradient_") + field).c_str());
return;
auto arr = poly_data_->GetPointData()->GetArray(field.c_str());
// for each vertex, compute the gradient of the field and store x,y,z
// components in a vector
auto gradient = vtkSmartPointer<vtkDoubleArray>::New();
gradient->SetNumberOfComponents(3);
gradient->SetNumberOfTuples(numPoints());
gradient->SetName((std::string("gradient_") + field).c_str());
for (int i = 0; i < numPoints(); i++) {
// get the field value at this vertex
double value = arr->GetTuple1(i);
// collect all neighboring vertices using vtk
auto cell = vtkSmartPointer<vtkGenericCell>::New();
auto neighbors = vtkSmartPointer<vtkIdList>::New();
poly_data_->GetPointCells(i, neighbors);
int num_neighbors = neighbors->GetNumberOfIds();
// for each neighbor vertex
double x = 0.0;
double y = 0.0;
double z = 0.0;
for (int j = 0; j < num_neighbors; j++) {
// get the neighbor vertex id
int neighbor_id = neighbors->GetId(j);
// get the neighbor vertex
auto neighbor = poly_data_->GetPoint(neighbor_id);
// get the neighbor vertex value
double neighbor_value = arr->GetTuple1(neighbor_id);
// compute the gradient
x += (neighbor[0] - getPoint(i)[0]) * (neighbor_value - value);
y += (neighbor[1] - getPoint(i)[1]) * (neighbor_value - value);
z += (neighbor[2] - getPoint(i)[2]) * (neighbor_value - value);
}
gradient->SetTuple3(i, x, y, z);
}
poly_data_->GetPointData()->AddArray(gradient);
}
Eigen::Vector3d Mesh::computeFieldGradientAtPoint(const std::string& field, const Point3& query) const {
this->updateCellLocator();
// compute gradient if not already computed