]> Creatis software - creaVtk.git/blob - bbtk_creaVtk_PKG/src/bbcreaVtkCreateMeshFromPoints.cxx
#3510 Bug windows CreateMeshFromPoints box
[creaVtk.git] / bbtk_creaVtk_PKG / src / bbcreaVtkCreateMeshFromPoints.cxx
1 //===== 
2 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
3 //===== 
4 #include "bbcreaVtkCreateMeshFromPoints.h"
5 #include "bbcreaVtkPackage.h"
6
7 #include "vtkTriangleStrip.h"
8 #include "vtkTriangle.h"
9 #include <vtkMath.h>
10
11 namespace bbcreaVtk
12 {
13
14 BBTK_ADD_BLACK_BOX_TO_PACKAGE(creaVtk,CreateMeshFromPoints)
15 BBTK_BLACK_BOX_IMPLEMENTATION(CreateMeshFromPoints,bbtk::AtomicBlackBox);
16 //===== 
17 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
18 //===== 
19 void CreateMeshFromPoints::Process()
20 {
21
22 // THE MAIN PROCESSING METHOD BODY
23 //   Here we simply set the input 'In' value to the output 'Out'
24 //   And print out the output value
25 // INPUT/OUTPUT ACCESSORS ARE OF THE FORM :
26 //    void bbSet{Input|Output}NAME(const TYPE&)
27 //    const TYPE& bbGet{Input|Output}NAME() const 
28 //    Where :
29 //    * NAME is the name of the input/output
30 //      (the one provided in the attribute 'name' of the tag 'input')
31 //    * TYPE is the C++ type of the input/output
32 //      (the one provided in the attribute 'type' of the tag 'input')
33
34 //    bbSetOutputOut( bbGetInputIn() );
35 //    std::cout << "Output value = " <<bbGetOutputOut() << std::endl;
36
37                 std::vector<double> lstX                = bbGetInputLstX();
38                 std::vector<double> lstY                = bbGetInputLstY();
39                 std::vector<double> lstZ                = bbGetInputLstZ();
40                 std::vector<int> lstIndexs              = bbGetInputLstIndexs();
41                 double pointsCentroid[3];
42                 if ( (lstIndexs.size()<1) || (lstX.size()==0) || (lstX.size()!=lstY.size()) || (lstY.size()!=lstZ.size()) )
43                 {
44                         printf("Warning! CreateMeshFromPoints::Process: List of points X Y Z  and LstIndexes is not correct\n");
45                         bbSetOutputOut(NULL);
46                 } else  {
47                         int ii,sizeSegment1,sizeSegment2;
48                         int endSegment;
49 //                      vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
50                         if (points!=NULL) points->Delete();
51                         points = vtkPoints::New();
52                         int i,sizeLstX  =       lstX.size();
53                         for (i=0;i<sizeLstX;i++)
54                         {
55                                 points->InsertNextPoint(lstX[i],lstY[i],lstZ[i]);
56                                 pointsCentroid[0] += lstX[i];
57                                 pointsCentroid[1] += lstY[i];
58                                 pointsCentroid[2] += lstZ[i];
59                         } // for i
60                         pointsCentroid[0] /= sizeLstX;
61                         pointsCentroid[1] /= sizeLstX;
62                         pointsCentroid[2] /= sizeLstX;
63                         
64                         if ((bbGetInputCloseSurface()==true)  && (lstIndexs.size()>=2) )
65             {
66                 //Correct surface normals if needed
67                 double pointSurf1[3], pointSurf2[3], pointSurf3[3];
68                 double vect1[3], vect2[3];
69                 double surfNormal[3], vectorCenter[3];
70                 double dotNormalSurf = 0;
71                 for(int pIndex = 0; pIndex < lstIndexs[0]-1; pIndex++)
72                 {
73                         pointSurf1[0] = lstX[pIndex];
74                         pointSurf1[1] = lstY[pIndex];
75                         pointSurf1[2] = lstZ[pIndex];
76                         vtkMath::Subtract(pointsCentroid, pointSurf1, vectorCenter);
77                         pointSurf2[0] = lstX[pIndex+lstIndexs[1]];
78                         pointSurf2[1] = lstY[pIndex+lstIndexs[1]];
79                         pointSurf2[2] = lstZ[pIndex+lstIndexs[1]];
80                         pointSurf3[0] = lstX[pIndex+1];
81                         pointSurf3[1] = lstY[pIndex+1];
82                         pointSurf3[2] = lstZ[pIndex+1];
83                         vtkMath::Subtract(pointSurf2, pointSurf1, vect1);
84                         vtkMath::Subtract(pointSurf3, pointSurf1, vect2);
85                         vtkMath::Cross(vect1, vect2, surfNormal);
86                         dotNormalSurf += vtkMath::Dot(surfNormal, vectorCenter);
87                 } // for pIndex
88                                 if(dotNormalSurf > 0){
89                                         points->Delete();
90                                         points = vtkPoints::New();
91                                         for(int splineI = 0; splineI < lstIndexs.size(); splineI++){
92                                                 for (i=lstIndexs[splineI]-1; i >= 0;i--)
93                                                 {
94                                                         points->InsertNextPoint(lstX[splineI*lstIndexs[0]+i],lstY[splineI*lstIndexs[0]+i],lstZ[splineI*lstIndexs[0]+i]);
95                                                 } // for i
96                                         } // for splineI
97                                 } // if dotNormalSurf
98                         }
99                         //
100                         
101 //                      vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
102                         if (cells!=NULL) cells->Delete();
103                         cells = vtkCellArray::New();
104                         int maxElements;
105                         int maxSegment1,maxSegment2;
106                         int iSeg1,iSeg2;
107                         int iGeneral    =       0;
108                         int     sizeLstIdexes=lstIndexs.size();
109                         for (i=0; i<sizeLstIdexes-1; i++ )
110                         {
111                                 sizeSegment1 = lstIndexs[i];
112                                 sizeSegment2 = lstIndexs[i+1];
113                                 vtkSmartPointer<vtkTriangleStrip> triangleStrip = vtkSmartPointer<vtkTriangleStrip>::New();
114                                 triangleStrip->GetPointIds()->SetNumberOfIds(sizeSegment1+sizeSegment2);
115                                 maxElements=sizeSegment1;
116                                 if (maxElements<sizeSegment2) maxElements=sizeSegment2;
117                                 maxSegment1     = iGeneral+sizeSegment1;
118                                 maxSegment2     = iGeneral+sizeSegment1+sizeSegment2;
119                                 iSeg1           = iGeneral;
120                                 iSeg2           = iGeneral+sizeSegment1;
121                                 for (ii=0; ii<maxElements; ii++)
122                                 {
123                                         triangleStrip->GetPointIds()->SetId(ii*2  ,iSeg1);
124                                         triangleStrip->GetPointIds()->SetId(ii*2+1,iSeg2);
125                                         iSeg1++;
126                                         iSeg2++;
127                         if (iSeg1>=maxSegment1) { iSeg1=maxSegment1-1; }
128                         if (iSeg2>=maxSegment2) { iSeg2=maxSegment2-1; }
129                                 } // for ii 
130                                 iGeneral=iGeneral+sizeSegment1;
131                                 cells->InsertNextCell(triangleStrip);
132                         } //for  LstIndexs
133                         
134                         
135                         if(bbGetInputCloseSurface())
136                         {
137                                 int lastId1 = lstIndexs[0]-1;
138                                 int lastId2 = sizeLstX - 1;
139                                 int firstId2 = sizeLstX - lstIndexs[sizeLstIdexes - 1];
140                                 bool face1open = std::fabs(lstX[0] - lstX[lastId1]) > 0.0001 && std::fabs(lstY[0] - lstY[lastId1]) > 0.0001 && std::fabs(lstZ[0] - lstZ[lastId1]) > 0.0001;
141                                 bool face2open = std::fabs(lstX[firstId2] - lstX[lastId2]) > 0.0001 && std::fabs(lstY[firstId2] - lstY[lastId2]) > 0.0001 && std::fabs(lstZ[firstId2] - lstZ[lastId2]) > 0.0001;
142                                 
143                                 bool altFace1open = std::fabs(lstX[0] - lstX[firstId2]) > 0.0001 && std::fabs(lstY[0] - lstY[firstId2]) > 0.0001 && std::fabs(lstZ[0] - lstZ[firstId2]) > 0.0001;
144                                 bool altFace2open = std::fabs(lstX[lastId1] - lstX[lastId2]) > 0.0001 && std::fabs(lstY[lastId1] - lstY[lastId2]) > 0.0001 && std::fabs(lstZ[lastId1] - lstZ[lastId2]) > 0.0001;
145
146                                 //false = Open Contour
147                                 //true = Closed Contour
148                                 if(!face1open && !face2open)
149                                 {
150 //                                      isClosedCont = true;
151                                         CloseContourSides(lstIndexs, true, true);
152                                 }
153                                 else if(!altFace1open && !altFace2open)
154                                 {
155 //                                      isClosedCont = true;
156                                         CloseContourSides(lstIndexs, false, true);
157                                 }
158                                 else{
159                                         CloseOpenContourSurface(lstIndexs);
160                                 }
161                         }
162                     
163 //                      vtkPolyData *polydata = vtkPolyData::New();
164                         if (polydata!=NULL) polydata->Delete();
165                         polydata = vtkPolyData::New();
166                         polydata->SetPoints(points);
167                         polydata->SetStrips(cells);
168 //                      vtkCleanPolyData *clean=vtkCleanPolyData::New();
169                         if (clean!=NULL) clean->Delete();
170                         clean = vtkCleanPolyData::New();
171                         clean->SetInputData(polydata);
172                         clean->Update();
173 //                      vtkTriangleFilter *triangle = vtkTriangleFilter::New();
174                         if (triangle!=NULL) triangle->Delete();
175                         triangle = vtkTriangleFilter::New();
176                         triangle->SetInputData( clean->GetOutput() );
177                         triangle->Update();
178             bbSetOutputOut( triangle->GetOutput() );
179             //            bbSetOutputOut( clean->GetOutput() );
180                 }// if listXYZ size
181                 //printf("PG CreateMeshFromPoints::Process: End\n");
182 }
183 /**
184 * Closes the sides of the contour
185 * iterates in one way or the other, depending on the order of the points and calculated vectors.
186 * uPointOrder: Points are order in a U shape
187 * lstIndexs: number of points on each spline
188 */
189 void CreateMeshFromPoints::CloseContourSides(std::vector<int> lstIndexs, bool uPointOrder, bool isClosedCont){
190         int     sizeLstIdexes = lstIndexs.size();
191         int sizePoints = bbGetInputLstX().size();
192
193         int firstIndex, end, centroidId, numPointsFace, contraryId;
194         int increment = uPointOrder?1:sizeLstIdexes;
195         double centroid[3];
196         int numProcessFaces = sizeLstIdexes > 1?2:1;
197         for(int facesIdx = 0; facesIdx < numProcessFaces; facesIdx++){
198                 std::fill(std::begin(centroid), std::end(centroid), 0);
199                 if(facesIdx == 0)
200                 {
201                         firstIndex = 0;
202                         numPointsFace = uPointOrder?lstIndexs[0]: sizeLstIdexes;
203                         end = uPointOrder?firstIndex + numPointsFace:sizePoints - lstIndexs[sizeLstIdexes - 1] + 1;
204                         contraryId = sizePoints-1;
205                 }else{
206                         firstIndex = uPointOrder?sizePoints - lstIndexs[sizeLstIdexes-1]:lstIndexs[0]-1;
207                         numPointsFace = uPointOrder?lstIndexs[sizeLstIdexes-1]:sizeLstIdexes;
208                         end = uPointOrder?firstIndex + numPointsFace:sizePoints;
209                         contraryId = 0;
210                 }
211                 if(numPointsFace > 1)
212                 {
213                         bool validCentroid = CalcValidCentroid(centroid, firstIndex, end, increment, numPointsFace);
214                         if(validCentroid)
215                         {
216                                 bool normalOrder    = isPointingCorrectly(firstIndex, firstIndex+increment, centroid, contraryId);
217                                 centroidId          = points->InsertNextPoint(centroid[0], centroid[1], centroid[2]);
218                                 //vtkSmartPointer<vtkTriangleStrip> triangleStrip = vtkSmartPointer<vtkTriangleStrip>::New();
219                                 //triangleStrip->GetPointIds()->SetNumberOfIds(numPointsFace*2 + (!isClosedCont?2:0));
220                                 //int triangleIndex = 0;
221                                 if( normalOrder )
222                 {
223                         int initial = firstIndex;
224                         for(int index = initial; index < end; index+=increment){
225                                                 if(index+increment >= end && !isClosedCont){
226                                                         vtkNew<vtkTriangle> triangle;
227                                                         triangle->GetPointIds()->SetId(0, index);
228                                                         triangle->GetPointIds()->SetId(1, initial);
229                                                         triangle->GetPointIds()->SetId(2, centroidId);
230                                                         cells->InsertNextCell(triangle);
231                                                 }else if(index+increment < end){
232                                                         vtkNew<vtkTriangle> triangle;
233                                                         triangle->GetPointIds()->SetId(0, index);
234                                                         triangle->GetPointIds()->SetId(1, index+increment);
235                                                         triangle->GetPointIds()->SetId(2, centroidId);
236                                                         cells->InsertNextCell(triangle);
237                                                 }
238                                                 /*
239                                                 triangleStrip->GetPointIds()->SetId(triangleIndex,index);
240                                                 triangleStrip->GetPointIds()->SetId(triangleIndex+1,centroidId);//1
241                                                 if(index+increment >= end && !isClosedCont){
242                                                         triangleStrip->GetPointIds()->SetId(triangleIndex+2,initial);//2
243                                                         triangleStrip->GetPointIds()->SetId(triangleIndex+3,centroidId);//3
244                                                 }
245                                                 triangleIndex+=2;
246                                                 */
247                                         }
248                                         //cells->InsertNextCell(triangleStrip);
249                                 } else {
250                                         int initial = firstIndex-1;
251                                         int triangleStripStart = end-1;
252                                         for(int index = triangleStripStart; index > initial; index-=increment){ 
253                                                 if(index-increment <= initial && !isClosedCont){
254                                                         vtkNew<vtkTriangle> triangle;
255                                                         triangle->GetPointIds()->SetId(0, index);
256                                                         triangle->GetPointIds()->SetId(1, triangleStripStart);
257                                                         triangle->GetPointIds()->SetId(2, centroidId);
258                                                         cells->InsertNextCell(triangle);
259                                                 }else if(index-increment > initial){
260                                                         vtkNew<vtkTriangle> triangle;
261                                                         triangle->GetPointIds()->SetId(0, index);
262                                                         triangle->GetPointIds()->SetId(1, index-increment);
263                                                         triangle->GetPointIds()->SetId(2, centroidId);
264                                                         cells->InsertNextCell(triangle);
265                                                 }
266                                         }
267                                 }//if normalOrder
268                         }//if validCentroid
269                 }//if numPointsFace
270         }//for facesIdx
271
272 }
273
274 /**
275 * Checks if the normal from firstPointId, secPointId and centroid points away 
276 * from the vector centroid to contrPointId.
277 * Used to check that the order used to create the new polygons is correct.
278 */
279 bool CreateMeshFromPoints::isPointingCorrectly( int firstPointId, int secPointId, double(&centroid)[3], int contrPointId) {
280
281         double firstPoint[3], secPoint[3], contrPoint[3];
282         points->GetPoint(firstPointId, firstPoint);
283         points->GetPoint(secPointId, secPoint);
284         
285         double firstVect[3], secVect[3], normal[3], contrVect[3];
286         
287         vtkMath::Subtract(firstPoint, centroid, firstVect);
288         vtkMath::Subtract(secPoint, centroid, secVect);
289         
290         points->GetPoint(contrPointId, contrPoint);
291         vtkMath::Subtract(contrPoint, centroid, contrVect);
292         
293         vtkMath::Cross(firstVect, secVect, normal);
294         double dotCalc;
295         dotCalc = vtkMath::Dot(normal, contrVect);
296         
297         return dotCalc<0;
298 }
299
300 /**
301 * Checks if the order of the points represent a curved spline (U shape) or the points resemble a straight spline.
302 * Now it checks the angle between each point and the vector that goes from the last point to the first.
303 *
304 * Previous version checked the curvature between 3 points in the spline, but this created problems when the straight lines
305 * had curves in the middle, increasing the curvature although they are not in the U shape.
306 */
307 bool CreateMeshFromPoints::CheckLinePointOrder(){
308         int sizePoints = bbGetInputLstX().size();
309         std::vector<int> lstIndexs = bbGetInputLstIndexs();
310         double point1[3], point2[3], point3[3];
311         double center[3];
312         double firstAngleSum = 0;
313         double secondAngleSum = 0;
314
315         points->GetPoint(0, point1);
316         points->GetPoint((lstIndexs[0]-1), point3);
317         double firstVect[3];
318         double secVect[3];
319         vtkMath::Subtract(point3, point1, firstVect);
320         for(int i = 0; i < lstIndexs[0]; i++){
321                 points->GetPoint(i, point2);
322                 vtkMath::Subtract(point2, point1, secVect);
323                 firstAngleSum += vtkMath::SignedAngleBetweenVectors(firstVect, secVect, firstVect);
324         }
325         points->GetPoint((sizePoints-lstIndexs[0]), point3);
326         vtkMath::Subtract(point3, point1, firstVect);
327         for(int i = 0; i < sizePoints; i+=lstIndexs.size()){
328                 points->GetPoint(i, point2);
329                 vtkMath::Subtract(point2, point1, secVect);
330                 secondAngleSum += vtkMath::SignedAngleBetweenVectors(firstVect, secVect, firstVect);
331         }
332
333         return firstAngleSum < secondAngleSum;
334 }
335
336 /**
337 * Closes an open contour
338 * lstIndexs: number of points on each spline
339 */
340 void CreateMeshFromPoints::CloseOpenContourSurface(std::vector<int> lstIndexs){
341         bool linePointOrder = CheckLinePointOrder();
342         CloseContourSides(lstIndexs, !linePointOrder, false);
343         CloseContourBottom(!linePointOrder);
344 }
345
346 /**
347 * Calculates centroid and checks if points are collinear.
348 * centroid: array to store calculation
349 * start: start index of points to use
350 * end: end index of points to use
351 * increment: increment to be used in point iteration
352 * numPoints: number of points used to calculate the centroid.
353 * Returns a bool indicating the validity of the centroid calculated.
354 * False = invalid centroid = all points are the same.
355 */
356 bool CreateMeshFromPoints::CalcValidCentroid(double(&centroid)[3], int start, int end, int increment, int numPoints){
357         double currPoint[3] = {}, prevPoint[3] = {}, middlePoint[3] = {}, firstPoint[3] = {};
358         double vector1[3], vector2[3];
359         bool samePoint = true;
360         int splineMidPoint = numPoints/2;
361         bool collinear = true;
362
363         points->GetPoint(start, firstPoint);
364         points->GetPoint(splineMidPoint, middlePoint);
365         vtkMath::Subtract(middlePoint, firstPoint, vector1);
366
367         for(int i = start; i < end; i+=increment){
368                 points->GetPoint(i, currPoint);
369                 if(samePoint && i > start && (currPoint[0] != prevPoint[0] || currPoint[1] != prevPoint[1] || currPoint[2] != prevPoint[2])){
370                         samePoint = false;
371                 }
372
373                 vtkMath::Subtract(currPoint, firstPoint, vector2);
374                 double angle = vtkMath::AngleBetweenVectors(vector1, vector2);
375                 if(angle > 0.0001 && collinear){
376                         collinear = false;
377                 }
378                 
379                 centroid[0] += currPoint[0];
380                 centroid[1] += currPoint[1];
381                 centroid[2] += currPoint[2];
382                 std::copy(std::begin(currPoint), std::end(currPoint), prevPoint);
383         }
384         
385         centroid[0] /= numPoints;
386         centroid[1] /= numPoints;
387         centroid[2] /= numPoints;
388         
389         return !samePoint && !collinear;
390 }
391
392 /**
393 * Closes the bottom of the given countour.
394 * Should only be used when its an open contour.
395 * uPointOrder: points are ordered in U shape
396 */
397 void CreateMeshFromPoints::CloseContourBottom(bool uPointOrder){
398         std::vector<int> lstIndexs = bbGetInputLstIndexs();
399         int sizeLstIdexes = lstIndexs.size();
400         int sizeLstX = bbGetInputLstX().size();
401         
402         vtkSmartPointer<vtkTriangleStrip> triangleStripBottom = vtkSmartPointer<vtkTriangleStrip>::New();
403         triangleStripBottom->GetPointIds()->SetNumberOfIds(sizeLstIdexes*2);
404         
405         double originPoint[3];
406         points->GetPoint(0, originPoint);
407         int middleMeshPoint = uPointOrder?lstIndexs[0]/2:lstIndexs[0]*sizeLstIdexes/2;
408         
409         bool normalOrder = isPointingCorrectly(uPointOrder?lstIndexs[0]-1:sizeLstX-lstIndexs[0], uPointOrder?lstIndexs[0]:1, originPoint, middleMeshPoint);
410         
411         int triangleIndex = 0, currentId = 0, nextId = 0;
412         for(int splineIndex = 0; splineIndex < sizeLstIdexes;splineIndex++){
413                 nextId = uPointOrder?currentId + lstIndexs[splineIndex] - 1:sizeLstX - sizeLstIdexes + splineIndex;
414                 if(normalOrder)
415                 {
416                         triangleStripBottom->GetPointIds()->SetId(triangleIndex, currentId);
417                         triangleStripBottom->GetPointIds()->SetId(triangleIndex+1, nextId);
418                 }
419                 else{
420                         triangleStripBottom->GetPointIds()->SetId(triangleIndex, nextId);
421                         triangleStripBottom->GetPointIds()->SetId(triangleIndex+1, currentId);
422                 }
423                 currentId = uPointOrder?nextId + 1: splineIndex+1;
424                 triangleIndex+=2;
425         }
426         cells->InsertNextCell(triangleStripBottom);
427 }
428
429 //===== 
430 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
431 //===== 
432 void CreateMeshFromPoints::bbUserSetDefaultValues()
433 {
434
435 //  SET HERE THE DEFAULT INPUT/OUTPUT VALUES OF YOUR BOX 
436 //    Here we initialize the input 'In' to 0
437 //   bbSetInputIn(0);
438         bbSetInputCloseSurface(false);
439         points          = NULL;
440         cells           = NULL;
441         polydata        = NULL;
442         clean           = NULL;
443         triangle        = NULL;
444 }
445 //===== 
446 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
447 //===== 
448 void CreateMeshFromPoints::bbUserInitializeProcessing()
449 {
450
451 //  THE INITIALIZATION METHOD BODY :
452 //    Here does nothing 
453 //    but this is where you should allocate the internal/output pointers 
454 //    if any 
455
456   
457 }
458 //===== 
459 // Before editing this file, make sure it's a file of your own (i.e.: it wasn't generated from xml description; if so : your modifications will be lost)
460 //===== 
461 void CreateMeshFromPoints::bbUserFinalizeProcessing()
462 {
463
464 //  THE FINALIZATION METHOD BODY :
465 //    Here does nothing 
466 //    but this is where you should desallocate the internal/output pointers 
467 //    if any
468   
469 }
470 }
471 // EO namespace bbcreaVtk
472
473