vtkPolyhedron.cxx 96.4 KB
Newer Older
1
2
3
/*=========================================================================

  Program:   Visualization Toolkit
4
  Module:    vtkPolyhedron.cxx
5
6
7
8
9
10
11
12
13
14
15
16
17

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

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

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

#include "vtkCellArray.h"
18
#include "vtkIdTypeArray.h"
19
20
21
#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
22
#include "vtkOrderedTriangulator.h"
23
24
25
26
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkTetra.h"
#include "vtkTriangle.h"
27
#include "vtkQuad.h"
28
29
#include "vtkPolygon.h"
#include "vtkLine.h"
Will Schroeder's avatar
Will Schroeder committed
30
#include "vtkEdgeTable.h"
31
32
33
#include "vtkPolyData.h"
#include "vtkCellLocator.h"
#include "vtkGenericCell.h"
34
#include "vtkPointLocator.h"
35
#include "vtkMeanValueCoordinatesInterpolator.h"
36
37
#include "vtkSmartPointer.h"
#include "vtkMergePoints.h"
38
#include "vtkCellData.h"
39
#include "vtkDataArray.h"
40
#include "vtkType.h"
41

42
43
#include <vtkstd/map>
#include <vtkstd/vector>
44
#include <vtkstd/set>
45
46
#include <vtkstd/list>
#include <limits>
47

48
49
vtkStandardNewMacro(vtkPolyhedron);

50
51
52
53
54
// Special typedef
typedef vtkstd::vector<vtkIdType>                 vtkIdVectorType;
class vtkPointIdMap : public vtkstd::map<vtkIdType,vtkIdType>{};
class vtkIdToIdMapType : public vtkstd::map<vtkIdType, vtkIdType>{};
class vtkIdToIdVectorMapType : public vtkstd::map<vtkIdType, vtkIdVectorType>{};
55
typedef vtkstd::map<vtkIdType,vtkIdType*>::iterator PointIdMapIterator;
56
57
58
59
typedef vtkIdToIdVectorMapType::iterator          vtkIdToIdVectorMapIteratorType;
typedef vtkstd::pair<vtkIdType, vtkIdVectorType>  vtkIdToIdVectorPairType;
typedef vtkstd::pair<vtkIdType, vtkIdType>        vtkIdToIdPairType;
typedef vtkstd::set<vtkIdType>                    vtkIdSetType;
60

61
// Special class for iterating through polyhedron faces
62
//----------------------------------------------------------------------------
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class vtkPolyhedronFaceIterator
{
public:
  vtkIdType CurrentPolygonSize;
  vtkIdType *Polygon;
  vtkIdType *Current;
  vtkIdType NumberOfPolygons;
  vtkIdType Id;

  vtkPolyhedronFaceIterator(vtkIdType numFaces, vtkIdType *t)
    {
      this->CurrentPolygonSize = t[0];
      this->Polygon = t;
      this->Current = t+1;
      this->NumberOfPolygons = numFaces;
      this->Id = 0;
    }
  vtkIdType* operator++()
    {
      this->Current += this->CurrentPolygonSize + 1;
      this->Polygon = this->Current - 1;
84
      this->CurrentPolygonSize = this->Polygon[0];
85
86
87
88
89
      this->Id++;
      return this->Current;
    }
};

90
91

// Special class for iterating through vertices on a polygon face
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
class vtkPolygonVertexIterator
{
public:
  vtkIdType *Current;
  vtkIdType NumberOfVertices;
  vtkIdType Id;
  // 1 or 0 for iterating along its original direction or reverse
  vtkIdType IterDirection; 

  vtkPolygonVertexIterator(vtkIdType numVertices, vtkIdType startVertex, 
                           vtkIdType *startVertexPointer, vtkIdType nextVertex)
    {
    this->Current = startVertexPointer;
    this->NumberOfVertices = numVertices;
    this->Id = startVertex;
    this->IterDirection = 1;
    vtkIdType nextId = this->Id + 1;
    vtkIdType *next = this->Current + 1;
    if (nextId == this->NumberOfVertices)
      {
      next -= this->NumberOfVertices;
      }
    if (*next != nextVertex)
      {
      this->IterDirection = 0;
      }
    }

  vtkIdType* operator++()
    {
    if (this->IterDirection)
      {
      this->Id++;
      this->Current++;
      if (this->Id == this->NumberOfVertices)
        {
        this->Id = 0;
        this->Current -= this->NumberOfVertices;
        }
      }
    else
      {
      this->Id--;
      this->Current--;
      if (this->Id == -1)
        {
        this->Id = this->NumberOfVertices - 1;
        this->Current += this->NumberOfVertices;
        }
      }
    return this->Current;
    }
};

147
//----------------------------------------------------------------------------
148
class vtkPolyhedron::vtkInternal
149
{
150
public:
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
  vtkIdTypeArray * FacesBackup;
  vtkEdgeTable * EdgeTableBackup;

vtkInternal()
{
  this->FacesBackup = NULL;
  this->EdgeTableBackup = NULL;
}

~vtkInternal()
{
  this->FacesBackup = NULL;
  this->EdgeTableBackup = NULL;
}

//----------------------------------------------------------------------------
// Here we use a point merger to try to prevent the problem of duplicated 
// points in the input. 
void RemoveDuplicatedPointsFromFaceArrayAndEdgeTable(vtkPoints * points,
                                                     vtkIdTypeArray * & faces,
                                                     vtkEdgeTable * & edgeTable,
                                                     double *bounds)
{
  const double eps = 0.000001;
  vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New();
  vtkSmartPointer<vtkPointLocator> merge = vtkSmartPointer<vtkPointLocator>::New();
  merge->SetTolerance(eps);
  merge->InitPointInsertion(newPoints, bounds);
  bool foundDupPoint = false;
  vtkIdType pid = -1;
  vtkIdToIdMapType pidMap0;
  for (vtkIdType i = 0; i < points->GetNumberOfPoints(); i++)
    {
    if (!merge->InsertUniquePoint(points->GetPoint(i), pid))
      {
      foundDupPoint = true;
      }
    if (pidMap0.find(pid) == pidMap0.end())
      {
      pidMap0.insert(vtkIdToIdPairType(pid,i));
      }
    }
  
  // update face array and edge table if necessary.
  if (foundDupPoint)
    {
    vtkIdToIdMapType pidMap;
    for (vtkIdType i = 0; i < points->GetNumberOfPoints(); i++)
      {
      pid = merge->IsInsertedPoint(points->GetPoint(i));
      pidMap.insert(vtkIdToIdPairType(i, pidMap0.find(pid)->second));
      }

    this->FacesBackup = faces;
    this->EdgeTableBackup = edgeTable;

    vtkIdType nfaces = 0;
    vtkIdType insertId = 0;
    
    faces = vtkIdTypeArray::New();
    faces->SetNumberOfTuples(points->GetNumberOfPoints()*10);
    faces->InsertComponent(insertId++, 0, 0); // allocate space for nfaces
    edgeTable = vtkEdgeTable::New();
    edgeTable->InitEdgeInsertion(points->GetNumberOfPoints());

    vtkPolyhedronFaceIterator 
      faceIter(this->FacesBackup->GetValue(0), this->FacesBackup->GetPointer(1));
    while (faceIter.Id < faceIter.NumberOfPolygons)
      {
      vtkIdVectorType vVector;
      for (vtkIdType i = 0; i < faceIter.CurrentPolygonSize; i++)
        {
223
        pid = pidMap.find(faceIter.Current[i])->second;
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
        vVector.push_back(pid);
        }
      bool dupPointRemoved = true;
      while (dupPointRemoved && vVector.size() > 2)
        {
        dupPointRemoved = false;
        if (vVector[0] == vVector[vVector.size()-1])
          {
          vVector.erase(vVector.begin()+vVector.size()-1);
          dupPointRemoved = true;
          }
        for (size_t i = 1; i < vVector.size(); i++)
          {
          if (vVector[i] == vVector[i-1])
            {
            vVector.erase(vVector.begin()+i);
            dupPointRemoved = true;
            }
          }
        }      
      if (vVector.size() < 3)
        {
        ++faceIter;
        continue;
        }
      
      nfaces++;

      faces->InsertComponent(insertId++, 0, vVector.size());
      for (size_t i = 0; i < vVector.size(); i++)
        {
        faces->InsertComponent(insertId++, 0, vVector[i]);
        }
      if (edgeTable->IsEdge(vVector[0],vVector[vVector.size()-1]) == (-1))
        {
        edgeTable->InsertEdge(vVector[0],vVector[vVector.size()-1]);
        }
      for (size_t i = 1; i < vVector.size(); i++)
        {
        if (edgeTable->IsEdge(vVector[i],vVector[i-1]) == (-1))
          {
          edgeTable->InsertEdge(vVector[i],vVector[i-1]);
          }
        }

      ++faceIter;
      }
    
    faces->SetComponent(0,0,nfaces);
    }
  else
    {
    this->FacesBackup = NULL;
    this->EdgeTableBackup = NULL;
    }
}

//----------------------------------------------------------------------------
// Here we use a point merger to try to prevent the problem of duplicated 
// points in the input. 
void RestoreFaceArrayAndEdgeTable(vtkIdTypeArray * & faces,
                                  vtkEdgeTable * & edgeTable)
{
  if (this->FacesBackup)
    {
    faces->Delete();
    faces = this->FacesBackup;
    }
  if (this->EdgeTableBackup)
    {
    edgeTable->Delete();
    edgeTable = this->EdgeTableBackup;
    }
}
298
299

//----------------------------------------------------------------------------
300
301
// insert new id element in between two existing adjacent id elements.
// this is a convenient function. no check whether the input elements 
302
// exist in the vector. no check for element adjacency.
303
304
int InsertNewIdToIdVector(vtkIdVectorType & idVector, vtkIdType id, 
                          vtkIdType id0, vtkIdType id1)
305
{
306
  if (idVector.size() < 2)
307
308
309
310
    {
    return 0;
    }
  
311
312
313
  size_t num = idVector.size();
  if ((idVector[0] == id0 && idVector[num-1] == id1)
    ||(idVector[0] == id1 && idVector[num-1] == id0))
314
    {
315
    idVector.push_back(id);
316
317
318
    return 1;
    }
  
319
  vtkIdVectorType::iterator iter = idVector.begin();
320
  for (; iter != idVector.end(); ++iter)
321
322
323
324
    {
    if (*iter == id0 || *iter == id1)
      {
      ++iter;
325
      idVector.insert(iter, id);
326
327
328
329
330
      return 1;
      }
    }
  
  return 0;
331
};
332
333
334
335

// Convinient function used by clip. The id is the vector index of the positive 
// point, id0 is the vector index of the start point, and id1 is the vector index
// of the end point.
336
//----------------------------------------------------------------------------
337
338
int EraseSegmentFromIdVector(vtkIdVectorType & idVector, vtkIdType id, 
                             vtkIdType id0, vtkIdType id1)
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
{
  // three possible cases
  // first case: 0 -- id0 -- id -- id1 -- size-1
  if (id0 < id && id < id1)
    {
    idVector.erase(idVector.begin() + id0 + 1, idVector.begin() + id1);
    }
  // second case: 0 -- id1 -- id0 -- id -- size-1
  // third case: 0 -- id -- id1 -- id0 -- size-1
  else if (id1 < id0 && (id0 < id || id < id1))
    {
    idVector.erase(idVector.begin() + id0 + 1, idVector.end());
    idVector.erase(idVector.begin(), idVector.begin() + id1);
    }
  else
    {
    // we should never get here.
    return 0;
    }
  return 1;
359
};
360

361
// convert the point ids from map.first to map.second
362
//----------------------------------------------------------------------------
363
int ConvertPointIds(vtkIdType npts, vtkIdType * pts, 
364
                    vtkIdToIdMapType & map, vtkIdType reverse = 0)
365
366
367
{
  for (vtkIdType i = 0; i < npts; i++)
    {
368
    vtkIdType id = reverse ? npts-1-i : i;
369
    vtkIdToIdMapType::iterator iter = map.find(pts[id]);
370
371
372
373
    if (iter == map.end())
      {
      return 0;
      }
374
    pts[id] = iter->second;
375
376
    }
  return 1;
377
};
378

379
380
381
382
383
384
385
386
//----------------------------------------------------------------------------
// The connected contour points are found by (1) locating the current
// contour point in the face loop, (2) looping through face point: 
//  meet a positive point, keep going. 
//  meet a contour point, store it and stop marching in this direction.
//  meet a negative point, stop marching in this direction.
//  meet the same point from both directions, stop. 
// This loop may find zero, one or two connected contour points.
387
388
void FindConnectedContourPointsOnFace(vtkIdVectorType & facePtsVector, 
                                      vtkIdVectorType & faceContourPtsVec,
389
                                      vtkIdType currContourPoint,
390
391
392
                                      vtkIdVectorType & pointLabelVec,
                                      vtkIdSetType & connectedContourPtsSet,
                                      vtkIdSetType & unConnectedContourPtsSet)
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
{
  vtkIdType numFacePoints = static_cast<vtkIdType>(facePtsVector.size());
  if (numFacePoints < 3)
    {
    return;
    }
  if (faceContourPtsVec.size() < 2)
    {
    return;
    }
  // locate the id of the startContourPt inside the face loop
  vtkIdType startPt = -1;
  for (vtkIdType i = 0; i < numFacePoints; i++)
    {
    if (currContourPoint == facePtsVector[i])
      {
      startPt = i;
      break;
      }
    }

  if (startPt < 0 || startPt >= numFacePoints)
    {
    return;
    }

  vtkIdType leftEndPt = -1; // face loop index
  vtkIdType rightEndPt = -1; // face loop index
  vtkIdType leftEndPoint = -1; // point id
  vtkIdType rightEndPoint = -1; // point id
  vtkIdType leftEndPassPositivePoint = 0;
  vtkIdType rightEndPassPositivePoint = 0;
  // search in one direction.
  vtkIdType endPt = startPt - 1;
  for (; endPt != startPt; endPt--)
    {
    if (endPt < 0)
      {
      endPt = numFacePoints - 1;
      if (endPt == startPt)
        {
        break;
        }
      }
    if (pointLabelVec[facePtsVector[endPt]] == -1)//negative point reached. stop
      {
      break;
      }
    else if (pointLabelVec[facePtsVector[endPt]] == 0)//contour pt reached. stop
      {
      leftEndPt = endPt;
      leftEndPoint = facePtsVector[endPt];
      break;
      }
    else
      {
      leftEndPassPositivePoint = 1;
      }
    // positive pt reached. continue.
    }
  
  // check if already loop through the entire face
  if (endPt != startPt)
    {
    vtkIdType prevEndPt = endPt;
    
    // search in the other direction
    for (endPt = startPt + 1; endPt != prevEndPt; endPt++)
      {
      if (endPt > numFacePoints - 1)
        {
        endPt = 0;
        if (endPt == prevEndPt)
          {
          break;
          }
        if (endPt == startPt)
          {
          break;
          }
        }
      if (pointLabelVec[facePtsVector[endPt]] == -1)//negative point reached. stop
        {
        break;
        }
      else if (pointLabelVec[facePtsVector[endPt]] == 0)//contour pt reached. stop
        {
        rightEndPt = endPt;
        rightEndPoint = facePtsVector[endPt];
        break;
        }
      else
        {
        rightEndPassPositivePoint = 1;
        }
      }
    }

  // need to check a special case where startPt, leftEndPoint and rightEndPoint
  // are directly connected or connected by a series of other contour points, 
  // and startPt is at one end of the contour strip. We can check this situation
  // using leftEndPassPositivePoint and leftEndPassPositivePoint. If both are
  // 1, then the three points are not on a contour strip. If both are 0, then
  // startPt is not at one end of the contour strip.
  if (leftEndPoint >= 0 && rightEndPoint >=0 && leftEndPoint != rightEndPoint)
    {
    if (leftEndPassPositivePoint != rightEndPassPositivePoint)
      {
      bool foundNonContourPoint = false;
      for (endPt = leftEndPt - 1; endPt != rightEndPt; endPt--)
        {
        if (endPt < 0)
          {
          endPt = numFacePoints - 1;
          if (endPt == rightEndPt)
            {
            break;
            }
          }
        if (pointLabelVec[facePtsVector[endPt]] != 0)
          {
          foundNonContourPoint = true;
          break;
          }
        }
      if (!foundNonContourPoint)// startPt on one end of the contour strip
        {
        if (leftEndPassPositivePoint)
          {
          leftEndPoint = -1;
          }
        else
          {
          rightEndPoint = -1;
          }
        }
      }
    }
  
  if (leftEndPoint >= 0)
    {
    connectedContourPtsSet.insert(leftEndPoint);
    }
  if (rightEndPoint >= 0)
    {
    connectedContourPtsSet.insert(rightEndPoint);
    }
  for (size_t i = 0; i < faceContourPtsVec.size(); i++)
    {
    if (faceContourPtsVec[i] != leftEndPoint && 
        faceContourPtsVec[i] != rightEndPoint &&
        faceContourPtsVec[i] != currContourPoint)
      {
      unConnectedContourPtsSet.insert(faceContourPtsVec[i]);
      }
    }
549
};
550
551

//----------------------------------------------------------------------------
552
void RemoveIdFromIdToIdVectorMap(vtkIdToIdVectorMapType & map, vtkIdType id)
553
{
554
  vtkIdToIdVectorMapIteratorType mit = map.begin();
555
556
  for (; mit != map.end(); ++mit)
    {
557
    vtkIdVectorType::iterator vit = mit->second.begin();
558
559
560
561
562
563
564
565
566
    for (; vit != mit->second.end(); ++vit)
      {
      if ((*vit) == id)
        {
        mit->second.erase(vit);
        break;
        }
      }
    }
567
};
568
569
570
571
572
573
574
575
576
577
578
579
580

//----------------------------------------------------------------------------
// For each contour point, extract its adjacent faces, then extract other 
// contour points on the same face that can be connected to the current
// points.
// The connected contour points are found by (1) locating the current
// contour point in the face loop, (2) looping through face point: 
//  meet a positive point, keep going. 
//  meet a contour point, store it and stop marching in this direction.
//  meet a negative point, stop marching in this direction.
//  meet the same point from both directions, stop. 
// This loop may find zero, one or two connected contour points.
int  ExtractContourConnectivities(
581
582
583
584
585
586
                 vtkIdToIdVectorMapType & ceMap,
                 vtkIdSetType & cpSet, 
                 vtkIdVectorType & pointLabelVector, 
                 vtkIdToIdVectorMapType & pointToFacesMap, 
                 vtkIdToIdVectorMapType & faceToPointsMap, 
                 vtkIdToIdVectorMapType & faceToContourPointsMap)
587
588
589
590
591
592
593
{
  int maxConnectivity = 0;
  if (cpSet.empty())
    {
    return 0;
    }
  
594
595
596
597
598
  vtkIdSetType contourBranchesSet;
  vtkIdSetType nonContourBranchesSet;
  vtkIdVectorType contourBranchesVector;
  vtkIdSetType::iterator cpSetIt;
  vtkIdToIdVectorMapType::iterator fcpMapIt, fvMapIt, ceMapIt, ceMapIt1;
599
600
601
602
603
604
  for (cpSetIt = cpSet.begin(); cpSetIt != cpSet.end(); /*manual increment*/)
    {
    contourBranchesSet.clear();
    nonContourBranchesSet.clear();
    contourBranchesVector.clear();
    vtkIdType pid = *cpSetIt;
605
    vtkIdVectorType fVector = pointToFacesMap.find(pid)->second;
606
607
608
609
610
611
612
613
614
615
616
    for (size_t i = 0; i < fVector.size(); i++)
      {
      // find adjacent faces that contain contour points
      fcpMapIt = faceToContourPointsMap.find(fVector[i]);
      if (fcpMapIt == faceToContourPointsMap.end())
        {
        continue;
        }
      fvMapIt = faceToPointsMap.find(fVector[i]);
      if (fvMapIt == faceToPointsMap.end())
        {
617
618
        cout << "Cannot find point ids of a face. We should never get "
          "here. Contouring aborted." << endl;
619
620
621
622
623
624
625
626
        return 0;
        }


      // find connected contour points and store them in the set. Notice that
      // some weird topology will classify a point as a connected contour point
      // in one face and a non-connected contour point in some other face. we
      // will extract the union.
627
628
      FindConnectedContourPointsOnFace(
                  fvMapIt->second, fcpMapIt->second, pid, 
629
630
631
632
633
                  pointLabelVector, contourBranchesSet, nonContourBranchesSet);
      }

    if (!contourBranchesSet.empty())
      {
634
      vtkIdSetType::iterator ccpSetIt = contourBranchesSet.begin();
635
636
637
638
639
640
641
642
643
644
645
646
      for (; ccpSetIt != contourBranchesSet.end(); ++ccpSetIt)
        {
        if (nonContourBranchesSet.find(*ccpSetIt) == nonContourBranchesSet.end())
          {
          contourBranchesVector.push_back(*ccpSetIt);
          }
        }
      }

    if (contourBranchesVector.size() >= 2)
      {
      ceMap.insert(
647
        vtkIdToIdVectorPairType(pid, contourBranchesVector));
648
649
650
651
652
653
      ++cpSetIt;
      }
    else // throw away point contour or edge contour.
      {
      if (cpSetIt != cpSet.begin())
        {
654
        vtkIdSetType::iterator tempIt = cpSetIt;
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
        --cpSetIt;
        cpSet.erase(tempIt);
        ++cpSetIt;
        }
      else
        {
        cpSet.erase(cpSetIt);
        cpSetIt = cpSet.begin();
        }
      }
    }
  
  // sanity check, all edges should be listed twice
  for (ceMapIt = ceMap.begin(); ceMapIt != ceMap.end(); ++ceMapIt)
    {
670
    vtkIdVectorType edges = ceMapIt->second;
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
    for (size_t i = 0; i < edges.size(); i++)
      {
      bool foundMatch = false;
      ceMapIt1 = ceMap.find(edges[i]);
      if (ceMapIt1 != ceMap.end())
        {
        for (size_t j = 0; j < ceMapIt1->second.size(); j++)
          {
          if (ceMapIt->first == ceMapIt1->second[j])
            {
            foundMatch = true;
            break;
            }
          }
        }
      if (!foundMatch)
        {
        edges.erase(edges.begin()+i);
        i--;
        }
      }
    ceMapIt->second = edges;
    }

  // clean 0 or 1-connected contour from ceMap
  for (ceMapIt = ceMap.begin(); ceMapIt != ceMap.end(); /*manual increment*/)
    {
    if (ceMapIt->second.size() >= 2)
      {
      ++ceMapIt;
      continue;
      }
      
    cpSetIt = cpSet.find(ceMapIt->first);
    if (cpSetIt != cpSet.end())
      {
      cpSet.erase(cpSetIt);
      }
    
    if (ceMapIt != ceMap.begin())
      {
712
      vtkIdToIdVectorMapType::iterator tempIt = ceMapIt;
713
714
715
716
717
718
719
720
721
722
723
      --ceMapIt;
      ceMap.erase(tempIt);
      ++ceMapIt;
      }
    else
      {
      ceMap.erase(ceMapIt);
      ceMapIt = ceMap.begin();
      }
    }
  
