-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegmentation2.cpp
3684 lines (2995 loc) · 144 KB
/
segmentation2.cpp
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 <vector>
#include <algorithm>
#include <iostream>
#include <iomanip> // for std::setw
#include <cmath>
#include <random>
#include <limits>
#include <unordered_set>
#include <stack>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/boost/graph/iterator.h>
#include <CGAL/Polygon_2.h>
#include <CGAL/convex_hull_2.h>
#include <CGAL/convex_hull_3_to_face_graph.h>
#include <CGAL/convex_hull_3.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/Side_of_triangle_mesh.h>
#include <CGAL/Polygon_mesh_processing/measure.h>
#include <CGAL/Delaunay_triangulation_3.h>
#include <CGAL/Surface_mesh.h>
#include <list>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstddef>
#include <new>
#include <memory>
#include <omp.h>
#include <deque>
#include <queue> // for std::priority_queue
#include <utility> // for std::pair
#include <algorithm> // for std::all_of
#include <cstdlib> // for std::exit
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
// #include "/tinyobj_loader_opt.h"
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_2 Point_2;
typedef K::Point_3 Point_3;
typedef CGAL::Polygon_2<K> Polygon_2;
typedef CGAL::Polyhedron_3<K> Polyhedron_3;
typedef CGAL::Delaunay_triangulation_3<K> Delaunay;
typedef CGAL::Surface_mesh<Point_3> Surface_mesh;
class Triangle;
class TriangleAdjacency;
class Hull;
// Assuming a Vector3D structure is present somewhere, used for normals.
class Vector3D {
public:
double x, y, z;
// Constructors
Vector3D() : x(0), y(0), z(0) {}
Vector3D(double x, double y, double z) : x(x), y(y), z(z) {}
// Subtraction
Vector3D operator-(const Vector3D& other) const {
return Vector3D(x - other.x, y - other.y, z - other.z);
}
// Cross product
Vector3D cross(const Vector3D& other) const {
double newX = y * other.z - z * other.y;
double newY = z * other.x - x * other.z;
double newZ = x * other.y - y * other.x;
return Vector3D(newX, newY, newZ);
}
Vector3D operator/(double scalar) const {
if (std::abs(scalar) < 1e-9) { // Avoid division by zero
return *this; // Return the original vector or handle this case differently
}
return Vector3D(x / scalar, y / scalar, z / scalar);
}
// Overload the += operator
Vector3D& operator+=(const Vector3D& rhs) {
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this; // Return this instance
}
// Overload the /= operator for scalar division
Vector3D& operator/=(double scalar) {
if (scalar != 0.0) { // Avoid division by zero
x /= scalar;
y /= scalar;
z /= scalar;
}
return *this; // Return this instance
}
bool operator<(const Vector3D& rhs) const {
if (x != rhs.x) return x < rhs.x;
if (y != rhs.y) return y < rhs.y;
return z < rhs.z;
}
Vector3D operator+(const Vector3D& other) const {
Vector3D result;
result.x = this->x + other.x;
result.y = this->y + other.y;
result.z = this->z + other.z;
return result;
}
double dot(const Vector3D& other) const {
return x * other.x + y * other.y + z * other.z;
}
// Length (magnitude) of the vector
double length() const {
return std::sqrt(x * x + y * y + z * z);
}
// Check if vector is a zero vector
bool isZero() const {
const double epsilon = 1e-9; // Adjust this to your needs
return std::abs(x) < epsilon && std::abs(y) < epsilon && std::abs(z) < epsilon;
}
bool operator==(const Vector3D& other) const {
return x == other.x && y == other.y && z == other.z;
}
std::string toString() const {
return "(" + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ")";
}
void normalize() {
double len = length();
if (len > 0) {
x /= len;
y /= len;
z /= len;
}
}
};
struct Vector3DHash {
std::size_t operator()(const Vector3D& vec) const {
std::size_t hx = std::hash<double>()(vec.x);
std::size_t hy = std::hash<double>()(vec.y);
std::size_t hz = std::hash<double>()(vec.z);
return hx ^ (hy << 1) ^ hz;
}
};
namespace std {
template <>
struct hash<Vector3D> {
std::size_t operator()(const Vector3D& vec) const {
Vector3DHash hasher;
return hasher(vec);
}
};
}
class Vertex {
public:
int x, y, z; // 3D coordinates
Vertex() : x(0), y(0), z(0) {}
Vertex(int index) : x(index), y(index), z(index) {} // New constructor
Vertex(int x, int y, int z) : x(x), y(y), z(z) {}
Vertex(const Vector3D& vec) : x(vec.x), y(vec.y), z(vec.z) {}
bool operator==(const Vertex& other) const {
return x == other.x && y == other.y && z == other.z;
}
bool operator!=(const Vertex& other) const {
return !(*this == other);
}
bool isValid() const {
return !std::isnan(x) && !std::isnan(y) && !std::isnan(z);
}
Vector3D toVector3D() const {
return Vector3D(x, y, z); // assuming Vertex has x, y, and z as public members.
}
std::string toString() const {
return "(" + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ")";
}
};
namespace std {
template <> struct hash<Vertex> {
size_t operator()(const Vertex& v) const {
return hash<int>()(v.x) ^ hash<int>()(v.y) ^ hash<int>()(v.z);
}
};
}
struct TriangleEdge {
Vector3D v1, v2;
TriangleEdge(const Vector3D& a, const Vector3D& b) : v1(a), v2(b) {
if (v2 < v1) {
std::swap(v1, v2);
}
}
bool operator==(const TriangleEdge& other) const {
return v1 == other.v1 && v2 == other.v2;
}
bool operator!=(const TriangleEdge& other) const {
return !(*this == other);
}
bool operator<(const TriangleEdge& other) const {
if (v1 == other.v1) return v2 < other.v2;
return v1 < other.v1;
}
std::string toString() const {
return "[" + v1.toString() + ", " + v2.toString() + "]";
}
};
struct EdgeHash {
Vector3DHash vecHash; // Using your custom hash function for Vector3D
size_t operator()(const TriangleEdge& edge) const {
size_t h1 = vecHash(edge.v1);
size_t h2 = vecHash(edge.v2);
return h1 ^ (h2 << 1); // XOR and shift h2 before combining with h1 for better distribution
}
};
class Triangle {
public:
Vector3D vec1, vec2, vec3;
Vector3D normal;
double area;
double e_min;
double e_max;
Vector3D color;
std::string type; // The type of this triangle
Triangle() : area(0), e_min(0), e_max(0) {}
Triangle(const Vector3D& a, const Vector3D& b, const Vector3D& c);
bool isValid() const;
bool operator==(const Triangle& other) const;
bool operator!=(const Triangle& other) const;
bool operator<(const Triangle& other) const;
void setColor(const Vector3D& assignedColor);
std::vector<TriangleEdge> getEdges() const;
bool isAdjacent(const Triangle& other, const class TriangleAdjacency& adjacency) const;
bool isNewAdjacent(const Triangle& other, const class TriangleAdjacency& adjacency) const; // Added this
std::string toString() const; // Added toString() method
bool isDegenerate() const;
};
namespace std {
template <>
struct hash<Triangle> {
size_t operator()(const Triangle& t) const {
std::hash<Vector3D> vertexHasher;
size_t h1 = vertexHasher(t.vec1);
size_t h2 = vertexHasher(t.vec2);
size_t h3 = vertexHasher(t.vec3);
return h1 ^ (h2 << 1) ^ (h3 << 2); // or use boost::hash_combine (better)
}
};
}
class TriangleAdjacency {
private:
typedef TriangleEdge Edge;
std::unordered_map<Edge, std::unordered_set<Triangle>, EdgeHash> adjacencyMap;
public:
void addTriangle(const Triangle& triangle);
bool isAdjacent(const Triangle& t1, const Triangle& t2) const;
bool isNewAdjacent(const Triangle& t1, const Triangle& t2) const;
std::string toString() const; // Added toString() method
std::unordered_set<Triangle> getAdjacentTriangles(const Triangle& t) const;
};
// Triangle methods
Triangle::Triangle(const Vector3D& a, const Vector3D& b, const Vector3D& c)
: vec1(a), vec2(b), vec3(c) {
Vector3D edge1 = vec2 - vec1;
Vector3D edge2 = vec3 - vec1;
normal = edge1.cross(edge2);
double normalLength = normal.length();
normal = normal / normalLength;
if (normalLength > 1e-9) {
normal = normal / normalLength; // This line normalizes the normal vector
}
area = 0.5 * normalLength;
double len1 = edge1.length();
double len2 = edge2.length();
double len3 = (vec3 - vec2).length();
e_min = std::min({len1, len2, len3});
e_max = std::max({len1, len2, len3});
}
bool Triangle::isValid() const {
return !vec1.isZero() || !vec2.isZero() || !vec3.isZero();
}
bool Triangle::operator==(const Triangle& other) const {
return (vec1 == other.vec1 && vec2 == other.vec2 && vec3 == other.vec3) ||
(vec1 == other.vec1 && vec2 == other.vec3 && vec3 == other.vec2) ||
(vec1 == other.vec2 && vec2 == other.vec1 && vec3 == other.vec3) ||
(vec1 == other.vec2 && vec2 == other.vec3 && vec3 == other.vec1) ||
(vec1 == other.vec3 && vec2 == other.vec1 && vec3 == other.vec2) ||
(vec1 == other.vec3 && vec2 == other.vec2 && vec3 == other.vec1);
}
bool Triangle::operator!=(const Triangle& other) const {
return !(*this == other);
}
bool Triangle::operator<(const Triangle& other) const {
return this->area < other.area;
}
void Triangle::setColor(const Vector3D& assignedColor) {
color = assignedColor;
}
std::vector<TriangleEdge> Triangle::getEdges() const {
return {TriangleEdge(vec1, vec2), TriangleEdge(vec2, vec3), TriangleEdge(vec3, vec1)};
}
bool Triangle::isAdjacent(const Triangle& other, const TriangleAdjacency& adjacency) const {
return adjacency.isAdjacent(*this, other);
}
bool Triangle::isNewAdjacent(const Triangle& other, const TriangleAdjacency& adjacency) const {
return adjacency.isNewAdjacent(*this, other);
}
std::string Triangle::toString() const {
return "Triangle: [" + vec1.toString() + ", " + vec2.toString() + ", " + vec3.toString() + "]";
}
bool Triangle::isDegenerate() const {
double area = 0.5 * std::abs((vec1.x - vec2.x)*(vec1.y - vec3.y) - (vec1.x - vec3.x)*(vec1.y - vec2.y));
return area == 0;
}
// TriangleAdjacency methods
void TriangleAdjacency::addTriangle(const Triangle& triangle) {
std::vector<TriangleEdge> edges = {
TriangleEdge(triangle.vec1, triangle.vec2),
TriangleEdge(triangle.vec2, triangle.vec3),
TriangleEdge(triangle.vec3, triangle.vec1)
};
for (const TriangleEdge& edge : edges) {
adjacencyMap[edge].insert(triangle);
}
}
bool TriangleAdjacency::isAdjacent(const Triangle& t1, const Triangle& t2) const {
std::vector<TriangleEdge> edges = {
TriangleEdge(t1.vec1, t1.vec2),
TriangleEdge(t1.vec2, t1.vec3),
TriangleEdge(t1.vec3, t1.vec1)
};
for (const TriangleEdge& edge : edges) {
if (adjacencyMap.count(edge) && adjacencyMap.at(edge).count(t2)) {
return true;
}
}
return false;
}
bool TriangleAdjacency::isNewAdjacent(const Triangle& t1, const Triangle& t2) const {
// Implement your new adjacency logic here
// Example: Share at least two vertices
std::unordered_set<Vector3D> vertices1 = {t1.vec1, t1.vec2, t1.vec3};
std::unordered_set<Vector3D> vertices2 = {t2.vec1, t2.vec2, t2.vec3};
std::vector<Vector3D> commonVertices;
for (const auto& vertex : vertices1) {
if (vertices2.count(vertex)) {
commonVertices.push_back(vertex);
}
}
if (commonVertices.size() >= 2) {
return true;
}
return false; // Replace this with your logic
}
std::string TriangleAdjacency::toString() const {
std::ostringstream oss;
oss << "TriangleAdjacency: {" << std::endl;
for (const auto& entry : adjacencyMap) {
const Edge& edge = entry.first;
const std::unordered_set<Triangle>& adjacentTriangles = entry.second;
oss << " Edge: " << edge.toString() << " -> Adjacent Triangles: {";
for (const Triangle& triangle : adjacentTriangles) {
oss << triangle.toString() << ", ";
}
oss << "}," << std::endl;
}
oss << "}" << std::endl;
return oss.str();
}
std::unordered_set<Triangle> TriangleAdjacency::getAdjacentTriangles(const Triangle& t) const {
std::unordered_set<Triangle> adjacentTriangles;
for (const TriangleEdge& edge : t.getEdges()) {
auto it = adjacencyMap.find(edge);
if (it != adjacencyMap.end()) {
adjacentTriangles.insert(it->second.begin(), it->second.end());
}
}
adjacentTriangles.erase(t); // Remove the triangle itself from its adjacent list
return adjacentTriangles;
}
struct TriangleIndices {
int v1, v2, v3;
// Default constructor
TriangleIndices() : v1(0), v2(0), v3(0) {}
// Parameterized constructor
TriangleIndices(int v1, int v2, int v3) : v1(v1), v2(v2), v3(v3) {}
};
Vector3D computeNormal(const Vector3D& v1, const Vector3D& v2, const Vector3D& v3) {
Vector3D edge1 = v2 - v1;
Vector3D edge2 = v3 - v1;
Vector3D normal = edge1.cross(edge2);
normal.normalize(); // Assuming you have a normalize method
return normal;
}
std::vector<Triangle> indicesToTriangles(const std::vector<TriangleIndices>& indices, const std::vector<Vector3D>& vertices) {
std::vector<Triangle> triangles;
for (const auto& index : indices) {
Vector3D v1 = vertices[index.v1];
Vector3D v2 = vertices[index.v2];
Vector3D v3 = vertices[index.v3];
Triangle t(v1, v2, v3);
// Compute the normal and normalize it
t.normal = computeNormal(v1, v2, v3);
// Compute the magnitude of the normal vector manually
double magnitude = std::sqrt(t.normal.x * t.normal.x + t.normal.y * t.normal.y + t.normal.z * t.normal.z);
// Check for a degenerate triangle based on the magnitude of the normal vector
if (magnitude < 1e-6) { // Adjust threshold as needed
std::cerr << "Degenerate triangle detected, skipping." << std::endl;
continue; // Skip this triangle and continue with the next iteration
}
triangles.push_back(t);
}
return triangles;
}
struct Cluster {
std::vector<Triangle> triangles;
bool operator==(const Cluster& other) const {
return triangles == other.triangles;
}
};
struct TupleHash {
std::size_t operator()(const std::tuple<int, int, int>& k) const {
size_t h1 = std::hash<int>{}(std::get<0>(k));
size_t h2 = std::hash<int>{}(std::get<1>(k));
size_t h3 = std::hash<int>{}(std::get<2>(k));
return h1 ^ (h2 << 1) ^ (h3 << 2);
}
};
struct IndexedTriangle {
int clusterIndex;
Triangle triangle;
};
class SpatialHash {
private:
double cellSize;
double invCellSize; // Reciprocal of cellSize for optimization
std::unordered_map<std::tuple<int, int, int>, std::vector<IndexedTriangle>, TupleHash> hashTable;
std::unordered_map<Triangle, std::vector<Triangle>> adjacencyMap;
std::unordered_map<Triangle, std::array<std::tuple<int, int, int>, 3>> precomputedHashes;
// std::unordered_map<Triangle, std::vector<Triangle>> precomputedNeighbors;
std::tuple<int, int, int> hash(const Vector3D& vec) {
int x = static_cast<int>(std::floor(vec.x * invCellSize));
int y = static_cast<int>(std::floor(vec.y * invCellSize));
int z = static_cast<int>(std::floor(vec.z * invCellSize));
return {x, y, z};
}
std::array<std::tuple<int, int, int>, 3> getTriangleHashes(const Triangle& t) {
return {hash(t.vec1), hash(t.vec2), hash(t.vec3)};
}
public:
SpatialHash(double size) : cellSize(size), invCellSize(1.0 / size) {}
std::vector<std::string> keys() const {
std::vector<std::string> allKeys;
for (const auto& [key, _] : hashTable) {
auto [x, y, z] = key;
allKeys.push_back(std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z));
}
return allKeys;
}
size_t size() const {
return hashTable.size();
}
std::unordered_set<int> getNeighboringClusters(const Triangle& t, const TriangleAdjacency& adjacency) {
std::unordered_set<int> clusterIndices;
// Use the iterator from find to avoid a second lookup
auto it = precomputedHashes.find(t);
if (it == precomputedHashes.end()) {
std::cerr << "Triangle not found in precomputed hashes: " << t.toString() << std::endl;
return clusterIndices;
}
const auto& hashes = it->second;
for (const auto& h : hashes) {
// Use iterator for the hashTable lookup
auto hashIt = hashTable.find(h);
if (hashIt == hashTable.end()) continue;
for (const auto& indexedTriangle : hashIt->second) {
const Triangle& potentialNeighbor = indexedTriangle.triangle;
if (potentialNeighbor != t) {
// Add an adjacency check here
// if (t.isAdjacent(potentialNeighbor, adjacency)) {
clusterIndices.insert(indexedTriangle.clusterIndex);
// }
}
}
}
return clusterIndices;
}
std::vector<Triangle> getPotentialNeighbors(const Triangle& t, const TriangleAdjacency& adjacency) {
std::unordered_set<Triangle> neighbors;
auto it = precomputedHashes.find(t);
if (it == precomputedHashes.end()) {
std::cout << "Error: Triangle hashes not precomputed for: " << t.toString() << std::endl;
return {};
}
const auto& hashes = it->second;
for (const auto& h : hashes) {
for (const auto& indexedTriangle : hashTable[h]) {
const Triangle& potentialNeighbor = indexedTriangle.triangle;
if (potentialNeighbor != t && t.isAdjacent(potentialNeighbor, adjacency)) {
neighbors.insert(potentialNeighbor);
}
}
}
return std::vector<Triangle>(neighbors.begin(), neighbors.end());
}
std::unordered_set<int> getNeighboringClustersForCluster(const Cluster& cluster, const TriangleAdjacency& adjacency) {
std::unordered_set<int> clusterIndices;
std::unordered_set<Triangle> processedTriangles;
for (const auto& triangle : cluster.triangles) {
auto neighboringClustersForTriangle = getNeighboringClusters(triangle, adjacency);
clusterIndices.insert(neighboringClustersForTriangle.begin(), neighboringClustersForTriangle.end());
}
return clusterIndices;
}
void precomputeTriangleHashes(const std::vector<Cluster>& clusters) {
size_t totalTriangles = 0;
for (size_t clusterIndex = 0; clusterIndex < clusters.size(); ++clusterIndex) {
const Cluster& cluster = clusters[clusterIndex];
for (const Triangle& triangle : cluster.triangles) {
auto hashes = getTriangleHashes(triangle);
precomputedHashes[triangle] = hashes;
totalTriangles++;
for (const auto& h : hashes) {
hashTable[h].emplace_back(IndexedTriangle{static_cast<int>(clusterIndex), triangle});
}
}
}
}
void clear() {
hashTable.clear();
}
};
struct pair_hash {
template <class T1, class T2>
std::size_t operator () (const std::pair<T1,T2>& p) const {
auto h1 = std::hash<T1>{}(p.first);
auto h2 = std::hash<T2>{}(p.second);
return h1 ^ h2;
}
};
// Checks if two triangles share a vertex
bool shareVertex(const Triangle& a, const Triangle& b) {
return a.vec1 == b.vec1 || a.vec1 == b.vec2 || a.vec1 == b.vec3 ||
a.vec2 == b.vec1 || a.vec2 == b.vec2 || a.vec2 == b.vec3 ||
a.vec3 == b.vec1 || a.vec3 == b.vec2 || a.vec3 == b.vec3;
}
// Depth First Search function
void DFS(int u, std::vector<std::vector<int>>& adjList, std::vector<bool>& visited) {
// std::cout << "[Debug] Visiting vertex: " << u << std::endl;
visited[u] = true;
for (int v : adjList[u]) {
if (!visited[v]) {
DFS(v, adjList, visited);
}
}
}
bool areTrianglesContiguous(const std::vector<Triangle>& triangles) {
int n = triangles.size();
if (n == 0) return true;
std::vector<std::vector<int>> adjList(n);
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (shareVertex(triangles[i], triangles[j])) {
adjList[i].push_back(j);
adjList[j].push_back(i);
}
}
}
std::vector<bool> visited(n, false);
int connectedComponents = 0;
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
// std::cout << "[Debug] Running DFS starting from: " << i << std::endl;
DFS(i, adjList, visited);
connectedComponents++;
}
}
// std::cout << "[Debug] Number of connected components: " << connectedComponents << std::endl;
return connectedComponents == 1;
}
void print_convex_hull(const CGAL::Surface_mesh<Point_3>& P) {
std::cout << "Vertices of the convex hull:" << std::endl;
for (auto v : P.vertices()) {
Point_3 p = P.point(v);
std::cout << "(" << p.x() << ", " << p.y() << ", " << p.z() << ")" << std::endl;
}
std::cout << "Edges of the convex hull:" << std::endl;
for (auto e : P.edges()) {
auto v1 = P.vertex(e, 0);
auto v2 = P.vertex(e, 1);
Point_3 p1 = P.point(v1);
Point_3 p2 = P.point(v2);
std::cout << "[(" << p1.x() << ", " << p1.y() << ", " << p1.z() << ") - ("
<< p2.x() << ", " << p2.y() << ", " << p2.z() << ")]" << std::endl;
}
// std::cout << "Faces of the convex hull:" << std::endl;
// for (auto f : P.faces()) {
// std::cout << "Face: ";
// auto h = P.halfedge(f); // Obtain a halfedge handle from face f
// if(h == CGAL::Surface_mesh<Point_3>::null_halfedge()) {
// std::cerr << "Error: null halfedge encountered." << std::endl;
// continue; // Skip this face if we got a null halfedge
// }
// CGAL::Halfedge_around_face_circulator<CGAL::Surface_mesh<Point_3>> hf_circ(h, P), hf_end;
// do {
// auto v = P.target(*hf_circ);
// Point_3 p = P.point(v);
// std::cout << "(" << p.x() << ", " << p.y() << ", " << p.z() << ") ";
// } while (++hf_circ != hf_end);
// std::cout << std::endl;
// }
}
void print_2d_convex_hull(const Polygon_2& P_2D) {
std::cout << "Vertices of the 2D convex hull:" << std::endl;
for (auto vertex_it = P_2D.vertices_begin(); vertex_it != P_2D.vertices_end(); ++vertex_it) {
CGAL::Point_2<K> p = *vertex_it;
std::cout << "(" << p.x() << ", " << p.y() << ")" << std::endl;
}
std::cout << "Edges of the 2D convex hull:" << std::endl;
for (auto edge_it = P_2D.edges_begin(); edge_it != P_2D.edges_end(); ++edge_it) {
CGAL::Segment_2<K> segment = *edge_it;
CGAL::Point_2<K> source = segment.source();
CGAL::Point_2<K> target = segment.target();
std::cout << "[(" << source.x() << ", " << source.y() << ") - ("
<< target.x() << ", " << target.y() << ")]" << std::endl;
}
}
class Hull {
private:
Delaunay T; // Delaunay triangulation
std::vector<Point_3> points;
Surface_mesh P; // Adjusted to Surface_mesh
mutable double cachedVolume = -1;
mutable bool isVolumeCacheValid = false;
public:
Hull() = default; // Add a default constructor if it's missing
Hull(const std::vector<Triangle>& triangles) {
for (const Triangle& triangle : triangles) {
add(triangle);
}
computeHull();
}
// Copy constructor
Hull(const Hull& other) {
points = other.points;
P = other.P;
}
Hull(const Hull& h1, const Hull& h2) {
points = h1.points;
points.insert(points.end(), h2.points.begin(), h2.points.end());
computeHull();
}
// Add this method to access the private member P
const Surface_mesh& getSurfaceMesh() const {
return P;
}
std::string toString() const {
std::ostringstream oss;
// oss << "Hull with " << points.size() << " points and ";
if (P.is_empty()) {
oss << "no surface mesh constructed.";
} else {
oss << "surface mesh with " << P.number_of_vertices() << " vertices, "
<< P.number_of_halfedges() << " halfedges, and "
<< P.number_of_faces() << " facets.";
}
return oss.str();
}
bool arePointsCoplanar(const std::vector<Point_3>& points) {
if (points.size() < 4) return true; // Less than 4 points are always coplanar
const Point_3& p1 = points[0];
const Point_3& p2 = points[1];
const Point_3& p3 = points[2];
CGAL::Vector_3 normal = CGAL::cross_product(p2 - p1, p3 - p1);
for (size_t i = 3; i < points.size(); ++i) {
CGAL::Vector_3 vec = points[i] - p1;
if (CGAL::scalar_product(normal, vec) != 0) {
return false;
}
}
return true;
}
void add(const Triangle& triangle) {
addPoint(triangle.vec1);
addPoint(triangle.vec2);
addPoint(triangle.vec3);
}
void addPoint(const Vector3D& vec) {
Point_3 point(vec.x, vec.y, vec.z);
// T.insert(point); // Insert point into Delaunay triangulation
points.push_back(point); // Store point in vector
}
void removePoint(const Point_3& point) {
auto vertex_handle = T.nearest_vertex(point);
if (vertex_handle != nullptr && vertex_handle->point() == point) {
T.remove(vertex_handle);
}
}
void computeHull() {
try {
CGAL::convex_hull_3(points.begin(), points.end(), P);
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
exit(1);
}
}
bool arePointsUnique() const {
std::set<Point_3> uniquePoints(points.begin(), points.end());
return uniquePoints.size() == points.size();
}
bool isEmpty() const {
return P.is_empty();
}
bool isClosed() const {
return CGAL::is_closed(P);
}
void updateVolume() const { // add const qualifier here
if (P.is_empty() || !CGAL::is_closed(P)) {
cachedVolume = 0.0;
} else {
cachedVolume = CGAL::Polygon_mesh_processing::volume(P);
}
isVolumeCacheValid = true; // set the cache flag to valid
}
double volume() const {
if (!isVolumeCacheValid) {
updateVolume(); // Automatically update the volume cache if it's invalid
}
return cachedVolume;
}
void invalidateVolumeCache() {
isVolumeCacheValid = false; // set the cache flag to invalid
}
};
// if (T.dimension() != 3) {
// std::vector<Point_2> projected_points;
// for (const auto& point : points) {
// // Project the point to a plane, e.g., the XY-plane
// projected_points.emplace_back(point.x(), point.y());
// }
// Polygon_2 P_2D;
// CGAL::convex_hull_2(projected_points.begin(), projected_points.end(), std::back_inserter(P_2D));
// // print_2d_convex_hull(P_2D);
// }
// else {
// try {
// CGAL::convex_hull_3_to_face_graph(T, P);
// // print_convex_hull(P);
// } catch (const std::exception& e) {
// std::cerr << "Error computing convex hull: " << e.what() << std::endl;
// }
// }
// try {
// CGAL::convex_hull_3(points.begin(), points.end(), P);
// } catch (const std::exception& e) {
// std::cerr << "Exception: " << e.what() << std::endl;
// exit(1);
// }
using ComponentType = std::string;
struct Component {
std::vector<Triangle> triangles;
double weight;
double currentScore; // Add this line to keep track of the current score
ComponentType type; // The type of this component
int depth = 0; // Initialize depth to 0 for new components
Hull convexHull; // Now it's optional and can be empty
int id;
Component() = default; // Explicitly adding a default constructor
void addTriangle(const Triangle& triangle) {
triangles.push_back(triangle);
updateHull();
convexHull.invalidateVolumeCache(); // Invalidate the cached volume
}
// Method to get the last added triangle
Triangle getLastTriangle() const {
if (!triangles.empty()) {
return triangles.back();
}
// Handle the case when there are no triangles.
// You could throw an exception, return a dummy triangle, etc.
throw std::runtime_error("No triangles in the component");
}
void removeTriangle(const Triangle& triangleToRemove) {
auto it = std::remove_if(triangles.begin(), triangles.end(),
[&triangleToRemove](const Triangle& triangle) {
return triangle == triangleToRemove;
});
if (it != triangles.end()) {
triangles.erase(it, triangles.end());
updateHull();
}
}
bool arePointsUnique() const {
return convexHull.arePointsUnique();
}
void updateHull() {
if (!triangles.empty()) {
convexHull = Hull(triangles);
// convexHull.updateVolume();
}
}
bool isValid() const {
bool contiguous = areTrianglesContiguous(triangles);
return contiguous;
}
void updateWeight() {
double Zi = static_cast<double>(triangles.size());
weight = 1.0 / (Zi * Zi);
}
std::string toString() const {
std::ostringstream oss;
for (const auto& triangle : triangles) {
oss << triangle.toString() << ", ";
}
return oss.str();
}
bool overlapsSignificantly(const Component& other);
// Overload the equality operator
bool operator==(const Component& other) const {
// Define your equality logic here. For example:
return this->triangles == other.triangles; // replace this condition with your specific equality check
}
// Overload the inequality operator
bool operator!=(const Component& other) const {
return !(*this == other);
}
bool isEmpty() const {
return triangles.empty();
}
bool isHullClosed() const {
return !convexHull.isEmpty() && CGAL::is_closed(convexHull.getSurfaceMesh());
}
bool containsTriangle(const Triangle& queryTriangle) const {
for (const auto& existingTriangle : triangles) {
if (existingTriangle == queryTriangle) {
return true;
}
}
return false;
}
};
struct ComponentHash {