VCG Library
Loading...
Searching...
No Matches
clean.h
1/****************************************************************************
2* VCGLib o o *
3* Visual and Computer Graphics Library o o *
4* _ O _ *
5* Copyright(C) 2004-2016 \/)\/ *
6* Visual Computing Lab /\/| *
7* ISTI - Italian National Research Council | *
8* \ *
9* All rights reserved. *
10* *
11* This program is free software; you can redistribute it and/or modify *
12* it under the terms of the GNU General Public License as published by *
13* the Free Software Foundation; either version 2 of the License, or *
14* (at your option) any later version. *
15* *
16* This program is distributed in the hope that it will be useful, *
17* but WITHOUT ANY WARRANTY; without even the implied warranty of *
18* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
20* for more details. *
21* *
22****************************************************************************/
23
24#ifndef __VCGLIB_CLEAN
25#define __VCGLIB_CLEAN
26
27#include <map>
28#include <unordered_set>
29
30// VCG headers
31#include <vcg/complex/complex.h>
32#include <vcg/complex/algorithms/closest.h>
33#include <vcg/space/index/grid_static_ptr.h>
34#include <vcg/space/index/spatial_hashing.h>
35#include <vcg/complex/algorithms/update/normal.h>
36#include <vcg/space/triangle3.h>
37#include <vcg/complex/append.h>
38
39namespace vcg {
40namespace tri{
41
42template <class ConnectedEdgeMeshType>
44{
45public:
46 typedef ConnectedEdgeMeshType MeshType;
47 typedef typename MeshType::VertexType VertexType;
48 typedef typename MeshType::VertexPointer VertexPointer;
49 typedef typename MeshType::VertexIterator VertexIterator;
50 typedef typename MeshType::ScalarType ScalarType;
51 typedef typename MeshType::EdgeType EdgeType;
52 typedef typename MeshType::EdgePointer EdgePointer;
53 typedef typename MeshType::EdgeIterator EdgeIterator;
54 typedef typename MeshType::ConstEdgeIterator ConstEdgeIterator;
55 typedef typename MeshType::EdgeContainer EdgeContainer;
56
57public:
58 void operator ++()
59 {
60 EdgePointer ep = se.top();
61 se.pop();
62 for(int i = 0; i < 2; ++i)
63 {
64 edge::VEIterator<EdgeType> vei(ep->V(i));
65 while (!vei.End())
66 {
67 if (!tri::IsMarked(*mp, vei.E()))
68 {
69 tri::Mark(*mp, vei.E());
70 se.push(vei.E());
71 }
72 ++vei;
73 }
74 }
75 }
76
77 void start(MeshType &m, EdgePointer e)
78 {
79 tri::RequirePerEdgeMark(m);
80 mp=&m;
81
82 while(!se.empty())
83 se.pop();
84
85 UnMarkAll(m);
86
87 tri::Mark(m, e);
88 se.push(e);
89 }
90
91 bool completed() {
92 return se.empty();
93 }
94
95 EdgePointer operator *()
96 {
97 return se.top();
98 }
99private:
100 std::stack<EdgePointer> se;
101 MeshType *mp;
102};
103
104template <class ConnectedMeshType>
106{
107public:
108 typedef ConnectedMeshType MeshType;
109 typedef typename MeshType::VertexType VertexType;
110 typedef typename MeshType::VertexPointer VertexPointer;
111 typedef typename MeshType::VertexIterator VertexIterator;
112 typedef typename MeshType::ScalarType ScalarType;
113 typedef typename MeshType::FaceType FaceType;
114 typedef typename MeshType::FacePointer FacePointer;
115 typedef typename MeshType::FaceIterator FaceIterator;
116 typedef typename MeshType::ConstFaceIterator ConstFaceIterator;
117 typedef typename MeshType::FaceContainer FaceContainer;
118
119public:
120 void operator ++()
121 {
122 FacePointer fpt=sf.top();
123 sf.pop();
124 for(int j=0; j<fpt->VN(); ++j)
125 if( !face::IsBorder(*fpt,j) )
126 {
127 FacePointer l=fpt->FFp(j);
128 if( !tri::IsMarked(*mp,l) )
129 {
130 tri::Mark(*mp,l);
131 sf.push(l);
132 }
133 }
134 }
135
136 void start(MeshType &m, FacePointer p)
137 {
138 tri::RequirePerFaceMark(m);
139 mp=&m;
140 while(!sf.empty()) sf.pop();
141 UnMarkAll(m);
142 tri::Mark(m,p);
143 sf.push(p);
144 }
145
146 bool completed() {
147 return sf.empty();
148 }
149
150 FacePointer operator *()
151 {
152 return sf.top();
153 }
154private:
155 std::stack<FacePointer> sf;
156 MeshType *mp;
157};
158
159
161
164template <class CleanMeshType>
165class Clean
166{
167
168public:
169 typedef CleanMeshType MeshType;
170 typedef typename MeshType::VertexType VertexType;
171 typedef typename MeshType::VertexPointer VertexPointer;
172 typedef typename MeshType::ConstVertexPointer ConstVertexPointer;
173 typedef typename MeshType::VertexIterator VertexIterator;
174 typedef typename MeshType::ConstVertexIterator ConstVertexIterator;
175 typedef typename MeshType::EdgeIterator EdgeIterator;
176 typedef typename MeshType::EdgePointer EdgePointer;
177 typedef typename MeshType::CoordType CoordType;
178 typedef typename MeshType::ScalarType ScalarType;
179 typedef typename MeshType::FaceType FaceType;
180 typedef typename MeshType::FacePointer FacePointer;
181 typedef typename MeshType::FaceIterator FaceIterator;
182 typedef typename MeshType::ConstFaceIterator ConstFaceIterator;
183 typedef typename MeshType::FaceContainer FaceContainer;
184 typedef typename MeshType::TetraType TetraType;
185 typedef typename MeshType::TetraPointer TetraPointer;
186 typedef typename MeshType::TetraIterator TetraIterator;
187 typedef typename MeshType::ConstTetraIterator ConstTetraIterator;
188
189 typedef typename vcg::Box3<ScalarType> Box3Type;
190
191 typedef GridStaticPtr<FaceType, ScalarType > TriMeshGrid;
192
193 /* classe di confronto per l'algoritmo di eliminazione vertici duplicati*/
195 public:
196 inline bool operator()(VertexPointer const &a, VertexPointer const &b)
197 {
198 return ((*a).cP() == (*b).cP()) ? (a<b): ((*a).cP() < (*b).cP());
199 }
200 };
201
202
207 static int RemoveDuplicateVertex( MeshType & m, bool RemoveDegenerateFlag=true) // V1.0
208 {
209 if(m.vert.size()==0 || m.vn==0) return 0;
210
211 // Where each merged vertex went, indexed by vertex; a vertex that stays is left null.
212 // This used to be a std::map holding every vertex, which on a triangle soup -- an STL
213 // file, where every vertex has twins -- made the merge several times slower than
214 // reading the file: 2.6 s against 0.6 s on a 2M-face STL. The result is unchanged.
215 std::vector<VertexPointer> mp(m.vert.size(), nullptr);
216 size_t i,j;
217 VertexIterator vi;
218 int deleted=0;
219 int k=0;
220 size_t num_vert = m.vert.size();
221 std::vector<VertexPointer> perm(num_vert);
222 for(vi=m.vert.begin(); vi!=m.vert.end(); ++vi, ++k)
223 perm[k] = &(*vi);
224
226
227 std::sort(perm.begin(),perm.end(),c_obj);
228
229 j = 0;
230 i = j;
231 ++i;
232 for(;i!=num_vert;)
233 {
234 if( (! (*perm[i]).IsD()) &&
235 (! (*perm[j]).IsD()) &&
236 (*perm[i]).P() == (*perm[j]).cP() )
237 {
238 VertexPointer t = perm[i];
239 mp[tri::Index(m, t)] = perm[j];
240 ++i;
242 deleted++;
243 }
244 else
245 {
246 j = i;
247 ++i;
248 }
249 }
250
251 for(FaceIterator fi = m.face.begin(); fi!=m.face.end(); ++fi)
252 if( !(*fi).IsD() )
253 for(k = 0; k < (*fi).VN(); ++k)
254 if( VertexPointer to = mp[tri::Index(m, (*fi).V(k))] )
255 (*fi).V(k) = to;
256
257 for(EdgeIterator ei = m.edge.begin(); ei!=m.edge.end(); ++ei)
258 if( !(*ei).IsD() )
259 for(k = 0; k < 2; ++k)
260 if( VertexPointer to = mp[tri::Index(m, (*ei).V(k))] )
261 (*ei).V(k) = to;
262
263 for (TetraIterator ti = m.tetra.begin(); ti != m.tetra.end(); ++ti)
264 if (!(*ti).IsD())
265 for (k = 0; k < 4; ++k)
266 if (VertexPointer to = mp[tri::Index(m, (*ti).V(k))])
267 (*ti).V(k) = to;
268
269 if(RemoveDegenerateFlag) RemoveDegenerateFace(m);
270 if(RemoveDegenerateFlag && m.en>0) {
271 RemoveDegenerateEdge(m);
273 }
274 return deleted;
275 }
276
278 {
279 public:
280 SortedPair() {}
281 SortedPair(unsigned int v0, unsigned int v1, EdgePointer _fp)
282 {
283 v[0]=v0;v[1]=v1;
284 fp=_fp;
285 if(v[0]>v[1]) std::swap(v[0],v[1]);
286 }
287 bool operator < (const SortedPair &p) const
288 {
289 return (v[1]!=p.v[1])?(v[1]<p.v[1]):
290 (v[0]<p.v[0]); }
291
292 bool operator == (const SortedPair &s) const
293 {
294 if( (v[0]==s.v[0]) && (v[1]==s.v[1]) ) return true;
295 return false;
296 }
297
298 unsigned int v[2];
299 EdgePointer fp;
300 };
302 {
303 public:
304 SortedTriple() {}
305 SortedTriple(unsigned int v0, unsigned int v1, unsigned int v2,FacePointer _fp)
306 {
307 v[0]=v0;v[1]=v1;v[2]=v2;
308 fp=_fp;
309 std::sort(v,v+3);
310 }
311 bool operator < (const SortedTriple &p) const
312 {
313 return (v[2]!=p.v[2])?(v[2]<p.v[2]):
314 (v[1]!=p.v[1])?(v[1]<p.v[1]):
315 (v[0]<p.v[0]); }
316
317 bool operator == (const SortedTriple &s) const
318 {
319 if( (v[0]==s.v[0]) && (v[1]==s.v[1]) && (v[2]==s.v[2]) ) return true;
320 return false;
321 }
322
323 unsigned int v[3];
324 FacePointer fp;
325 };
326
327
335 static int RemoveDuplicateFace( MeshType & m, bool DeleteFacesFlag=true) // V1.0
336 {
337 std::vector<SortedTriple> fvec;
338 for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
339 if(!(*fi).IsD())
340 {
341 fvec.push_back(SortedTriple( tri::Index(m,(*fi).V(0)),
342 tri::Index(m,(*fi).V(1)),
343 tri::Index(m,(*fi).V(2)),
344 &*fi));
345 }
346 std::sort(fvec.begin(),fvec.end());
347 int total=0;
348 for(int i=0;i<int(fvec.size())-1;++i)
349 {
350 if(fvec[i]==fvec[i+1])
351 {
352 total++;
353 if(DeleteFacesFlag)
354 tri::Allocator<MeshType>::DeleteFace(m, *(fvec[i].fp) );
355 }
356 }
357 return total;
358 }
359
365 static int RemoveDuplicateEdge( MeshType & m) // V1.0
366 {
367 if (m.en==0) return 0;
368 std::vector<SortedPair> eVec;
369 for(EdgeIterator ei=m.edge.begin();ei!=m.edge.end();++ei)
370 if(!(*ei).IsD())
371 {
372 eVec.push_back(SortedPair( tri::Index(m,(*ei).V(0)), tri::Index(m,(*ei).V(1)), &*ei));
373 }
374 std::sort(eVec.begin(),eVec.end());
375 int total=0;
376 for(int i=0;i<int(eVec.size())-1;++i)
377 {
378 if(eVec[i]==eVec[i+1])
379 {
380 total++;
381 tri::Allocator<MeshType>::DeleteEdge(m, *(eVec[i].fp) );
382 }
383 }
384 return total;
385 }
386
387 static int CountUnreferencedVertex( MeshType& m)
388 {
389 return RemoveUnreferencedVertex(m,false);
390 }
391
392
398 static int RemoveUnreferencedVertex( MeshType& m, bool DeleteVertexFlag=true) // V1.0
399 {
400 tri::RequirePerVertexFlags(m);
401
402 std::vector<bool> referredVec(m.vert.size(),false);
403 int deleted = 0;
404
405 for(auto fi = m.face.begin(); fi != m.face.end(); ++fi)
406 if( !(*fi).IsD() )
407 for(auto j=0; j < (*fi).VN(); ++j)
408 referredVec[tri::Index(m, (*fi).V(j))]=true;
409
410 for(auto ei=m.edge.begin();ei!=m.edge.end();++ei)
411 if( !(*ei).IsD() ){
412 referredVec[tri::Index(m, (*ei).V(0))]=true;
413 referredVec[tri::Index(m, (*ei).V(1))]=true;
414 }
415
416 for(auto ti=m.tetra.begin(); ti!=m.tetra.end();++ti)
417 if( !(*ti).IsD() ){
418 referredVec[tri::Index(m, (*ti).V(0))]=true;
419 referredVec[tri::Index(m, (*ti).V(1))]=true;
420 referredVec[tri::Index(m, (*ti).V(2))]=true;
421 referredVec[tri::Index(m, (*ti).V(3))]=true;
422 }
423
424
425 if(!DeleteVertexFlag)
426 return std::count(referredVec.begin(),referredVec.end(),false);
427
428 for(auto vi=m.vert.begin();vi!=m.vert.end();++vi)
429 if( (!(*vi).IsD()) && (!referredVec[tri::Index(m,*vi)]) )
430 {
432 ++deleted;
433 }
434 return deleted;
435 }
436
441 static int RemoveDegenerateVertex(MeshType& m, bool DeleteVertexFlag=true)
442 {
443 VertexIterator vi;
444 int count_vd = 0;
445
446 for(vi=m.vert.begin(); vi!=m.vert.end();++vi)
447 if(math::IsNAN( (*vi).P()[0]) ||
448 math::IsNAN( (*vi).P()[1]) ||
449 math::IsNAN( (*vi).P()[2]) )
450 {
451 count_vd++;
452 if (DeleteVertexFlag)
454 }
455
456 FaceIterator fi;
457 int count_fd = 0;
458
459 for(fi=m.face.begin(); fi!=m.face.end();++fi)
460 if(!(*fi).IsD())
461 if( (*fi).V(0)->IsD() ||
462 (*fi).V(1)->IsD() ||
463 (*fi).V(2)->IsD() )
464 {
465 count_fd++;
466 if (DeleteVertexFlag)
468 }
469 (void)count_fd;
470 return count_vd;
471 }
472
481 static int RemoveDegenerateFace(MeshType& m, bool DeleteFacesFlag=true)
482 {
483 int count_fd = 0;
484
485 for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi)
486 if(!(*fi).IsD())
487 {
488 if((*fi).V(0) == (*fi).V(1) ||
489 (*fi).V(0) == (*fi).V(2) ||
490 (*fi).V(1) == (*fi).V(2) )
491 {
492 count_fd++;
493 if (DeleteFacesFlag)
495 }
496 }
497 return count_fd;
498 }
499
500 static int RemoveDegenerateEdge(MeshType& m, bool DeleteEdgesFlag=true)
501 {
502 int count_ed = 0;
503
504 for(EdgeIterator ei=m.edge.begin(); ei!=m.edge.end();++ei)
505 if(!(*ei).IsD())
506 {
507 if((*ei).V(0) == (*ei).V(1) )
508 {
509 count_ed++;
510 if (DeleteEdgesFlag)
512 }
513 }
514 return count_ed;
515 }
516
517 static int RemoveNonManifoldVertex(MeshType& m)
518 {
521 int count_removed = 0;
522 for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi)
523 if(!(*fi).IsD() && (*fi).IsS())
525 for(VertexIterator vi=m.vert.begin(); vi!=m.vert.end();++vi)
526 if(!(*vi).IsD() && (*vi).IsS()) {
527 ++count_removed;
529 }
530 return count_removed;
531 }
532
533
534 static int SplitSelectedVertexOnEdgeMesh(MeshType& m)
535 {
536 tri::RequireCompactness(m);
537
538 // count selected vertices references
539 std::unordered_map<size_t,size_t> refCount; // selected vertex index -> reference count
540 size_t countSplit = 0;
541 for (size_t i=0; i<m.edge.size(); ++i)
542 {
543 for (int j=0; j<2; ++j)
544 {
545 const VertexPointer vp = m.edge[i].V(j);
546 if (vp->IsS())
547 {
548 const size_t refs = ++refCount[Index(m, m.edge[i].V(j))];
549 if (refs > 1) {
550 countSplit++;
551 }
552 }
553 }
554 }
555 // actual split
556 if (countSplit > 0)
557 {
558 auto newVertIt = tri::Allocator<MeshType>::AddVertices(m, countSplit);
559 for (size_t i=0; i<m.edge.size(); ++i)
560 {
561 for (int j=0; j<2; ++j)
562 {
563 const VertexPointer vp = m.edge[i].V(j);
564 const size_t vIdx = Index(m, vp);
565 if (vp->IsS())
566 {
567 if (--refCount[vIdx] > 0)
568 {
569 newVertIt->ImportData(*vp);
570 m.edge[i].V(j) = &*(newVertIt++);
571 }
572 }
573 }
574 }
575 }
576 return int(countSplit);
577 }
578
579
580 static void SelectNonManifoldVertexOnEdgeMesh(MeshType &m)
581 {
582 tri::RequireCompactness(m);
584 std::vector<int> cnt(m.vn,0);
585
586 for(size_t i=0;i<m.edge.size();++i)
587 {
588 cnt[tri::Index(m,m.edge[i].V(0))]++;
589 cnt[tri::Index(m,m.edge[i].V(1))]++;
590 }
591 for(size_t i=0;i<m.vert.size();++i)
592 if(cnt[i]>2) m.vert[i].SetS();
593 }
594
597 static void SelectCreaseVertexOnEdgeMeshEE(MeshType &m, ScalarType AngleRadThr)
598 {
599 tri::RequireCompactness(m);
600 tri::RequireEEAdjacency(m);
604 for(size_t i=0;i<m.edge.size();++i)
605 {
606 for(int j=0;j<2;++j)
607 {
608 if(! m.edge[i].V(j)->IsV())
609 {
610 const CoordType &centerV = m.edge[i].V(j)->cP();
611 m.edge[i].V(j)->SetV();
612 std::vector<VertexPointer> VVStarVec;
613 edge::VVStarEE(&(m.edge[i]),j,VVStarVec);
614 if(VVStarVec.size()==2)
615 {
616 CoordType v0 = centerV - VVStarVec[0]->P();
617 CoordType v1 = VVStarVec[1]->P() - centerV;
618 if(vcg::Angle(v0,v1) > AngleRadThr)
619 m.edge[i].V(j)->SetS();
620 }
621 }
622 }
623 }
624 }
627 static void SelectCreaseVertexOnEdgeMeshVE(MeshType &m, ScalarType AngleRadThr)
628 {
629 tri::RequireCompactness(m);
630 tri::RequireVEAdjacency(m);
633 for(size_t i=0;i<m.vert.size();++i)
634 {
635 std::vector<VertexPointer> VVStarVec;
636 edge::VVStarVE(&(m.vert[i]),VVStarVec);
637 if(VVStarVec.size()==2)
638 {
639 CoordType v0 = m.vert[i].P() - VVStarVec[0]->P();
640 CoordType v1 = m.vert[i].P() - VVStarVec[1]->P();
641 float angle = M_PI-vcg::Angle(v0,v1);
642 if(angle > AngleRadThr) m.vert[i].SetS();
643 }
644 }
645 }
646
648
649 // Given a mesh with FF adjacency
650 // it search for non manifold vertices and duplicate them.
651 // Duplicated vertices are moved apart according to the move threshold param.
652 // that is a percentage of the average vector from the non manifold vertex to the barycenter of the incident faces.
653
654 static int SplitNonManifoldVertex(MeshType& m, ScalarType moveThreshold)
655 {
656 RequireFFAdjacency(m);
657 typedef std::pair<FacePointer,int> FaceInt; // a face and the index of the vertex that we have to change
658 //
659 std::vector<std::pair<VertexPointer, std::vector<FaceInt> > >ToSplitVec;
660
662 ss.push();
665 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD())
666 {
667 for (int i=0; i<fi->VN(); i++)
668 if ((*fi).V(i)->IsS() && !(*fi).V(i)->IsV())
669 {
670 (*fi).V(i)->SetV();
671 face::Pos<FaceType> startPos(&*fi,i);
672 face::Pos<FaceType> curPos = startPos;
673 std::set<FaceInt> faceSet;
674 do
675 {
676 faceSet.insert(std::make_pair(curPos.F(),curPos.VInd()));
677 curPos.FlipE();
678 curPos.NextF();
679 } while (curPos != startPos);
680
681 ToSplitVec.push_back(make_pair((*fi).V(i),std::vector<FaceInt>()));
682
683 typename std::set<FaceInt>::const_iterator iii;
684
685 for(iii=faceSet.begin();iii!=faceSet.end();++iii)
686 ToSplitVec.back().second.push_back(*iii);
687 }
688 }
689 ss.pop();
690 // Second step actually add new vertices and split them.
691 typename tri::Allocator<MeshType>::template PointerUpdater<VertexPointer> pu;
692 VertexIterator firstVp = tri::Allocator<MeshType>::AddVertices(m,ToSplitVec.size(),pu);
693 for(size_t i =0;i<ToSplitVec.size();++i)
694 {
695 // qDebug("Splitting Vertex %i",ToSplitVec[i].first-&*m.vert.begin());
696 VertexPointer np=ToSplitVec[i].first;
697 pu.Update(np);
698 firstVp->ImportData(*np);
699 // loop on the face to be changed, and also compute the movement vector;
700 CoordType delta(0,0,0);
701 for(size_t j=0;j<ToSplitVec[i].second.size();++j)
702 {
703 FaceInt ff=ToSplitVec[i].second[j];
704 ff.first->V(ff.second)=&*firstVp;
705 delta+=Barycenter(*(ff.first))-np->cP();
706 }
707 delta /= ToSplitVec[i].second.size();
708 firstVp->P() = firstVp->P() + delta * moveThreshold;
709 firstVp++;
710 }
711
712 return int(ToSplitVec.size());
713 }
714
725 static size_t SplitManifoldComponents(MeshType &m, const ScalarType moveThreshold = 0)
726 {
727 RequireFFAdjacency(m);
728
729 // The component of every face, grown across manifold edges only.
730 std::vector<int> component(m.face.size(), -1);
731 int componentCount = 0;
732 for (size_t seed = 0; seed < m.face.size(); ++seed)
733 {
734 if (m.face[seed].IsD() || component[seed] >= 0) continue;
735 std::vector<size_t> stack(1, seed);
736 component[seed] = componentCount;
737 while (!stack.empty())
738 {
739 FaceType &f = m.face[stack.back()];
740 stack.pop_back();
741 for (int i = 0; i < f.VN(); ++i)
742 {
743 const size_t adj = Index(m, f.FFp(i));
744 if (face::IsManifold(f, i) && component[adj] < 0)
745 {
746 component[adj] = componentCount;
747 stack.push_back(adj);
748 }
749 }
750 }
751 ++componentCount;
752 }
753
754 // A copy of a vertex for each component that uses it after the first one.
755 std::vector<int> owner(m.vert.size(), -1);
756 std::map<std::pair<size_t, int>, size_t> copyOf; // (vertex, component) -> its copy
757 std::vector<size_t> source; // the vertex each copy duplicates
758 std::vector<bool> split(m.vert.size(), false);
759 for (size_t fi = 0; fi < m.face.size(); ++fi)
760 {
761 if (m.face[fi].IsD()) continue;
762 for (int i = 0; i < m.face[fi].VN(); ++i)
763 {
764 const size_t v = Index(m, m.face[fi].V(i));
765 if (owner[v] < 0) owner[v] = component[fi];
766 else if (owner[v] != component[fi]
767 && copyOf.emplace(std::make_pair(v, component[fi]), m.vert.size() + source.size()).second)
768 {
769 source.push_back(v);
770 split[v] = true;
771 }
772 }
773 }
774 if (source.empty()) return size_t(componentCount);
775
776 const size_t firstCopy = m.vert.size();
777 Allocator<MeshType>::AddVertices(m, source.size());
778 split.resize(m.vert.size(), true);
779 for (size_t k = 0; k < source.size(); ++k)
780 {
781 m.vert[firstCopy + k].ImportData(m.vert[source[k]]);
782 for (const auto &attr : m.vert_attr)
783 attr._handle->CopyValue(firstCopy + k, source[k], attr._handle);
784 }
785 for (size_t fi = 0; fi < m.face.size(); ++fi)
786 {
787 if (m.face[fi].IsD()) continue;
788 for (int i = 0; i < m.face[fi].VN(); ++i)
789 {
790 const auto copy = copyOf.find(std::make_pair(size_t(Index(m, m.face[fi].V(i))), component[fi]));
791 if (copy != copyOf.end()) m.face[fi].V(i) = &m.vert[copy->second];
792 }
793 }
794
795 if (moveThreshold != 0)
796 {
797 std::vector<CoordType> delta(m.vert.size(), CoordType(0, 0, 0));
798 std::vector<int> count(m.vert.size(), 0);
799 for (FaceType &f : m.face)
800 if (!f.IsD())
801 for (int i = 0; i < f.VN(); ++i)
802 {
803 const size_t v = Index(m, f.V(i));
804 delta[v] += Barycenter(f) - f.V(i)->cP();
805 ++count[v];
806 }
807 for (size_t v = 0; v < m.vert.size(); ++v)
808 if (split[v] && count[v] > 0)
809 m.vert[v].P() += delta[v] / ScalarType(count[v]) * moveThreshold;
810 }
811 return size_t(componentCount);
812 }
813
814
815 // Auxiliary function for sorting the non manifold faces according to their area. Used in RemoveNonManifoldFace
817 bool operator ()(FacePointer const& f1, FacePointer const& f2) const {
818 return DoubleArea(*f1) < DoubleArea(*f2);
819 }
820 };
821
823 static int RemoveNonManifoldFace(MeshType& m, bool DeleteFacesFlag=true)
824 {
825 FaceIterator fi;
826 int count_fd = 0;
827 std::vector<FacePointer> ToDelVec;
828
829 for(fi=m.face.begin(); fi!=m.face.end();++fi)
830 if (!fi->IsD())
831 {
832 if ((!IsManifold(*fi,0))||
833 (!IsManifold(*fi,1))||
834 (!IsManifold(*fi,2)))
835 ToDelVec.push_back(&*fi);
836 }
837
838 if (!DeleteFacesFlag)
839 return ToDelVec.size();
840
841 std::sort(ToDelVec.begin(),ToDelVec.end(),CompareAreaFP());
842
843 for(size_t i=0;i<ToDelVec.size();++i)
844 {
845 if(!ToDelVec[i]->IsD())
846 {
847 FaceType &ff= *ToDelVec[i];
848 if ((!IsManifold(ff,0))||
849 (!IsManifold(ff,1))||
850 (!IsManifold(ff,2)))
851 {
852 for(int j=0;j<3;++j)
853 if(!face::IsBorder<FaceType>(ff,j))
854 vcg::face::FFDetach<FaceType>(ff,j);
855
857 count_fd++;
858 }
859 }
860 }
861 return count_fd;
862 }
863
864 /* Remove the faces that are out of a given range of area */
865 static int RemoveFaceOutOfRangeArea(MeshType& m, ScalarType MinAreaThr=0, ScalarType MaxAreaThr=(std::numeric_limits<ScalarType>::max)(), bool OnlyOnSelected=false, bool DeleteFacesFlag=true)
866 {
867 int count_fd = 0;
868 MinAreaThr*=2;
869 MaxAreaThr*=2;
870 for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi){
871 if(!(*fi).IsD())
872 if(!OnlyOnSelected || (*fi).IsS())
873 {
874 const ScalarType doubleArea=DoubleArea<FaceType>(*fi);
875 if((doubleArea<=MinAreaThr) || (doubleArea>=MaxAreaThr) )
876 {
877 if (DeleteFacesFlag)
879 count_fd++;
880 }
881 }
882 }
883 return count_fd;
884 }
885
886 static int RemoveZeroAreaFace(MeshType& m, bool DeleteFacesFlag=true) { return RemoveFaceOutOfRangeArea(m,0, (std::numeric_limits<ScalarType>::max)(), false, DeleteFacesFlag); }
887
888
889
893 static bool IsBitQuadOnly(const MeshType &m)
894 {
895 typedef typename MeshType::FaceType F;
896 tri::RequirePerFaceFlags(m);
897 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) {
898 unsigned int tmp = fi->Flags()&(F::FAUX0|F::FAUX1|F::FAUX2);
899 if ( tmp != F::FAUX0 && tmp != F::FAUX1 && tmp != F::FAUX2) return false;
900 }
901 return true;
902 }
903
904
905 static bool IsFaceFauxConsistent(MeshType &m)
906 {
907 RequirePerFaceFlags(m);
908 RequireFFAdjacency(m);
909 for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD())
910 {
911 for(int z=0;z<(*fi).VN();++z)
912 {
913 FacePointer fp = fi->FFp(z);
914 int zp = fi->FFi(z);
915 if(fi->IsF(z) != fp->IsF(zp)) return false;
916 }
917 }
918 return true;
919 }
920
924 static bool IsBitTriOnly(const MeshType &m)
925 {
926 tri::RequirePerFaceFlags(m);
927 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) {
928 if ( !fi->IsD() && fi->IsAnyF() ) return false;
929 }
930 return true;
931 }
932
933 static bool IsBitPolygonal(const MeshType &m){
934 return !IsBitTriOnly(m);
935 }
936
941 static bool IsBitTriQuadOnly(const MeshType &m)
942 {
943 tri::RequirePerFaceFlags(m);
944 typedef typename MeshType::FaceType F;
945 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) {
946 unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2);
947 if ( tmp!=F::FAUX0 && tmp!=F::FAUX1 && tmp!=F::FAUX2 && tmp!=0 ) return false;
948 }
949 return true;
950 }
951
956 static int CountBitQuads(const MeshType &m)
957 {
958 tri::RequirePerFaceFlags(m);
959 typedef typename MeshType::FaceType F;
960 int count=0;
961 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) {
962 unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2);
963 if ( tmp==F::FAUX0 || tmp==F::FAUX1 || tmp==F::FAUX2) count++;
964 }
965 return count / 2;
966 }
967
971 static int CountBitTris(const MeshType &m)
972 {
973 tri::RequirePerFaceFlags(m);
974 int count=0;
975 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) {
976 if (!(fi->IsAnyF())) count++;
977 }
978 return count;
979 }
980
985 static int CountBitPolygons(const MeshType &m)
986 {
987 tri::RequirePerFaceFlags(m);
988 int count = 0;
989 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) {
990 if (fi->IsF(0)) count++;
991 if (fi->IsF(1)) count++;
992 if (fi->IsF(2)) count++;
993 }
994 return m.fn - count/2;
995 }
996
1008 static int CountBitLargePolygons(const MeshType &m)
1009 {
1010 //note - using unordered_map to set visited vertices because
1011 //the mesh is const (before, the function used vertex flags...).
1012 //could be used std::vector<bool> if the vertex has the Index()
1013 //member function...
1014 std::unordered_map<ConstVertexPointer, bool> vertVisited;
1015 for (ConstVertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi)
1016 if (!vi->IsD()) vertVisited[&(*vi)] = true;
1017
1018 // First loop Clear all referenced vertices
1019 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1020 if (!fi->IsD())
1021 for(int i=0;i<3;++i){
1022 vertVisited[fi->V(i)] = false;
1023 }
1024
1025
1026 // Second Loop, count (twice) faux edges and mark all vertices touched by non faux edges
1027 // (e.g vertexes on the boundary of a polygon)
1028 int countE = 0;
1029 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1030 if (!fi->IsD()) {
1031 for(int i=0;i<3;++i)
1032 {
1033 if (fi->IsF(i))
1034 countE++;
1035 else
1036 {
1037 vertVisited[fi->V0(i)] = true;
1038 vertVisited[fi->V1(i)] = true;
1039 }
1040 }
1041 }
1042 // Third Loop, count the number of referenced vertexes that are completely surrounded by faux edges.
1043
1044 int countV = 0;
1045 for (ConstVertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi)
1046 if (!vi->IsD() && !(vertVisited[&(*vi)])) countV++;
1047
1048 return m.fn - countE/2 + countV ;
1049 }
1050
1051
1059 static bool HasConsistentPerFaceFauxFlag(const MeshType &m)
1060 {
1061 RequireFFAdjacency(m);
1062 RequirePerFaceFlags(m);
1063
1064 for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1065 if(!(*fi).IsD())
1066 for (int k=0; k<3; k++)
1067 if( ( fi->IsF(k) != fi->cFFp(k)->IsF(fi->cFFi(k)) ) ||
1068 ( fi->IsF(k) && face::IsBorder(*fi,k)) )
1069 {
1070 return false;
1071 }
1072 return true;
1073 }
1074
1079 static int CountNonManifoldEdgeEE( MeshType & m, bool SelectFlag=false)
1080 {
1081 MeshAssert<MeshType>::OnlyEdgeMesh(m);
1082 RequireEEAdjacency(m);
1084
1086
1087 int nonManifoldCnt=0;
1088 SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0);
1089
1090 // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter.
1091 EdgeIterator ei;
1092 for (ei = m.edge.begin(); ei != m.edge.end(); ++ei) if (!ei->IsD())
1093 {
1094 TD[(*ei).V(0)]++;
1095 TD[(*ei).V(1)]++;
1096 }
1097
1099 // Second Loop, Check that each vertex have been seen 1 or 2 times.
1100 for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD())
1101 {
1102 if( TD[vi] >2 )
1103 {
1104 if(SelectFlag) (*vi).SetS();
1105 nonManifoldCnt++;
1106 }
1107 }
1108 return nonManifoldCnt;
1109 }
1110
1117 static int CountNonManifoldEdgeFF( MeshType & m, bool SelectFlag=false)
1118 {
1119 RequireFFAdjacency(m);
1120 int nmfBit[3];
1121 nmfBit[0]= FaceType::NewBitFlag();
1122 nmfBit[1]= FaceType::NewBitFlag();
1123 nmfBit[2]= FaceType::NewBitFlag();
1124
1125
1126 UpdateFlags<MeshType>::FaceClear(m,nmfBit[0]+nmfBit[1]+nmfBit[2]);
1127
1128 if(SelectFlag){
1131 }
1132
1133 int edgeCnt = 0;
1134 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1135 {
1136 if (!fi->IsD())
1137 {
1138 for(int i=0;i<3;++i)
1139 if(!IsManifold(*fi,i))
1140 {
1141 if(!(*fi).IsUserBit(nmfBit[i]))
1142 {
1143 ++edgeCnt;
1144 if(SelectFlag)
1145 {
1146 (*fi).V0(i)->SetS();
1147 (*fi).V1(i)->SetS();
1148 }
1149 // follow the ring of faces incident on edge i;
1150 face::Pos<FaceType> nmf(&*fi,i);
1151 do
1152 {
1153 if(SelectFlag) nmf.F()->SetS();
1154 nmf.F()->SetUserBit(nmfBit[nmf.E()]);
1155 nmf.NextF();
1156 }
1157 while(nmf.f != &*fi);
1158 }
1159 }
1160 }
1161 }
1162
1163 FaceType::DeleteBitFlag(nmfBit[2]);
1164 FaceType::DeleteBitFlag(nmfBit[1]);
1165 FaceType::DeleteBitFlag(nmfBit[0]);
1166 return edgeCnt;
1167 }
1168
1173 static int CountNonManifoldVertexFF( MeshType & m, bool selectVert = true, bool clearSelection = true)
1174 {
1175 RequireFFAdjacency(m);
1176 if(selectVert && clearSelection) UpdateSelection<MeshType>::VertexClear(m);
1177
1178 int nonManifoldCnt=0;
1179 SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0);
1180
1181 // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter.
1182 FaceIterator fi;
1183 for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD())
1184 {
1185 for (int k=0; k<fi->VN(); k++)
1186 {
1187 TD[(*fi).V(k)]++;
1188 }
1189 }
1190
1192 // Second Loop.
1193 // mark out of the game the vertexes that are incident on non manifold edges.
1194 for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD())
1195 {
1196 for(int i=0; i<fi->VN(); ++i)
1197 if (!IsManifold(*fi,i))
1198 {
1199 (*fi).V0(i)->SetV();
1200 (*fi).V1(i)->SetV();
1201 }
1202 }
1203 // Third Loop, for safe vertexes, check that the number of faces that you can reach starting
1204 // from it and using FF is the same of the previously counted.
1205 for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD())
1206 {
1207 for(int i=0; i<fi->VN(); i++) if (!(*fi).V(i)->IsV())
1208 {
1209 (*fi).V(i)->SetV();
1210 face::Pos<FaceType> pos(&(*fi),i);
1211
1212 int starSizeFF = pos.NumberOfIncidentFaces();
1213
1214 if (starSizeFF != TD[(*fi).V(i)])
1215 {
1216 if (selectVert)
1217 (*fi).V(i)->SetS();
1218 nonManifoldCnt++;
1219 }
1220 }
1221 }
1222 return nonManifoldCnt;
1223 }
1231 static bool IsWaterTight(MeshType & m)
1232 {
1233 int edgeNum=0,edgeBorderNum=0,edgeNonManifNum=0;
1234 CountEdgeNum(m, edgeNum, edgeBorderNum,edgeNonManifNum);
1235 return (edgeBorderNum==0) && (edgeNonManifNum==0);
1236 }
1237
1238 static void CountEdgeNum( MeshType & m, int &total_e, int &boundary_e, int &non_manif_e )
1239 {
1240 std::vector< typename tri::UpdateTopology<MeshType>::PEdge > edgeVec;
1242 sort(edgeVec.begin(), edgeVec.end()); // Lo ordino per vertici
1243 total_e=0;
1244 boundary_e=0;
1245 non_manif_e=0;
1246
1247 size_t f_on_cur_edge =1;
1248 for(size_t i=0;i<edgeVec.size();++i)
1249 {
1250 if(( (i+1) == edgeVec.size()) || !(edgeVec[i] == edgeVec[i+1]))
1251 {
1252 ++total_e;
1253 if(f_on_cur_edge==1)
1254 ++boundary_e;
1255 if(f_on_cur_edge>2)
1256 ++non_manif_e;
1257 f_on_cur_edge=1;
1258 }
1259 else
1260 {
1261 ++f_on_cur_edge;
1262 }
1263 } // end for
1264 }
1265
1266
1267
1273 static int CountHoles( MeshType & m)
1274 {
1275 RequireFFAdjacency(m);
1276 MeshAssert<MeshType>::FFAdjacencyIsInitialized(m);
1277 // The walk below turns around each boundary vertex through the faces on it
1278 // (Pos::NextB) until it reaches the next border edge. That only comes round when the
1279 // faces around the vertex form a fan: a non-manifold edge on the vertex closes the
1280 // rotation on itself without ever reaching a border, and the walk would not end.
1281 // Only the vertices of border edges are turned around, so mark those on a
1282 // non-manifold edge and give up if a border edge has one.
1284 for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!fi->IsD())
1285 for(int j=0;j<3;++j)
1286 if(!face::IsManifold(*fi,j))
1287 {
1288 fi->V(j)->SetV();
1289 fi->V1(j)->SetV();
1290 }
1291 bool wellDefined=true;
1292 for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!fi->IsD())
1293 for(int j=0;j<3;++j)
1294 if(face::IsBorder(*fi,j) && (fi->V(j)->IsV() || fi->V1(j)->IsV()))
1295 wellDefined=false;
1297 if(!wellDefined)
1298 return -1;
1300 int loopNum=0;
1301 for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!fi->IsD())
1302 {
1303 for(int j=0;j<3;++j)
1304 {
1305 if(!fi->IsV() && face::IsBorder(*fi,j))
1306 {
1307 face::Pos<FaceType> startPos(&*fi,j);
1308 face::Pos<FaceType> curPos=startPos;
1309 do
1310 {
1311 curPos.NextB();
1312 curPos.F()->SetV();
1313 }
1314 while(curPos!=startPos);
1315 ++loopNum;
1316 }
1317 }
1318 }
1319 return loopNum;
1320 }
1321
1322 /*
1323 Compute the set of connected components of a given mesh
1324 it fills a vector of pair < int , faceptr > with, for each connecteed component its size and a represnant
1325 If faceComponent is not null it is also filled, for each face, with the index of its component in CCV
1326 (-1 for a deleted face): the faces of one component are the ones that share a label.
1327 */
1328 static int CountConnectedComponents(MeshType &m)
1329 {
1330 std::vector< std::pair<int,FacePointer> > CCV;
1331 return ConnectedComponents(m,CCV);
1332 }
1333
1334 static int ConnectedComponents(MeshType &m, std::vector< std::pair<int,FacePointer> > &CCV,
1335 std::vector<int> *faceComponent = nullptr)
1336 {
1337 tri::RequireFFAdjacency(m);
1338 CCV.clear();
1339 if(faceComponent)
1340 faceComponent->assign(m.face.size(), -1);
1342 std::stack<FacePointer> sf;
1343 FacePointer fpt=&*(m.face.begin());
1344 for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
1345 {
1346 if(!((*fi).IsD()) && !(*fi).IsV())
1347 {
1348 (*fi).SetV();
1349 CCV.push_back(std::make_pair(0,&*fi));
1350 sf.push(&*fi);
1351 while (!sf.empty())
1352 {
1353 fpt=sf.top();
1354 ++CCV.back().first;
1355 if(faceComponent)
1356 (*faceComponent)[tri::Index(m,fpt)] = int(CCV.size())-1;
1357 sf.pop();
1358 for(int j=0; j<fpt->VN(); ++j)
1359 {
1360 if( !face::IsBorder(*fpt,j) )
1361 {
1362 FacePointer l = fpt->FFp(j);
1363 if( !(*l).IsV() )
1364 {
1365 (*l).SetV();
1366 sf.push(l);
1367 }
1368 }
1369 }
1370 }
1371 }
1372 }
1373 return int(CCV.size());
1374 }
1375
1376 static int edgeMeshConnectedComponents(MeshType & poly, std::vector<std::pair<int, typename MeshType::EdgePointer> > &eCC)
1377 {
1378 typedef typename MeshType::EdgePointer EdgePointer;
1379 tri::UpdateTopology<MeshType>::VertexEdge(poly);
1380 tri::UpdateFlags<MeshType>::EdgeClear(poly);
1381 eCC.clear();
1382 std::stack<EdgePointer> stack;
1383
1384 for (auto ei = poly.edge.begin(); ei != poly.edge.end(); ++ei)
1385 if (!ei->IsD() && !ei->IsV())
1386 {
1387 ei->SetV();
1388
1389 std::pair<int, EdgePointer> cc(1, &*ei);
1390
1391 stack.push(&*ei);
1392 while (!stack.empty())
1393 {
1394 EdgePointer ep = stack.top();
1395 stack.pop();
1396
1397 for (int i = 0; i < 2; ++i)
1398 {
1399 edge::VEIterator<typename MeshType::EdgeType> vei(ep->V(i));
1400 while (!vei.End())
1401 {
1402 if (!vei.E()->IsV())
1403 {
1404 vei.E()->SetV();
1405 stack.push(vei.E());
1406 cc.first += 1;
1407 }
1408 ++vei;
1409 }
1410 }
1411 }
1412 eCC.push_back(cc);
1413 }
1414 return int(eCC.size());
1415 }
1416
1417 static void ComputeValence( MeshType &m, typename MeshType::PerVertexIntHandle &h)
1418 {
1419 for(VertexIterator vi=m.vert.begin(); vi!= m.vert.end();++vi)
1420 h[vi]=0;
1421
1422 for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi)
1423 {
1424 if(!((*fi).IsD()))
1425 for(int j=0;j<fi->VN();j++)
1426 ++h[tri::Index(m,fi->V(j))];
1427 }
1428 }
1429
1465 static int MeshGenus(int nvert,int nedges,int nfaces, int numholes, int numcomponents)
1466 {
1467 return -((nvert + nfaces - nedges + numholes - 2 * numcomponents) / 2);
1468 }
1469
1470 static int MeshGenus(MeshType &m)
1471 {
1472 int nvert=m.vn;
1473 int nfaces=m.fn;
1474 int boundary_e,total_e,nonmanif_e;
1475 CountEdgeNum(m,total_e,boundary_e,nonmanif_e);
1476 int numholes=CountHoles(m);
1477 int numcomponents=CountConnectedComponents(m);
1478 int G=MeshGenus(nvert,total_e,nfaces,numholes,numcomponents);
1479 return G;
1480 }
1481
1493 static void IsRegularMesh(MeshType &m, bool &Regular, bool &Semiregular)
1494 {
1495 RequireVFAdjacency(m);
1496 Regular = true;
1497
1498 VertexIterator vi;
1499
1500 // for each vertex the number of edges are count
1501 for (vi = m.vert.begin(); vi != m.vert.end(); ++vi)
1502 {
1503 if (!vi->IsD())
1504 {
1505 face::Pos<FaceType> he((*vi).VFp(), &*vi);
1506 face::Pos<FaceType> ht = he;
1507
1508 int n=0;
1509 bool border=false;
1510 do
1511 {
1512 ++n;
1513 ht.NextE();
1514 if (ht.IsBorder())
1515 border=true;
1516 }
1517 while (ht != he);
1518
1519 if (border)
1520 n = n/2;
1521
1522 if ((n != 6)&&(!border && n != 4))
1523 {
1524 Regular = false;
1525 break;
1526 }
1527 }
1528 }
1529
1530 if (!Regular)
1531 Semiregular = false;
1532 else
1533 {
1534 // For now we do not account for semi-regularity
1535 Semiregular = false;
1536 }
1537 }
1538
1539
1540 static bool IsCoherentlyOrientedMesh(MeshType &m)
1541 {
1542 RequireFFAdjacency(m);
1543 MeshAssert<MeshType>::FFAdjacencyIsInitialized(m);
1544 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1545 if (!fi->IsD())
1546 for(int i=0;i<3;++i)
1547 if(!face::CheckOrientation(*fi,i))
1548 return false;
1549
1550 return true;
1551 }
1552
1553 static void OrientCoherentlyMesh(MeshType &m, bool &_IsOriented, bool &_IsOrientable)
1554 {
1555 RequireFFAdjacency(m);
1556 MeshAssert<MeshType>::FFAdjacencyIsInitialized(m);
1557 bool IsOrientable = true;
1558 bool IsOriented = true;
1559
1560 UpdateFlags<MeshType>::FaceClearV(m);
1561 std::stack<FacePointer> faces;
1562 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1563 {
1564 if (!fi->IsD() && !fi->IsV())
1565 {
1566 // each face put in the stack is selected (and oriented)
1567 fi->SetV();
1568 faces.push(&(*fi));
1569 while (!faces.empty())
1570 {
1571 FacePointer fp = faces.top();
1572 faces.pop();
1573
1574 // make consistently oriented the adjacent faces
1575 for (int j = 0; j < 3; j++)
1576 {
1577 if (!face::IsBorder(*fp,j) && face::IsManifold<FaceType>(*fp, j))
1578 {
1579 FacePointer fpaux = fp->FFp(j);
1580 int iaux = fp->FFi(j);
1581 if (!CheckOrientation(*fpaux, iaux))
1582 {
1583 IsOriented = false;
1584
1585 if (!fpaux->IsV())
1586 face::SwapEdge<FaceType,true>(*fpaux, iaux);
1587 else
1588 {
1589 IsOrientable = false;
1590 break;
1591 }
1592 }
1593 if (!fpaux->IsV())
1594 {
1595 fpaux->SetV();
1596 faces.push(fpaux);
1597 }
1598 }
1599 }
1600 }
1601 }
1602 if (!IsOrientable) break;
1603 }
1604 _IsOriented = IsOriented;
1605 _IsOrientable = IsOrientable;
1606 }
1607
1608
1610 static void FlipMesh(MeshType &m, bool selected=false)
1611 {
1612 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD())
1613 if(!selected || (*fi).IsS())
1614 {
1615 face::SwapEdge<FaceType,false>((*fi), 0);
1616 if (HasPerWedgeTexCoord(m))
1617 std::swap((*fi).WT(0),(*fi).WT(1));
1618 }
1619 }
1625 static bool FlipNormalOutside(MeshType &m)
1626 {
1627 if(m.vert.empty()) return false;
1628
1631
1632 std::vector< VertexPointer > minVertVec;
1633 std::vector< VertexPointer > maxVertVec;
1634
1635 // The set of directions to be chosen
1636 std::vector< CoordType > dirVec;
1637 dirVec.push_back(CoordType(1,0,0));
1638 dirVec.push_back(CoordType(0,1,0));
1639 dirVec.push_back(CoordType(0,0,1));
1640 dirVec.push_back(CoordType( 1, 1,1));
1641 dirVec.push_back(CoordType(-1, 1,1));
1642 dirVec.push_back(CoordType(-1,-1,1));
1643 dirVec.push_back(CoordType( 1,-1,1));
1644 for(size_t i=0;i<dirVec.size();++i)
1645 {
1646 Normalize(dirVec[i]);
1647 minVertVec.push_back(&*m.vert.begin());
1648 maxVertVec.push_back(&*m.vert.begin());
1649 }
1650 for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if(!(*vi).IsD())
1651 {
1652 for(size_t i=0;i<dirVec.size();++i)
1653 {
1654 if( (*vi).cP().dot(dirVec[i]) < minVertVec[i]->P().dot(dirVec[i])) minVertVec[i] = &*vi;
1655 if( (*vi).cP().dot(dirVec[i]) > maxVertVec[i]->P().dot(dirVec[i])) maxVertVec[i] = &*vi;
1656 }
1657 }
1658
1659 int voteCount=0;
1660 ScalarType angleThreshold = cos(math::ToRad(85.0));
1661 for(size_t i=0;i<dirVec.size();++i)
1662 {
1663 // qDebug("Min vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],minVertVec[i]->P()[0],minVertVec[i]->P()[1],minVertVec[i]->P()[2]);
1664 // qDebug("Max vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],maxVertVec[i]->P()[0],maxVertVec[i]->P()[1],maxVertVec[i]->P()[2]);
1665 if(minVertVec[i]->N().dot(dirVec[i]) > angleThreshold ) voteCount++;
1666 if(maxVertVec[i]->N().dot(dirVec[i]) < -angleThreshold ) voteCount++;
1667 }
1668 // qDebug("votecount = %i",voteCount);
1669 if(voteCount < int(dirVec.size())/2) return false;
1670 FlipMesh(m);
1671 return true;
1672 }
1673
1694 MeshType &m,
1695 float normalThresholdDeg=175,
1696 bool repeat=true,
1697 bool updateTopology=true)
1698 {
1699 RequireFFAdjacency(m);
1700 RequireCompactness(m);
1701 RequirePerFaceNormal(m);
1702 RequireTriangularMesh(m);
1703 if (m.fn == 0 || !IsBitTriOnly(m) || m.face.front().IsWedgeTexCoordEnabled())
1704 return 0;
1705
1706 if (updateTopology)
1708 if (CountNonManifoldEdgeFF(m) > 0)
1709 return 0;
1711 const ScalarType thresholdCos = math::Cos(math::ToRad(math::Clamp(
1712 ScalarType(normalThresholdDeg), ScalarType(0), ScalarType(180))));
1713 const ScalarType barycentricEps = ScalarType(0.0001);
1714
1715 auto isFold = [&](const auto &a, const auto &b) {
1716 return a * b < thresholdCos;
1717 };
1718 auto isFoldedAcrossEdge = [&](FaceType &f, int edge, const CoordType &normal) {
1719 if (face::IsBorder(f, edge)) return false;
1720 const auto &adjacentNormal = f.FFp(edge)->N();
1721 return adjacentNormal.SquaredNorm() == ScalarType(0)
1722 || isFold(normal, adjacentNormal);
1723 };
1724
1725 std::vector<size_t> queue(m.fn);
1726 std::vector<unsigned char> queued(m.fn, 1);
1727 for (size_t i = 0; i < queue.size(); ++i) queue[i] = i;
1728 auto enqueue = [&](FacePointer fp) {
1729 const size_t index = tri::Index(m, fp);
1730 if (queued[index]) return;
1731 queued[index] = 1;
1732 queue.push_back(index);
1733 };
1734
1735 int total = 0;
1736 while (!queue.empty()) {
1737 const size_t faceIndex = queue.back();
1738 queue.pop_back();
1739 queued[faceIndex] = 0;
1740 FaceType &f = m.face[faceIndex];
1741
1742 const auto &fNormal = f.N();
1743 if (fNormal.SquaredNorm() == ScalarType(0))
1744 continue;
1745
1746 bool isolatedFold = true;
1747 for (int edge = 0; edge < 3; ++edge) {
1748 if (face::IsBorder(f, edge)) {
1749 isolatedFold = false;
1750 break;
1751 }
1752 const auto &adjacentNormal = f.FFp(edge)->N();
1753 if (adjacentNormal.SquaredNorm() == ScalarType(0)
1754 || !isFold(fNormal, adjacentNormal)) {
1755 isolatedFold = false;
1756 break;
1757 }
1758 }
1759 if (!isolatedFold)
1760 continue;
1761
1762 int flipEdge = -1;
1763 for (int edge = 0; edge < 3; ++edge) {
1764 FacePointer g = f.FFp(edge);
1765 const int oppositeEdge = f.FFi(edge);
1766 if (!face::CheckFlipEdge<FaceType>(f, edge))
1767 continue;
1768
1769 CoordType barycentric;
1770 if (!vcg::InterpolationParameters(
1771 *g, TriangleNormal(*g), f.P2(edge), barycentric))
1772 continue;
1773 if (barycentric[0] <= barycentricEps
1774 || barycentric[1] <= barycentricEps
1775 || barycentric[2] <= barycentricEps)
1776 continue;
1777
1778 const CoordType newFNormal =
1779 Normal(f.P0(edge), g->P2(oppositeEdge), f.P2(edge)).Normalize();
1780 const CoordType newGNormal =
1781 Normal(f.P1(edge), f.P2(edge), g->P2(oppositeEdge)).Normalize();
1782
1783 // After the flip: f-next moves to g, while g-next moves to f.
1784 if (newFNormal.SquaredNorm() == ScalarType(0)
1785 || newGNormal.SquaredNorm() == ScalarType(0)
1786 || isFold(newFNormal, newGNormal)
1787 || isFoldedAcrossEdge(f, f.Next(edge), newGNormal)
1788 || isFoldedAcrossEdge(f, f.Prev(edge), newFNormal)
1789 || isFoldedAcrossEdge(*g, g->Next(oppositeEdge), newFNormal)
1790 || isFoldedAcrossEdge(*g, g->Prev(oppositeEdge), newGNormal))
1791 continue;
1792
1793 flipEdge = edge;
1794 break;
1795 }
1796
1797 if (flipEdge < 0)
1798 continue;
1799
1800 FacePointer g = f.FFp(flipEdge);
1801 const int oppositeEdge = f.FFi(flipEdge);
1802 const bool fNextSelected = f.IsFaceEdgeS(f.Next(flipEdge));
1803 const bool gNextSelected = g->IsFaceEdgeS(g->Next(oppositeEdge));
1804 face::FlipEdge<FaceType>(f, flipEdge);
1805 f.N() = NormalizedTriangleNormal(f);
1806 g->N() = NormalizedTriangleNormal(*g);
1807 // Preserve the four boundary-edge flags; the newly created diagonal is unselected.
1808 if (gNextSelected) f.SetFaceEdgeS(flipEdge); else f.ClearFaceEdgeS(flipEdge);
1809 if (fNextSelected) g->SetFaceEdgeS(oppositeEdge); else g->ClearFaceEdgeS(oppositeEdge);
1810 f.ClearFaceEdgeS(f.Next(flipEdge));
1811 g->ClearFaceEdgeS(g->Next(oppositeEdge));
1812 ++total;
1813 if (repeat) {
1814 enqueue(&f);
1815 enqueue(g);
1816 for (int edge = 0; edge < 3; ++edge) {
1817 enqueue(f.FFp(edge));
1818 enqueue(g->FFp(edge));
1819 }
1820 }
1821 }
1822 return total;
1823 }
1824
1825
1826 static int RemoveTVertexByFlip(MeshType &m, float threshold=40, bool repeat=true)
1827 {
1828 RequireFFAdjacency(m);
1829 RequirePerVertexMark(m);
1830 //Counters for logging and convergence
1831 int count, total = 0;
1832
1833 do {
1835 tri::UnMarkAll(m);
1836 count = 0;
1837
1838 //detection stage
1839 for(unsigned int index = 0 ; index < m.face.size(); ++index )
1840 {
1841 FacePointer f = &(m.face[index]); float sides[3]; CoordType dummy;
1842 sides[0] = Distance(f->P(0), f->P(1));
1843 sides[1] = Distance(f->P(1), f->P(2));
1844 sides[2] = Distance(f->P(2), f->P(0));
1845 // Find largest triangle side
1846 int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides);
1847 if( tri::IsMarked(m,f->V2(i) )) continue;
1848
1849 if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] )
1850 {
1851 tri::Mark(m,f->V2(i));
1852 if(face::CheckFlipEdge<FaceType>( *f, i )) {
1853 // Check if EdgeFlipping improves quality
1854 FacePointer g = f->FFp(i); int k = f->FFi(i);
1855 Triangle3<ScalarType> t1(f->P(i), f->P1(i), f->P2(i)), t2(g->P(k), g->P1(k), g->P2(k)),
1856 t3(f->P(i), g->P2(k), f->P2(i)), t4(g->P(k), f->P2(i), g->P2(k));
1857
1858 if ( std::min( QualityFace(t1), QualityFace(t2) ) < std::min( QualityFace(t3), QualityFace(t4) ))
1859 {
1860 face::FlipEdge<FaceType>( *f, i );
1861 ++count; ++total;
1862 }
1863 }
1864
1865 }
1866 }
1867
1868 // tri::UpdateNormal<MeshType>::PerFace(m);
1869 }
1870 while( repeat && count );
1871 return total;
1872 }
1873
1874 static int RemoveTVertexByCollapse(MeshType &m, float threshold=40, bool repeat=true)
1875 {
1876 RequirePerVertexMark(m);
1877 //Counters for logging and convergence
1878 int count, total = 0;
1879
1880 do {
1881 tri::UnMarkAll(m);
1882 count = 0;
1883
1884 //detection stage
1885 for(unsigned int index = 0 ; index < m.face.size(); ++index )
1886 {
1887 FacePointer f = &(m.face[index]);
1888 float sides[3];
1889 CoordType dummy;
1890
1891 sides[0] = Distance(f->P(0), f->P(1));
1892 sides[1] = Distance(f->P(1), f->P(2));
1893 sides[2] = Distance(f->P(2), f->P(0));
1894 int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides);
1895 if( tri::IsMarked(m,f->V2(i) )) continue;
1896
1897 if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] )
1898 {
1899 tri::Mark(m,f->V2(i));
1900
1901 int j = Distance(dummy,f->P(i))<Distance(dummy,f->P1(i))?i:(i+1)%3;
1902 f->P2(i) = f->P(j); tri::Mark(m,f->V(j));
1903 ++count; ++total;
1904 }
1905 }
1906
1907
1911 }
1912 while( repeat && count );
1913
1914 return total;
1915 }
1916
1917 static bool SelfIntersections(MeshType &m, std::vector<FaceType*> &ret)
1918 {
1919 RequirePerFaceMark(m);
1920 ret.clear();
1921 int referredBit = FaceType::NewBitFlag();
1922 tri::UpdateFlags<MeshType>::FaceClear(m,referredBit);
1923
1924 TriMeshGrid gM;
1925 gM.Set(m.face.begin(),m.face.end());
1926
1927 for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD())
1928 {
1929 (*fi).SetUserBit(referredBit);
1930 Box3< ScalarType> bbox;
1931 (*fi).GetBBox(bbox);
1932 std::vector<FaceType*> inBox;
1933 vcg::tri::GetInBoxFace(m, gM, bbox,inBox);
1934 bool Intersected=false;
1935 typename std::vector<FaceType*>::iterator fib;
1936 for(fib=inBox.begin();fib!=inBox.end();++fib)
1937 {
1938 if(!(*fib)->IsUserBit(referredBit) && (*fib != &*fi) )
1940 ret.push_back(*fib);
1941 if(!Intersected) {
1942 ret.push_back(&*fi);
1943 Intersected=true;
1944 }
1945 }
1946 }
1947 inBox.clear();
1948 }
1949
1950 FaceType::DeleteBitFlag(referredBit);
1951 return (ret.size()>0);
1952 }
1953
1957 static bool IsSizeConsistent(MeshType &m)
1958 {
1959 int DeletedVertNum=0;
1960 for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi)
1961 if((*vi).IsD()) DeletedVertNum++;
1962
1963 int DeletedEdgeNum=0;
1964 for (EdgeIterator ei = m.edge.begin(); ei != m.edge.end(); ++ei)
1965 if((*ei).IsD()) DeletedEdgeNum++;
1966
1967 int DeletedFaceNum=0;
1968 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1969 if((*fi).IsD()) DeletedFaceNum++;
1970
1971 if(size_t(m.vn+DeletedVertNum) != m.vert.size()) return false;
1972 if(size_t(m.en+DeletedEdgeNum) != m.edge.size()) return false;
1973 if(size_t(m.fn+DeletedFaceNum) != m.face.size()) return false;
1974
1975 return true;
1976 }
1977
1982 static bool IsFFAdjacencyConsistent(MeshType &m)
1983 {
1984 RequireFFAdjacency(m);
1985
1986 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
1987 if(!(*fi).IsD())
1988 {
1989 for(int i=0;i<3;++i)
1990 if(!FFCorrectness(*fi, i)) return false;
1991 }
1992 return true;
1993 }
1994
1998 static bool HasConsistentPerWedgeTexCoord(MeshType &m)
1999 {
2000 tri::RequirePerFaceWedgeTexCoord(m);
2001
2002 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
2003 if(!(*fi).IsD())
2004 { FaceType &f=(*fi);
2005 if( ! ( (f.WT(0).N() == f.WT(1).N()) && (f.WT(0).N() == (*fi).WT(2).N()) ) )
2006 return false; // all the vertices must have the same index.
2007
2008 if((*fi).WT(0).N() <0) return false; // no undefined texture should be allowed
2009 }
2010 return true;
2011 }
2012
2016 static bool HasZeroTexCoordFace(MeshType &m)
2017 {
2018 tri::RequirePerFaceWedgeTexCoord(m);
2019
2020 for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi)
2021 if(!(*fi).IsD())
2022 {
2023 if( (*fi).WT(0).P() == (*fi).WT(1).P() && (*fi).WT(0).P() == (*fi).WT(2).P() ) return false;
2024 }
2025 return true;
2026 }
2027
2028
2036 static bool TestFaceFaceIntersection(FaceType *f0,FaceType *f1)
2037 {
2038 int sv = face::CountSharedVertex(f0,f1);
2039 if(sv==3) return true;
2040 if(sv==0) return (vcg::IntersectionTriangleTriangle<FaceType>((*f0),(*f1)));
2041 // if the faces share only a vertex, the opposite edge (as a segment) is tested against the face
2042 // to avoid degenerate cases where the two triangles have the opposite edge on a common plane
2043 // we offset the segment to test toward the shared vertex
2044 if(sv==1)
2045 {
2046 int i0,i1; ScalarType a,b;
2047 face::FindSharedVertex(f0,f1,i0,i1);
2048 CoordType shP = f0->V(i0)->P()*0.5;
2049 if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f0).V1(i0)->P()*0.5+shP,(*f0).V2(i0)->P()*0.5+shP), *f1, a, b) )
2050 {
2051 // a,b are the param coords of the intersection point of the segment.
2052 if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false;
2053 return true;
2054 }
2055 if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f1).V1(i1)->P()*0.5+shP,(*f1).V2(i1)->P()*0.5+shP), *f0, a, b) )
2056 {
2057 // a,b are the param coords of the intersection point of the segment.
2058 if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false;
2059 return true;
2060 }
2061
2062 }
2063 return false;
2064 }
2065
2066
2067
2071 static int MergeCloseVertex(MeshType &m, const ScalarType radius)
2072 {
2073 int mergedCnt=0;
2074 mergedCnt = ClusterVertex(m,radius);
2075 RemoveDuplicateVertex(m,true);
2076 return mergedCnt;
2077 }
2078
2079 static int ClusterVertex(MeshType &m, const ScalarType radius)
2080 {
2081 if(m.vn==0) return 0;
2082 // some spatial indexing structure does not work well with deleted vertices...
2084 typedef vcg::SpatialHashTable<VertexType, ScalarType> SampleSHT;
2085 SampleSHT sht;
2086 tri::EmptyTMark<MeshType> markerFunctor;
2087 std::vector<VertexType*> closests;
2088 int mergedCnt=0;
2089 sht.Set(m.vert.begin(), m.vert.end());
2091 for(VertexIterator viv = m.vert.begin(); viv!= m.vert.end(); ++viv)
2092 if(!(*viv).IsD() && !(*viv).IsV())
2093 {
2094 (*viv).SetV();
2095 Point3<ScalarType> p = viv->cP();
2096 Box3<ScalarType> bb(p-Point3<ScalarType>(radius,radius,radius),p+Point3<ScalarType>(radius,radius,radius));
2097 GridGetInBox(sht, markerFunctor, bb, closests);
2098 // qDebug("Vertex %i has %i closest", &*viv - &*m.vert.begin(),closests.size());
2099 for(size_t i=0; i<closests.size(); ++i)
2100 {
2101 ScalarType dist = Distance(p,closests[i]->cP());
2102 if(dist < radius && !closests[i]->IsV())
2103 {
2104 // printf("%f %f \n",dist,radius);
2105 mergedCnt++;
2106 closests[i]->SetV();
2107 closests[i]->P()=p;
2108 }
2109 }
2110 }
2111 return mergedCnt;
2112 }
2113
2114
2115 static std::pair<int,int> RemoveSmallConnectedComponentsSize(MeshType &m, int maxCCSize)
2116 {
2117 std::vector< std::pair<int, typename MeshType::FacePointer> > CCV;
2118 int TotalCC=ConnectedComponents(m, CCV);
2119 int DeletedCC=0;
2120
2121 ConnectedComponentIterator<MeshType> ci;
2122 for(unsigned int i=0;i<CCV.size();++i)
2123 {
2124 std::vector<typename MeshType::FacePointer> FPV;
2125 if(CCV[i].first<maxCCSize)
2126 {
2127 DeletedCC++;
2128 for(ci.start(m,CCV[i].second);!ci.completed();++ci)
2129 FPV.push_back(*ci);
2130
2131 typename std::vector<typename MeshType::FacePointer>::iterator fpvi;
2132 for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi)
2134 }
2135 }
2136 return std::make_pair(TotalCC,DeletedCC);
2137 }
2138
2139
2141 // it returns a pair with the number of connected components and the number of deleted ones.
2142 static std::pair<int,int> RemoveSmallConnectedComponentsDiameter(MeshType &m, ScalarType maxDiameter)
2143 {
2144 std::vector< std::pair<int, typename MeshType::FacePointer> > CCV;
2145 int TotalCC=ConnectedComponents(m, CCV);
2146 int DeletedCC=0;
2148 for(unsigned int i=0;i<CCV.size();++i)
2149 {
2151 std::vector<typename MeshType::FacePointer> FPV;
2152 for(ci.start(m,CCV[i].second);!ci.completed();++ci)
2153 {
2154 FPV.push_back(*ci);
2155 bb.Add((*ci)->P(0));
2156 bb.Add((*ci)->P(1));
2157 bb.Add((*ci)->P(2));
2158 }
2159 if(bb.Diag()<maxDiameter)
2160 {
2161 DeletedCC++;
2162 typename std::vector<typename MeshType::FacePointer>::iterator fpvi;
2163 for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi)
2165 }
2166 }
2167 return std::make_pair(TotalCC,DeletedCC);
2168 }
2169
2171 // it returns a pair with the number of connected components and the number of deleted ones.
2172 static std::pair<int,int> RemoveHugeConnectedComponentsDiameter(MeshType &m, ScalarType minDiameter)
2173 {
2174 std::vector< std::pair<int, typename MeshType::FacePointer> > CCV;
2175 int TotalCC=ConnectedComponents(m, CCV);
2176 int DeletedCC=0;
2178 for(unsigned int i=0;i<CCV.size();++i)
2179 {
2180 Box3f bb;
2181 std::vector<typename MeshType::FacePointer> FPV;
2182 for(ci.start(m,CCV[i].second);!ci.completed();++ci)
2183 {
2184 FPV.push_back(*ci);
2185 bb.Add((*ci)->P(0));
2186 bb.Add((*ci)->P(1));
2187 bb.Add((*ci)->P(2));
2188 }
2189 if(bb.Diag()>minDiameter)
2190 {
2191 DeletedCC++;
2192 typename std::vector<typename MeshType::FacePointer>::iterator fpvi;
2193 for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi)
2195 }
2196 }
2197 return std::make_pair(TotalCC,DeletedCC);
2198 }
2199
2200
2201
2208 static void SelectFoldedFaceFromOneRingFaces(MeshType &m, ScalarType cosThreshold)
2209 {
2210 typedef std::unordered_set<VertexPointer> VertexSet;
2211 tri::RequireVFAdjacency(m);
2212 tri::RequirePerFaceNormal(m);
2213 tri::RequirePerVertexNormal(m);
2218 if (cosThreshold > 0)
2219 cosThreshold = 0;
2220
2221#pragma omp parallel for schedule(dynamic, 10)
2222 for (int i = 0; i < m.face.size(); i++)
2223 {
2224 VertexSet nearVertex;
2225 std::vector<CoordType> pointVec;
2226 FacePointer f = &m.face[i];
2227 for (int j = 0; j < 3; j++)
2228 {
2229 std::vector<VertexPointer> temp;
2230 vcg::face::VVStarVF<FaceType>(f->V(j), temp);
2231 typename std::vector<VertexPointer>::iterator iter = temp.begin();
2232 for (; iter != temp.end(); iter++)
2233 {
2234 if ((*iter) != f->V1(j) && (*iter) != f->V2(j))
2235 {
2236 if (nearVertex.insert((*iter)).second)
2237 pointVec.push_back((*iter)->P());
2238 }
2239 }
2240 nearVertex.insert(f->V(j));
2241 pointVec.push_back(f->P(j));
2242 }
2243
2244 if (pointVec.size() > 3)
2245 {
2246 vcg::Plane3<ScalarType> plane;
2247 vcg::FitPlaneToPointSet(pointVec, plane);
2248 float avgDot = 0;
2249 for (auto nvp : nearVertex)
2250 avgDot += plane.Direction().dot(nvp->N());
2251 avgDot /= nearVertex.size();
2252 typename MeshType::VertexType::NormalType normal;
2253 if (avgDot < 0)
2254 normal = -plane.Direction();
2255 else
2256 normal = plane.Direction();
2257 if (normal.dot(f->N()) < cosThreshold)
2258 f->SetS();
2259 }
2260 }
2261 }
2266 static int SelectIntersectingFaces(MeshType &m1, MeshType &m2)
2267 {
2268 RequirePerFaceMark(m2);
2269 RequireCompactness(m1);
2270 RequireCompactness(m2);
2271
2273
2274 TriMeshGrid gM;
2275 gM.Set(m2.face.begin(),m2.face.end());
2276 int selCnt=0;
2277 for(auto fi=m1.face.begin();fi!=m1.face.end();++fi)
2278 {
2279 Box3< ScalarType> bbox;
2280 (*fi).GetBBox(bbox);
2281 std::vector<FaceType*> inBox;
2282 vcg::tri::GetInBoxFace(m2, gM, bbox,inBox);
2283 for(auto fib=inBox.begin(); fib!=inBox.end(); ++fib)
2284 {
2286 fi->SetS();
2287 ++selCnt;
2288 }
2289 }
2290 inBox.clear();
2291 }
2292 return selCnt;
2293 }
2294
2295}; // end class
2298} //End Namespace Tri
2299} // End Namespace vcg
2300#endif
Definition: box3.h:42
void Add(const Box3< BoxScalarType > &b)
Definition: box3.h:104
BoxScalarType Diag() const
Return the lenght of the diagonal of the box .
Definition: box3.h:240
Definition: point3.h:43
Class to safely add and delete elements in a mesh.
Definition: allocate.h:99
static void CompactFaceVector(MeshType &m, PointerUpdater< FacePointer > &pu)
Compact face vector by removing deleted elements.
Definition: allocate.h:1256
static void DeleteFace(MeshType &m, FaceType &f)
Definition: allocate.h:948
static void CompactVertexVector(MeshType &m, PointerUpdater< VertexPointer > &pu)
Compact vector of vertices removing deleted elements. Deleted elements are put to the end of the vect...
Definition: allocate.h:1109
static void DeleteVertex(MeshType &m, VertexType &v)
Definition: allocate.h:960
static VertexIterator AddVertices(MeshType &m, size_t n, PointerUpdater< VertexPointer > &pu)
Add n vertices to the mesh. Function to add n vertices to the mesh. The elements are added always to ...
Definition: allocate.h:197
static void DeleteEdge(MeshType &m, EdgeType &e)
Definition: allocate.h:971
Definition: clean.h:278
Definition: clean.h:302
Class of static functions to clean//restore meshs.
Definition: clean.h:166
static int RemoveDegenerateVertex(MeshType &m, bool DeleteVertexFlag=true)
Definition: clean.h:441
static int RemoveFaceFoldByFlip(MeshType &m, float normalThresholdDeg=175, bool repeat=true, bool updateTopology=true)
Definition: clean.h:1693
static void SelectFoldedFaceFromOneRingFaces(MeshType &m, ScalarType cosThreshold)
Definition: clean.h:2208
static bool FlipNormalOutside(MeshType &m)
Definition: clean.h:1625
static int RemoveDuplicateVertex(MeshType &m, bool RemoveDegenerateFlag=true)
Definition: clean.h:207
static bool IsSizeConsistent(MeshType &m)
Definition: clean.h:1957
static int SelectIntersectingFaces(MeshType &m1, MeshType &m2)
Definition: clean.h:2266
static bool IsBitTriQuadOnly(const MeshType &m)
Definition: clean.h:941
static bool IsBitTriOnly(const MeshType &m)
Definition: clean.h:924
static bool HasZeroTexCoordFace(MeshType &m)
Definition: clean.h:2016
static std::pair< int, int > RemoveSmallConnectedComponentsDiameter(MeshType &m, ScalarType maxDiameter)
Remove the connected components smaller than a given diameter.
Definition: clean.h:2142
static size_t SplitManifoldComponents(MeshType &m, const ScalarType moveThreshold=0)
Split the mesh along its non-manifold edges. The faces reachable from one another across manifold edg...
Definition: clean.h:725
static bool IsBitQuadOnly(const MeshType &m)
Definition: clean.h:893
static int CountNonManifoldEdgeEE(MeshType &m, bool SelectFlag=false)
Definition: clean.h:1079
static int RemoveUnreferencedVertex(MeshType &m, bool DeleteVertexFlag=true)
Definition: clean.h:398
static int SplitNonManifoldVertex(MeshType &m, ScalarType moveThreshold)
Removal of faces that were incident on a non manifold edge.
Definition: clean.h:654
static int MeshGenus(int nvert, int nedges, int nfaces, int numholes, int numcomponents)
Definition: clean.h:1465
static std::pair< int, int > RemoveHugeConnectedComponentsDiameter(MeshType &m, ScalarType minDiameter)
Remove the connected components greater than a given diameter.
Definition: clean.h:2172
static int CountBitLargePolygons(const MeshType &m)
Definition: clean.h:1008
static bool HasConsistentPerFaceFauxFlag(const MeshType &m)
Definition: clean.h:1059
static void SelectCreaseVertexOnEdgeMeshVE(MeshType &m, ScalarType AngleRadThr)
Given an edge mesh it selects the vertexes where the edge make an angle greater than AngleRadThr....
Definition: clean.h:627
static bool HasConsistentPerWedgeTexCoord(MeshType &m)
Definition: clean.h:1998
static int CountHoles(MeshType &m)
Counts the boundary loops of the mesh. Needs FF adjacency.
Definition: clean.h:1273
static bool TestFaceFaceIntersection(FaceType *f0, FaceType *f1)
Definition: clean.h:2036
static void FlipMesh(MeshType &m, bool selected=false)
Flip the orientation of the whole mesh flipping all the faces (by swapping the first two vertices)
Definition: clean.h:1610
static int CountBitQuads(const MeshType &m)
Definition: clean.h:956
static int CountBitPolygons(const MeshType &m)
Definition: clean.h:985
static bool IsWaterTight(MeshType &m)
Definition: clean.h:1231
static int RemoveDegenerateFace(MeshType &m, bool DeleteFacesFlag=true)
Definition: clean.h:481
static int CountBitTris(const MeshType &m)
Definition: clean.h:971
static int RemoveDuplicateEdge(MeshType &m)
Definition: clean.h:365
static void IsRegularMesh(MeshType &m, bool &Regular, bool &Semiregular)
Definition: clean.h:1493
static int CountNonManifoldEdgeFF(MeshType &m, bool SelectFlag=false)
Definition: clean.h:1117
static int RemoveDuplicateFace(MeshType &m, bool DeleteFacesFlag=true)
Definition: clean.h:335
static int RemoveNonManifoldFace(MeshType &m, bool DeleteFacesFlag=true)
Removal of faces that were incident on a non manifold edge.
Definition: clean.h:823
static void SelectCreaseVertexOnEdgeMeshEE(MeshType &m, ScalarType AngleRadThr)
Given an edge mesh it selects the vertexes where the edge make an angle greater than AngleRadThr....
Definition: clean.h:597
static int MergeCloseVertex(MeshType &m, const ScalarType radius)
Definition: clean.h:2071
static int CountNonManifoldVertexFF(MeshType &m, bool selectVert=true, bool clearSelection=true)
Definition: clean.h:1173
static bool IsFFAdjacencyConsistent(MeshType &m)
Definition: clean.h:1982
A stack for saving and restoring selection.
Definition: selection.h:43
bool pop(bool orFlag=false, bool andFlag=false)
Definition: selection.h:99
Management, updating and computation of per-vertex and per-face flags (like border flags).
Definition: flag.h:44
static void NormalizePerVertex(ComputeMeshType &m)
Normalize the length of the vertex normals.
Definition: normal.h:239
static void PerVertexAngleWeighted(ComputeMeshType &m)
Calculates the vertex normal as an angle weighted average. It does not need or exploit current face n...
Definition: normal.h:124
static void PerFaceNormalized(ComputeMeshType &m)
Equivalent to PerFace() and NormalizePerFace()
Definition: normal.h:276
static void PerVertexNormalized(ComputeMeshType &m)
Equivalent to PerVertex() and NormalizePerVertex()
Definition: normal.h:269
static size_t VertexClear(MeshType &m)
This function clear the selection flag for all the vertices.
Definition: selection.h:237
static size_t FaceClear(MeshType &m)
This function clears the selection flag for all the faces.
Definition: selection.h:253
static size_t FaceFromVertexLoose(MeshType &m, bool preserveSelection=false)
Select all the faces with at least one selected vertex.
Definition: selection.h:471
Generation of per-vertex and per-face topological information.
Definition: topology.h:43
static void VertexFace(MeshType &m)
Update the Vertex-Face topological relation.
Definition: topology.h:467
static void FillEdgeVector(MeshType &m, std::vector< PEdge > &edgeVec, bool includeFauxEdge=true)
Definition: topology.h:200
static void FaceFace(MeshType &m)
Update the Face-Face topological relation by allowing to retrieve for each face what other faces shar...
Definition: topology.h:395
bool IsManifold(FaceType const &f, const int j)
Definition: topology.h:41
int CountSharedVertex(FaceType *f0, FaceType *f1)
Definition: topology.h:1273
bool IsBorder(FaceType const &f, const int j)
Definition: topology.h:55
bool CheckOrientation(FaceType &f, int z)
Definition: topology.h:380
bool FindSharedVertex(FaceType *f0, FaceType *f1, int &i, int &j)
Definition: topology.h:1291
Definition: color4.h:30
P3ScalarType PSDist(const Point3< P3ScalarType > &p, const Point3< P3ScalarType > &v1, const Point3< P3ScalarType > &v2, Point3< P3ScalarType > &q)
Point(p) Edge(v1-v2) dist, q is the point in v1-v2 with min dist.
Definition: point3.h:522
Definition: clean.h:816