724
  // set maxConnectivity.
725
726
727
728
  for (ceMapIt = ceMap.begin(); ceMapIt != ceMap.end(); ++ceMapIt)
    {
    if (static_cast<int>(ceMapIt->second.size()) > maxConnectivity)
      {
729
      maxConnectivity = static_cast<int>(ceMapIt->second.size());
730
731
732
733
      }
    }

  return maxConnectivity;
734
};
735

736
737
738
739
//----------------------------------------------------------------------------
// Use eigenvalues to determine the dimension of the input contour points.
// This chunk of code is mostly copied from vtkOBBTree::ComputeOBB()
// Function return 0 if input is a single point, 1 if co-linear, 
740
741
742
743
// 2 if co-planar, 3 if 3D. It also returns the center as well as the normal
// (the eigenvector with the smallest eigenvalue) of the input contour pointset.
int CheckContourDimensions(vtkPoints* points, vtkIdType npts, vtkIdType * ptIds, 
                           double * normal, double * center)
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
{
  static const double eigenvalueRatioThresh = 0.001;
  
  if (npts < 3)
    {
    return npts - 1;
    }
  
  vtkIdType i, j;
  double x[3], mean[3], xp[3], *v[3], v0[3], v1[3], v2[3];
  double *a[3], a0[3], a1[3], a2[3], eigValue[3];

  // Compute mean
  mean[0] = mean[1] = mean[2] = 0.0;
  for (i=0; i < npts; i++ )
    {
    points->GetPoint(ptIds[i], x);
    mean[0] += x[0];
    mean[1] += x[1];
    mean[2] += x[2];
    }
  for (i=0; i < 3; i++)
    {
    mean[i] /= npts;
    }

  // Compute covariance matrix
  a[0] = a0; a[1] = a1; a[2] = a2; 
  for (i=0; i < 3; i++)
    {
    a0[i] = a1[i] = a2[i] = 0.0;
    }

  for (j = 0; j < npts; j++ )
    {
    points->GetPoint(ptIds[j], x);
    xp[0] = x[0] - mean[0]; xp[1] = x[1] - mean[1]; xp[2] = x[2] - mean[2];
    for (i = 0; i < 3; i++)
      {
      a0[i] += xp[0] * xp[i];
      a1[i] += xp[1] * xp[i];
      a2[i] += xp[2] * xp[i];
      }
    }//for all points

  for (i=0; i < 3; i++)
    {
    a0[i] /= npts;
    a1[i] /= npts;
    a2[i] /= npts;
    }

  // Extract axes (i.e., eigenvectors) from covariance matrix. 
  v[0] = v0; v[1] = v1; v[2] = v2; 
  vtkMath::Jacobi(a,eigValue,v);
799
  
800
801
802
803
804
805
806
807
808
809
810
  int ret = 3;
  
  if ((eigValue[2] / eigValue[0]) < eigenvalueRatioThresh)
    {
    ret--;
    }
  if ((eigValue[1] / eigValue[0]) < eigenvalueRatioThresh)
    {
    ret--;
    }
  
811
812
  if (normal)
    {
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
    for (i =0; i < 3; i++)
      {
      double norm = vtkMath::Norm(a[i], 3);
      if (norm > 0.000001)
        {
        break;
        }
      }
    if (i < 3)
      {    
      normal[0] = v2[0];
      normal[1] = v2[1];
      normal[2] = v2[2];
      }
    else
      {
      points->GetPoint(ptIds[0], v0);
      points->GetPoint(ptIds[1], v1);
      v0[0] = v0[0] - mean[0];
      v0[1] = v0[1] - mean[1];
      v0[2] = v0[2] - mean[2];
      v1[0] = v1[0] - mean[0];
      v1[1] = v1[1] - mean[1];
      v1[2] = v1[2] - mean[2];
      vtkMath::Normalize(v0);
      vtkMath::Normalize(v1);
      vtkMath::Cross(v0, v1, normal);
      vtkMath::Normalize(normal);
      }
842
843
844
845
846
847
848
849
    }
  if (center)
    {
    center[0] = mean[0];
    center[1] = mean[1];
    center[2] = mean[2];
    }
  
850
  return ret;
851
};
852

