VMTK
Loading...
Searching...
No Matches
vtkvmtkConcaveAnnularCapPolyData.cxx
Go to the documentation of this file.
1/*=========================================================================
2
3Program: VMTK
4Module: $RCSfile: vtkvmtkConcaveAnnularCapPolyData.cxx,v $
5Language: C++
6Date: $Date: 2012/09/19 $
7Version: $Revision: 1.0 $
8
9 Copyright (c) Luca Antiga, David Steinman. All rights reserved.
10 See LICENSE file for details.
11
12 Portions of this code are covered under the VTK copyright.
13 See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm
14 for details.
15
16 This software is distributed WITHOUT ANY WARRANTY; without even
17 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
18 PURPOSE. See the above copyright notices for more information.
19
20 Note: this class was contributed by
21 Martin Sandve Alnaes
22 Simula Research Laboratory
23 Based on vtkvmtkAnnularCapPolyData by Tangui Morvan.
24
25=========================================================================*/
26
30#include "vtkNew.h"
32#include "vtkPolyData.h"
33#include "vtkCellArray.h"
34#include "vtkPointData.h"
35#include "vtkCellData.h"
36#include "vtkPolygon.h"
37#include "vtkPolyLine.h"
38#include "vtkIdTypeArray.h"
39#include "vtkIntArray.h"
40#include "vtkMath.h"
41#include "vtkInformation.h"
42#include "vtkInformationVector.h"
43#include "vtkObjectFactory.h"
44#include "vtkSmartPointer.h"
45#include "vtkVersion.h"
46
47#include <iostream>
48#include <limits>
49
50
52
53namespace {
54void info(const std::string & s)
55{
56 std::cout << s << std::endl;
57}
58
59void cross_diff(const double start[3], const double forward[3], const double center[3], double cross[3])
60{
61 double vectorToStart[3] = { start[0] - center[0],
62 start[1] - center[1],
63 start[2] - center[2] };
64 double vectorToForward[3] = { forward[0] - center[0],
65 forward[1] - center[1],
66 forward[2] - center[2] };
67 vtkMath::Cross(vectorToStart, vectorToForward, cross);
68}
69}
70
80
82{
83 if (this->CellEntityIdsArrayName)
84 {
85 delete[] this->CellEntityIdsArrayName;
86 this->CellEntityIdsArrayName = NULL;
87 }
88 if (this->BoundaryIds)
89 {
90 this->BoundaryIds->Delete();
91 this->BoundaryIds = NULL;
92 }
93
96
97 if (this->BoundaryCellEntityIds)
98 {
99 this->BoundaryCellEntityIds->Delete();
100 this->BoundaryCellEntityIds = NULL;
101 }
102}
103
104#include <vector>
105#include <utility>
106using std::vector;
107using std::pair;
108using std::make_pair;
109typedef pair<vtkIdType,vtkIdType> IdPair;
110
111vector<IdPair> build_closest_pairs(vtkSmartPointer<vtkPoints> barycenters, vtkIdList* boundaryIds)
112{
113 int numberOfBoundaries = barycenters->GetNumberOfPoints();
114
115 vector<IdPair> pairs;
116
117 // Allocate array for marking visited boundaries
118 vector<bool> visited(numberOfBoundaries);
119 if (boundaryIds)
120 {
121 // Skip ids not in boundaryIds list
122 for (int i=0; i<numberOfBoundaries; i++)
123 {
124 visited[i] = true;
125 }
126 for (int i=0; i<boundaryIds->GetNumberOfIds(); i++)
127 {
128 visited[boundaryIds->GetId(i)] = false;
129 }
130 }
131 else
132 {
133 // Skip nothing
134 for (int i=0; i<numberOfBoundaries; i++)
135 {
136 visited[i] = false;
137 }
138 }
139
140 // Find the closest pairs of boundaries by comparing barycenter distances
141 for (int i=0; i<numberOfBoundaries; i++)
142 {
143 if (visited[i])
144 {
145 continue;
146 }
147 double barycenter[3];
148 barycenters->GetPoint(i, barycenter);
149
150 // Find which boundary j is closest to boundary i
151 double minBarycenterDistance2 = std::numeric_limits<double>::max();
152 vtkIdType closest = -1;
153 for (int j=i+1; j<numberOfBoundaries; j++)
154 {
155 if (visited[j])
156 {
157 continue;
158 }
159
160 // Fetch barycenter j
161 double currentBarycenter[3];
162 barycenters->GetPoint(j, currentBarycenter);
163
164 // Pick boundary j if the distance to boundary i is the smallest so far
165 double distance2 = vtkMath::Distance2BetweenPoints(barycenter,currentBarycenter);
166 if (distance2 < minBarycenterDistance2)
167 {
168 minBarycenterDistance2 = distance2;
169 closest = j;
170 }
171 }
172
173 // Mark as visited and add pair
174 //std::cout << "i, closest = " << i << ", " << closest << std::endl;
175 visited[i] = true;
176 visited[closest] = true;
177 pairs.push_back(make_pair(i, closest));
178 }
179 return pairs;
180}
181
182IdPair find_closest_points(vtkPolyData * points, vtkSmartPointer<vtkIdList> pointIds0, vtkSmartPointer<vtkIdList> pointIds1)
183{
184 vtkIdType i0 = -1;
185 vtkIdType i1 = -1;
186 double minPointDistance2 = std::numeric_limits<double>::max();
187 int n0 = pointIds0->GetNumberOfIds();
188 int n1 = pointIds1->GetNumberOfIds();
189 for (int j0=0; j0<n0; j0++)
190 {
191 double point0[3];
192 points->GetPoint(pointIds0->GetId(j0), point0);
193 for (int j1=0; j1<n1; j1++)
194 {
195 double point1[3];
196 points->GetPoint(pointIds1->GetId(j1), point1);
197 double distance2 = vtkMath::Distance2BetweenPoints(point0, point1);
198 if (distance2 < minPointDistance2)
199 {
200 i0 = j0;
201 i1 = j1;
202 minPointDistance2 = distance2;
203 }
204 }
205 }
206 return make_pair(i0, i1);
207}
208
210 vtkInformation *vtkNotUsed(request),
211 vtkInformationVector **inputVector,
212 vtkInformationVector *outputVector)
213{
214 // Administrative data type wrestling
215 vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
216 vtkInformation *outInfo = outputVector->GetInformationObject(0);
217
218 vtkPolyData *input = vtkPolyData::SafeDownCast(
219 inInfo->Get(vtkDataObject::DATA_OBJECT()));
220 vtkPolyData *output = vtkPolyData::SafeDownCast(
221 outInfo->Get(vtkDataObject::DATA_OBJECT()));
222
223 // Minimal check that we get at least some data
224 if ( input->GetNumberOfPoints() < 6 )
225 {
226 vtkErrorMacro(<< "Error: too few input points.");
227 return 1;
228 }
229 input->BuildLinks();
230
231 // Allocate output objects
232 vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New();
233 newPoints->DeepCopy(input->GetPoints());
234 vtkSmartPointer<vtkCellArray> newPolys = vtkSmartPointer<vtkCellArray>::New();
235 newPolys->DeepCopy(input->GetPolys());
236
237 // Mark cells if we have a nonempty name
238 bool markCells = this->CellEntityIdsArrayName && this->CellEntityIdsArrayName[0];
239 vtkSmartPointer<vtkIntArray> cellEntityIdsArray;
240 if (markCells)
241 {
242 cellEntityIdsArray = vtkSmartPointer<vtkIntArray>::New();
243 cellEntityIdsArray->SetName(this->CellEntityIdsArrayName);
244 if (input->GetCellData()->GetArray(this->CellEntityIdsArrayName))
245 {
246 cellEntityIdsArray->DeepCopy(input->GetCellData()->GetArray(this->CellEntityIdsArrayName));
247 }
248 else
249 {
250 cellEntityIdsArray->SetNumberOfTuples(newPolys->GetNumberOfCells());
251 cellEntityIdsArray->FillComponent(0,static_cast<double>(this->CellEntityIdOffset));
252 }
253 }
254
255 // Extract all boundaries (polylines) from input mesh
256 info("Finding boundaries of input surface...");
257 // The boundaries either come from the labels the input already carries, which are the same
258 // boundaries in the same order every other filter reading those labels sees, or they are
259 // extracted here as they always were.
260 vtkNew<vtkPolyData> boundariesData;
261 vtkNew<vtkIdList> boundaryLabels;
262 bool useBoundaryLabels = vtkvmtkBoundaryLabels::GetOrExtractBoundaries(
263 input,this->BoundaryLabelsArrayName,this->BoundaryPointOrderArrayName,boundariesData,boundaryLabels,this);
264 vtkPolyData* boundaries = boundariesData;
265
266 int numberOfBoundaries = boundaries->GetNumberOfCells();
267 std::cout << "Found " << numberOfBoundaries << " boundaries." << std::endl;
268
269 // Compute barycenters for all boundaries
270 info("Computing boundary barycenters...");
271 vtkSmartPointer<vtkPoints> barycenters = vtkSmartPointer<vtkPoints>::New();
272 barycenters->SetNumberOfPoints(numberOfBoundaries);
273 for (int i=0; i<numberOfBoundaries; i++)
274 {
275 double barycenter[3];
276 vtkvmtkBoundaryReferenceSystems::ComputeBoundaryBarycenter(boundaries->GetCell(i)->GetPoints(), barycenter);
277 barycenters->SetPoint(i, barycenter);
278 }
279
280 // Build pairs of boundaries from closest barycenter pairs, limited to list of input ids if any
281 info("Pairing boundaries...");
282 if ( (this->BoundaryIds && this->BoundaryIds->GetNumberOfIds() % 2)
283 || (!this->BoundaryIds && numberOfBoundaries % 2) )
284 {
285 vtkErrorMacro(<< "Error: the number of boundaries must be even.");
286 }
287 // build_closest_pairs() selects by boundary index; with the labels in use the caller's
288 // BoundaryIds name labels, so they are translated to indices here.
289 vtkNew<vtkIdList> boundaryIndicesToUse;
290 vtkIdList* boundaryIndexFilter = this->BoundaryIds;
291 if (this->BoundaryIds && useBoundaryLabels)
292 {
293 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
294 {
295 if (this->BoundaryIds->IsId(boundaryLabels->GetId(boundaryIndex)) != -1)
296 {
297 boundaryIndicesToUse->InsertNextId(boundaryIndex);
298 }
299 }
300 boundaryIndexFilter = boundaryIndicesToUse;
301 }
302 vector<IdPair> boundaryPairs = build_closest_pairs(barycenters, boundaryIndexFilter);
303
304 // Loop over all boundary pairings uniquely
305 for (size_t pairingCount=0; pairingCount<boundaryPairs.size(); ++pairingCount)
306 {
307 vtkIdType i0 = boundaryPairs[pairingCount].first;
308 vtkIdType i1 = boundaryPairs[pairingCount].second;
309
310 // These are point ids for all boundaries globally, pointing into global vertex array
311 info("Finding boundary point ids...");
312 vtkIdTypeArray * boundaryPointIdsArray = vtkIdTypeArray::SafeDownCast(boundaries->GetPointData()->GetScalars());
313
314 // Collect (global!) point ids for boundary 0 in current pairing into a contiguous array
315 vtkPolyLine* boundary0 = vtkPolyLine::SafeDownCast(boundaries->GetCell(i0));
316 vtkIdType numberOfBoundaryPoints0 = boundary0->GetNumberOfPoints();
317 if (numberOfBoundaryPoints0 < 8)
318 {
319 vtkErrorMacro(<< "Error: Assuming at least 8 boundary points!");
320 }
321 vtkSmartPointer<vtkIdList> boundaryPointIds0 = vtkSmartPointer<vtkIdList>::New();
322 boundaryPointIds0->SetNumberOfIds(numberOfBoundaryPoints0);
323 for (int j=0; j<numberOfBoundaryPoints0; j++)
324 {
325 // Translation: local0[j] = global[local2global0[j]];
326 boundaryPointIds0->SetId(j, boundaryPointIdsArray->GetValue(boundary0->GetPointId(j)));
327 }
328
329 // Collect (global!) point ids for boundary 1 in current pairing into a contiguous array
330 vtkPolyLine* boundary1 = vtkPolyLine::SafeDownCast(boundaries->GetCell(i1));
331 vtkIdType numberOfBoundaryPoints1 = boundary1->GetNumberOfPoints();
332 if (numberOfBoundaryPoints1 < 8)
333 {
334 vtkErrorMacro(<< "Error: Assuming at least 8 boundary points!");
335 }
336 vtkSmartPointer<vtkIdList> boundaryPointIds1 = vtkSmartPointer<vtkIdList>::New();
337 boundaryPointIds1->SetNumberOfIds(numberOfBoundaryPoints1);
338 for (int j=0; j<numberOfBoundaryPoints1; j++)
339 {
340 // Translation: local1[j] = global[local2global1[j]];
341 boundaryPointIds1->SetId(j, boundaryPointIdsArray->GetValue(boundary1->GetPointId(j)));
342 }
343
344 // Find the two closest vertices between the boundaries
345 info("Finding closest vertices...");
346 IdPair starts = find_closest_points(input, boundaryPointIds0, boundaryPointIds1);
347 vtkIdType i0start = starts.first;
348 vtkIdType i1start = starts.second;
349
350 // Compute direction of paired boundaries
351 // TODO: Why was this numBP0/8 in annular case? Numerical robustness or something?
352 int i0forward = (i0start + 1) % numberOfBoundaryPoints0;
353 int i1forward = (i1start + 1) % numberOfBoundaryPoints1;
354 double cross[2][3];
355 double barycenter[3];
356 double startingPoint[3];
357 double pointForward[3];
358
359 barycenters->GetPoint(i0, barycenter);
360 input->GetPoint(boundaryPointIds0->GetId(i0start), startingPoint);
361 input->GetPoint(boundaryPointIds0->GetId(i0forward), pointForward);
362 cross_diff(startingPoint, pointForward, barycenter, cross[0]);
363
364 barycenters->GetPoint(i1, barycenter);
365 input->GetPoint(boundaryPointIds1->GetId(i1start), startingPoint);
366 input->GetPoint(boundaryPointIds1->GetId(i1forward), pointForward);
367 cross_diff(startingPoint, pointForward, barycenter, cross[1]);
368
369 int dir0 = +1; // TODO: Does the absolute direction matter?
370 bool backwards = vtkMath::Dot(cross[0], cross[1]) < 0.0;
371 int dir1 = backwards ? dir0: -dir0;
372
373 // Compute vectors in directions away from endpoints of polygon
374 double nudgeFactor = 0.01;
375 i0forward = (i0start + dir0 + numberOfBoundaryPoints0) % numberOfBoundaryPoints0;
376 input->GetPoint(boundaryPointIds0->GetId(i0start), startingPoint);
377 input->GetPoint(boundaryPointIds0->GetId(i0forward), pointForward);
378 double nudgeVector0[3] = { nudgeFactor*(pointForward[0] - startingPoint[0]),
379 nudgeFactor*(pointForward[1] - startingPoint[1]),
380 nudgeFactor*(pointForward[2] - startingPoint[2]) };
381 i1forward = (i1start - dir1 + numberOfBoundaryPoints1) % numberOfBoundaryPoints1;
382 input->GetPoint(boundaryPointIds1->GetId(i1start), startingPoint);
383 input->GetPoint(boundaryPointIds1->GetId(i1forward), pointForward);
384 double nudgeVector1[3] = { nudgeFactor*(pointForward[0] - startingPoint[0]),
385 nudgeFactor*(pointForward[1] - startingPoint[1]),
386 nudgeFactor*(pointForward[2] - startingPoint[2]) };
387
388 // Use vtkPolygon::Triangulate to mesh between boundary pair
389 info("Setting up n-sided polygon...");
390 // Initialize a vtkPolygon instance with list of boundary points
391 int npts = numberOfBoundaryPoints0 + numberOfBoundaryPoints1 + 2;
392 vtkSmartPointer<vtkPolygon> polygon = vtkSmartPointer<vtkPolygon>::New();
393 vtkPoints * polygonPoints = polygon->GetPoints();
394 vtkIdList * polygonPointIds = polygon->GetPointIds();
395 polygonPoints->SetNumberOfPoints(npts);
396 polygonPointIds->SetNumberOfIds(npts);
397 vector<vtkIdType> polygonPointIdToGlobalPointId(npts);
398 // Add all vertices from the inner polygon in one
399 // direction, starting and ending with i0start.
400 int kk = 0;
401 for (int k=0; k<=numberOfBoundaryPoints0; k++) // NB! Using <= to repeat first point.
402 {
403 vtkIdType bp0id = (i0start + dir0*k + numberOfBoundaryPoints0) % numberOfBoundaryPoints0;
404 vtkIdType pid = boundaryPointIds0->GetId(bp0id);
405 double point[3];
406 input->GetPoint(pid, point);
407 if (k == 0)
408 {
409 point[0] += nudgeVector0[0];
410 point[1] += nudgeVector0[1];
411 point[2] += nudgeVector0[2];
412 }
413 polygonPointIdToGlobalPointId[kk] = pid;
414 polygonPointIds->SetId(kk,kk);
415 polygonPoints->InsertPoint(kk, point);
416 kk++;
417 }
418 // Continue by adding all vertices from the outer polygon in the
419 // opposite direction, starting and ending with i1start.
420 for (int k=0; k<=numberOfBoundaryPoints1; k++) // NB! Using <= to repeat first point.
421 {
422 vtkIdType bp1id = (i1start + dir1*k + numberOfBoundaryPoints1) % numberOfBoundaryPoints1;
423 vtkIdType pid = boundaryPointIds1->GetId(bp1id);
424 double point[3];
425 input->GetPoint(pid, point);
426 if (k == numberOfBoundaryPoints1)
427 {
428 point[0] += nudgeVector1[0];
429 point[1] += nudgeVector1[1];
430 point[2] += nudgeVector1[2];
431 }
432 polygonPointIdToGlobalPointId[kk] = pid;
433 polygonPointIds->SetId(kk,kk);
434 polygonPoints->InsertPoint(kk, point);
435 kk++;
436 }
437
438 // Call polygon->Triangulate(...) to mesh the interior of the concave polygon
439 info("Triangulating...");
440 vtkSmartPointer<vtkIdList> outTris = vtkSmartPointer<vtkIdList>::New();
441 int triRes = polygon->NonDegenerateTriangulate(outTris);
442 if (triRes == 0)
443 {
444 vtkErrorMacro(<< "Error: Numerical degeneracy when triangulating endcaps surface! Code: " << triRes);
445 }
446
447 // Output of triangulation is now in outTris, outPoints, append to newPolys
448 info("Appending datasets...");
449 size_t nt = outTris->GetNumberOfIds()/3;
450 for (size_t it=0; it<nt; ++it)
451 {
452 // Get mapped point ids for new triangle
453 vtkIdType triangleIds[3] = { polygonPointIdToGlobalPointId[outTris->GetId(3*it+0)],
454 polygonPointIdToGlobalPointId[outTris->GetId(3*it+1)],
455 polygonPointIdToGlobalPointId[outTris->GetId(3*it+2)] };
456
457 // Insert new triangle in endcaps mesh!
458 newPolys->InsertNextCell(3, triangleIds);
459 // Mark this new triangle with the pairing number (starting from 1) + given offset
460 if (markCells)
461 {
462 // A cap closes two boundaries, so the id comes from the pair rather than from one of
463 // them; pairingCount is only the fallback position.
464 vtkIdType boundaryId = useBoundaryLabels ? boundaryLabels->GetId(i0) : i0;
465 vtkIdType partnerBoundaryId = useBoundaryLabels ? boundaryLabels->GetId(i1) : i1;
466 cellEntityIdsArray->InsertNextValue(static_cast<int>(
467 this->PairCapCellEntityId(pairingCount + 1 + this->CellEntityIdOffset,boundaryId,partnerBoundaryId,useBoundaryLabels)));
468 }
469 }
470 } // end for loop over boundary pairs
471
472 // Collect output datastructures
473 output->SetPoints(newPoints);
474 output->SetPolys(newPolys);
475 output->GetPointData()->PassData(input->GetPointData());
476 if (markCells)
477 {
478 output->GetCellData()->AddArray(cellEntityIdsArray);
479 }
480 info("Done!");
481
482 return 1;
483}
484
485vtkIdType vtkvmtkConcaveAnnularCapPolyData::PairCapCellEntityId(vtkIdType positionalId, vtkIdType boundaryId, vtkIdType partnerBoundaryId, bool useBoundaryLabels)
486{
487 // With the labels in use a boundary's label is its name, so the pair is named by the
488 // lower of its two labels -- the inner boundary, when the surface was labelled in annular
489 // mode -- unless the caller chose an id for it. Without them there is only position.
490 vtkIdType unchosenId = useBoundaryLabels
491 ? (boundaryId < partnerBoundaryId ? boundaryId : partnerBoundaryId)
492 : positionalId;
493 if (!this->BoundaryCellEntityIds)
494 {
495 return unchosenId;
496 }
497
498 vtkIdType lowerId = boundaryId < partnerBoundaryId ? boundaryId : partnerBoundaryId;
499 vtkIdType higherId = boundaryId < partnerBoundaryId ? partnerBoundaryId : boundaryId;
500
501 vtkIdType numberOfEntries = this->BoundaryCellEntityIds->GetNumberOfTuples();
502 vtkIdType lowerEntry = (lowerId >= 0 && lowerId < numberOfEntries) ? this->BoundaryCellEntityIds->GetValue(lowerId) : -1;
503 vtkIdType higherEntry = (higherId >= 0 && higherId < numberOfEntries) ? this->BoundaryCellEntityIds->GetValue(higherId) : -1;
504
505 if (lowerEntry >= 0 && higherEntry >= 0 && lowerEntry != higherEntry)
506 {
507 vtkWarningMacro(<<"The two boundaries of a pair were given different cap ids ("<<lowerEntry<<" for boundary "<<lowerId
508 <<" and "<<higherEntry<<" for boundary "<<higherId<<"); the cap takes "<<lowerEntry
509 <<", the id of the lower boundary.");
510 }
511
512 if (lowerEntry >= 0)
513 {
514 return lowerEntry;
515 }
516 if (higherEntry >= 0)
517 {
518 return higherEntry;
519 }
520 return unchosenId;
521}
522
523void vtkvmtkConcaveAnnularCapPolyData::PrintSelf(std::ostream& os, vtkIndent indent)
524{
525 this->Superclass::PrintSelf(os,indent);
526}
static bool GetOrExtractBoundaries(vtkPolyData *surface, const char *boundaryLabelsArrayName, const char *boundaryPointOrderArrayName, vtkPolyData *boundaries, vtkIdList *boundaryLabels, vtkObject *warningSource=nullptr)
static void ComputeBoundaryBarycenter(vtkPoints *points, double barycenter[3])
Add annular caps between the boundaries of a walled surface.
virtual void SetBoundaryLabelsArrayName(const char *)
void PrintSelf(std::ostream &os, vtkIndent indent) override
virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *) override
virtual void SetBoundaryPointOrderArrayName(const char *)
vtkIdType PairCapCellEntityId(vtkIdType positionalId, vtkIdType boundaryId, vtkIdType partnerBoundaryId, bool useBoundaryLabels)
vtkStandardNewMacro(vtkvmtkConcaveAnnularCapPolyData)
pair< vtkIdType, vtkIdType > IdPair
vector< IdPair > build_closest_pairs(vtkSmartPointer< vtkPoints > barycenters, vtkIdList *boundaryIds)
IdPair find_closest_points(vtkPolyData *points, vtkSmartPointer< vtkIdList > pointIds0, vtkSmartPointer< vtkIdList > pointIds1)