853
//----------------------------------------------------------------------------
854
855
856
857
858
859
860
861
862
863
864
// For each contour point, compute the normal (pointing to the positive side),
// then sort the other contour points connected to it, such that the connecting
// edges are ordered contour-clockwise when viewed from the normal direction.

// Input ceMap shows that a contour point (map->first) is connected to a number
// of other contour points (map->second). It does not distinguish boundary 
// edges from internal edges. The following function also update ceMap such that
// a boundary edge a-->b (assuming traversing from the counter-clockwise 
// direction) is only stored once ({a, [b, ...]}). an internal edge a<-->b is 
// stored twice ({a, [b, ...] and {b, [a, ...]}}. 

865
866
867
868
// Current implementation of this function assumes planar contours, we only 
// compute normal once and reuse it for all other contour points.
// TODO: for non-planar cut, need to compute normal for each contour point. We 
// then project edges onto a tangent plane and sort them.
869
870
871
872
void OrderMultiConnectedContourPoints(vtkIdToIdVectorMapType & cpMap,
                                     vtkIdToIdVectorMapType & cpBackupMap,
                                     vtkIdSetType & cpSet,
                                     vtkPoints * points)
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
  double o[3], p[3], x0[3], x1[3], e0[3], e1[3], n[3], nn[3];
  vtkIdSetType::iterator setIt;
  vtkIdVectorType pids;
  for (setIt = cpSet.begin(); setIt != cpSet.end(); ++setIt)
    {
    pids.push_back(*setIt);
    }

  // return if the input contour points are 1D. Note: the function also
  // compute normal n and center c.
  if (CheckContourDimensions(
        points, static_cast<vtkIdType>(pids.size()), &(pids[0]), n, o) < 2)
    {
    return;
    }
  vtkMath::Normalize(n);

  // locate an extreme point in a direction normal to the normal. this
  // extreme point is a convex vertex.
  vtkIdToIdVectorMapType::iterator mapIt = cpMap.begin();
  points->GetPoint(mapIt->first, p);
  e0[0] = p[0] - o[0];
  e0[1] = p[1] - o[1];
  e0[2] = p[2] - o[2];
  vtkMath::Normalize(e0);
  vtkMath::Cross(e0, n, nn);
  vtkMath::Normalize(nn);
  
  double maxDistance = VTK_DOUBLE_MIN;
  vtkIdType maxPid = -1;
  for (; mapIt != cpMap.end(); ++mapIt)
    {
    points->GetPoint(mapIt->first, p);
    e0[0] = p[0] - o[0];
    e0[1] = p[1] - o[1];
    e0[2] = p[2] - o[2];
    double distance = vtkMath::Dot(nn, e0);
    if (distance > maxDistance)
      {
      maxDistance = distance;
      maxPid = mapIt->first;
      }
    }
  
  // Order edges of the contour point contour-clockwise. Note that a boundary 
  // point has two boundary edges. We will remove the incoming boundary edge 
  // and store the outgoing boundary edge at the end (after all internal edges).
  // incoming and outgoing boudnary edges are defined when they are traversed
  // counter-clockwisely.
  std::vector<double> extremePointAngles; // record the angles of extreme point
  vtkIdVectorType edges;
  size_t edgesSize = 0;
926
  const double eps = 0.0000001;
927
928
  for (mapIt = cpMap.begin(); mapIt != cpMap.end(); ++mapIt)
    {
929
930
    edges = mapIt->second;
    edgesSize = edges.size();
931
932
933
934
935
936
937
938
939
940
941
942
943
944
    
    // If the contour point is 2-connected we don't need to order them.
    if (edgesSize >=3 || mapIt->first == maxPid)
      {
      // get the current first edge
      points->GetPoint(mapIt->first, p);
      points->GetPoint(edges[0], x0);
      e0[0] = x0[0] - p[0];
      e0[1] = x0[1] - p[1];
      e0[2] = x0[2] - p[2];
      vtkMath::Normalize(e0);
      vtkMath::Cross(e0, n, x0);
      vtkMath::Cross(n, x0, e0);
      vtkMath::Normalize(e0);
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
      // compute the angles from other edges to the first edge
      std::vector<double> angles;
      angles.push_back(0);
      const double maxDotProduct = 0.95;
      for (size_t i = 1; i < edgesSize; i++)
        {
        points->GetPoint(edges[i], x1);
        e1[0] = x1[0] - p[0];
        e1[1] = x1[1] - p[1];
        e1[2] = x1[2] - p[2];
        vtkMath::Normalize(e1);
        vtkMath::Cross(e1, n, x1);
        vtkMath::Cross(n, x1, e1);
        vtkMath::Normalize(e1);
        double dotproduct = vtkMath::Dot(e0, e1);
        double angle = acos(dotproduct);
        if (dotproduct < maxDotProduct && dotproduct > -maxDotProduct)
          {
          vtkMath::Cross(e0, e1, nn);
          if (vtkMath::Dot(n, nn) < 0)
            {
            angle = 2.0*vtkMath::Pi() - angle;
            }
          }
        else if (dotproduct > maxDotProduct)
          {
          vtkMath::Cross(e0, n, nn);
          angle = acos(vtkMath::Dot(nn, e1)) - vtkMath::Pi()/2.0;
          }
        else if (dotproduct < -maxDotProduct)
          {
          vtkMath::Cross(n, e0, nn);
          angle = acos(vtkMath::Dot(nn, e1)) + vtkMath::Pi()/2.0;
          }
980
        if (angle < -eps)
981
          {
982
          angle += 2.0*vtkMath::Pi();
983
          }
984
        if (angle > 2.0*vtkMath::Pi()+eps)
985
          {
986
          angle -= 2.0*vtkMath::Pi();
987
          }
988
989
990
991
992
993
994
995
996
997
998
999
1000
        angles.push_back(angle);
        }
      
      // sort edges
      for (size_t i = 1; i < edgesSize-1; i++)
        {
        for (size_t j = i+1; j < edgesSize; j++)
          {
          if (angles[i] > angles[j])
            {
            vtkIdType temp = edges[i];
            edges[i] = edges[j];
            edges[j] = temp;