OpenFOAM logo
The Open Source CFD Toolbox
  Source Guide OpenCFD Solutions Contact OpenFOAM

triSurfaceTools.C

Go to the documentation of this file.
00001 /*---------------------------------------------------------------------------*\
00002   =========                 |
00003   \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
00004    \\    /   O peration     |
00005     \\  /    A nd           | Copyright (C) 1991-2009 OpenCFD Ltd.
00006      \\/     M anipulation  |
00007 -------------------------------------------------------------------------------
00008 License
00009     This file is part of OpenFOAM.
00010 
00011     OpenFOAM is free software; you can redistribute it and/or modify it
00012     under the terms of the GNU General Public License as published by the
00013     Free Software Foundation; either version 2 of the License, or (at your
00014     option) any later version.
00015 
00016     OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
00017     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00018     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
00019     for more details.
00020 
00021     You should have received a copy of the GNU General Public License
00022     along with OpenFOAM; if not, write to the Free Software Foundation,
00023     Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
00024 
00025 Description
00026 
00027 \*---------------------------------------------------------------------------*/
00028 
00029 #include "triSurfaceTools.H"
00030 
00031 #include "triSurface.H"
00032 #include "OFstream.H"
00033 #include "mergePoints.H"
00034 #include "polyMesh.H"
00035 #include "plane.H"
00036 #include "geompack.H"
00037 
00038 
00039 // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
00040 
00041 const Foam::label Foam::triSurfaceTools::ANYEDGE = -1;
00042 const Foam::label Foam::triSurfaceTools::NOEDGE = -2;
00043 const Foam::label Foam::triSurfaceTools::COLLAPSED = -3;
00044 
00045 // * * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * //
00046 
00047 /*
00048     Refine by splitting all three edges of triangle ('red' refinement).
00049     Neighbouring triangles (which are not marked for refinement get split
00050     in half ('green') refinement. (R. Verfuerth, "A review of a posteriori
00051     error estimation and adaptive mesh refinement techniques",
00052     Wiley-Teubner, 1996)
00053 */
00054 
00055 // FaceI gets refined ('red'). Propagate edge refinement.
00056 void Foam::triSurfaceTools::calcRefineStatus
00057 (
00058     const triSurface& surf,
00059     const label faceI,
00060     List<refineType>& refine
00061 )
00062 {
00063     if (refine[faceI] == RED)
00064     {
00065         // Already marked for refinement. Do nothing.
00066     }
00067     else
00068     {
00069         // Not marked or marked for 'green' refinement. Refine.
00070         refine[faceI] = RED;
00071 
00072         const labelList& myNeighbours = surf.faceFaces()[faceI];
00073 
00074         forAll(myNeighbours, myNeighbourI)
00075         {
00076             label neighbourFaceI = myNeighbours[myNeighbourI];
00077 
00078             if (refine[neighbourFaceI] == GREEN)
00079             {
00080                 // Change to red refinement and propagate
00081                 calcRefineStatus(surf, neighbourFaceI, refine);
00082             }
00083             else if (refine[neighbourFaceI] == NONE)
00084             {
00085                 refine[neighbourFaceI] = GREEN;
00086             }
00087         }
00088     }
00089 }
00090 
00091 
00092 // Split faceI along edgeI at position newPointI
00093 void Foam::triSurfaceTools::greenRefine
00094 (
00095     const triSurface& surf,
00096     const label faceI,
00097     const label edgeI,
00098     const label newPointI,
00099     DynamicList<labelledTri>& newFaces
00100 )
00101 {
00102     const labelledTri& f = surf.localFaces()[faceI];
00103     const edge& e = surf.edges()[edgeI];
00104 
00105     // Find index of edge in face.
00106 
00107     label fp0 = findIndex(f, e[0]);
00108     label fp1 = f.fcIndex(fp0);
00109     label fp2 = f.fcIndex(fp1);
00110 
00111     if (f[fp1] == e[1])
00112     {
00113         // Edge oriented like face
00114         newFaces.append
00115         (
00116             labelledTri
00117             (
00118                 f[fp0],
00119                 newPointI,
00120                 f[fp2],
00121                 f.region()
00122             )
00123         );
00124         newFaces.append
00125         (
00126             labelledTri
00127             (
00128                 newPointI,
00129                 f[fp1],
00130                 f[fp2],
00131                 f.region()
00132             )
00133         );
00134     }
00135     else
00136     {
00137         newFaces.append
00138         (
00139             labelledTri
00140             (
00141                 f[fp2],
00142                 newPointI,
00143                 f[fp1],
00144                 f.region()
00145             )
00146         );
00147         newFaces.append
00148         (
00149             labelledTri
00150             (
00151                 newPointI,
00152                 f[fp0],
00153                 f[fp1],
00154                 f.region()
00155             )
00156         );
00157     }
00158 }
00159 
00160 
00161 // Refine all triangles marked for refinement. 
00162 Foam::triSurface Foam::triSurfaceTools::doRefine
00163 (
00164     const triSurface& surf,
00165     const List<refineType>& refineStatus
00166 )
00167 {
00168     // Storage for new points. (start after old points)
00169     DynamicList<point> newPoints(surf.nPoints());
00170     forAll(surf.localPoints(), pointI)
00171     {
00172         newPoints.append(surf.localPoints()[pointI]);
00173     }
00174     label newVertI = surf.nPoints();
00175 
00176     // Storage for new faces
00177     DynamicList<labelledTri> newFaces(surf.size());
00178 
00179 
00180     // Point index for midpoint on edge
00181     labelList edgeMid(surf.nEdges(), -1);
00182 
00183     forAll(refineStatus, faceI)
00184     {
00185         if (refineStatus[faceI] == RED)
00186         {
00187             // Create new vertices on all edges to be refined.
00188             const labelList& fEdges = surf.faceEdges()[faceI];
00189 
00190             forAll(fEdges, i)
00191             {
00192                 label edgeI = fEdges[i];
00193 
00194                 if (edgeMid[edgeI] == -1)
00195                 {
00196                     const edge& e = surf.edges()[edgeI];
00197 
00198                     // Create new point on mid of edge
00199                     newPoints.append
00200                     (
00201                         0.5
00202                       * (
00203                             surf.localPoints()[e.start()]
00204                           + surf.localPoints()[e.end()]
00205                         )
00206                     );
00207                     edgeMid[edgeI] = newVertI++;
00208                 }
00209             }
00210 
00211             // Now we have new mid edge vertices for all edges on face
00212             // so create triangles for RED rerfinement.
00213 
00214             const edgeList& edges = surf.edges();
00215 
00216             // Corner triangles
00217             newFaces.append
00218             (
00219                 labelledTri
00220                 (
00221                     edgeMid[fEdges[0]],
00222                     edges[fEdges[0]].commonVertex(edges[fEdges[1]]),
00223                     edgeMid[fEdges[1]],
00224                     surf[faceI].region()
00225                 )
00226             );
00227 
00228             newFaces.append
00229             (
00230                 labelledTri
00231                 (
00232                     edgeMid[fEdges[1]],
00233                     edges[fEdges[1]].commonVertex(edges[fEdges[2]]),
00234                     edgeMid[fEdges[2]],
00235                     surf[faceI].region()
00236                 )
00237             );
00238 
00239             newFaces.append
00240             (
00241                 labelledTri
00242                 (
00243                     edgeMid[fEdges[2]],
00244                     edges[fEdges[2]].commonVertex(edges[fEdges[0]]),
00245                     edgeMid[fEdges[0]],
00246                     surf[faceI].region()
00247                 )
00248             );
00249 
00250             // Inner triangle
00251             newFaces.append
00252             (
00253                 labelledTri
00254                 (
00255                     edgeMid[fEdges[0]],
00256                     edgeMid[fEdges[1]],
00257                     edgeMid[fEdges[2]],
00258                     surf[faceI].region()
00259                 )
00260             );
00261 
00262 
00263             // Create triangles for GREEN refinement.
00264             forAll(fEdges, i)
00265             {
00266                 const label edgeI = fEdges[i];
00267 
00268                 label otherFaceI = otherFace(surf, faceI, edgeI);
00269 
00270                 if ((otherFaceI != -1) && (refineStatus[otherFaceI] == GREEN))
00271                 {
00272                     greenRefine
00273                     (
00274                         surf,
00275                         otherFaceI,
00276                         edgeI,
00277                         edgeMid[edgeI],
00278                         newFaces
00279                     );
00280                 }
00281             }
00282         }
00283     }
00284 
00285     // Copy unmarked triangles since keep original vertex numbering.
00286     forAll(refineStatus, faceI)
00287     {
00288         if (refineStatus[faceI] == NONE)
00289         {
00290             newFaces.append(surf.localFaces()[faceI]);
00291         }
00292     }
00293 
00294     newFaces.shrink();
00295     newPoints.shrink();
00296 
00297 
00298     // Transfer DynamicLists to straight ones.
00299     pointField allPoints;
00300     allPoints.transfer(newPoints);
00301     newPoints.clear();
00302 
00303     return triSurface(newFaces, surf.patches(), allPoints, true);
00304 }
00305 
00306 
00307 // Angle between two neighbouring triangles,
00308 // angle between shared-edge end points and left and right face end points
00309 Foam::scalar Foam::triSurfaceTools::faceCosAngle
00310 (
00311     const point& pStart,
00312     const point& pEnd,
00313     const point& pLeft,
00314     const point& pRight
00315 )
00316 {
00317     const vector common(pEnd - pStart);
00318     const vector base0(pLeft - pStart);
00319     const vector base1(pRight - pStart);
00320 
00321     vector n0(common ^ base0);
00322     n0 /= Foam::mag(n0);
00323 
00324     vector n1(base1 ^ common);
00325     n1 /= Foam::mag(n1);
00326 
00327     return n0 & n1;
00328 }
00329 
00330 
00331 // Protect edges around vertex from collapsing.
00332 // Moving vertI to a different position
00333 // - affects obviously the cost of the faces using it
00334 // - but also their neighbours since the edge between the faces changes
00335 void Foam::triSurfaceTools::protectNeighbours
00336 (
00337     const triSurface& surf,
00338     const label vertI,
00339     labelList& faceStatus
00340 )
00341 {
00342 //    const labelList& myFaces = surf.pointFaces()[vertI];
00343 //    forAll(myFaces, i)
00344 //    {
00345 //        label faceI = myFaces[i];
00346 //
00347 //        if ((faceStatus[faceI] == ANYEDGE) || (faceStatus[faceI] >= 0))
00348 //        {
00349 //            faceStatus[faceI] = NOEDGE;
00350 //        }
00351 //    }
00352 
00353     const labelList& myEdges = surf.pointEdges()[vertI];
00354     forAll(myEdges, i)
00355     {
00356         const labelList& myFaces = surf.edgeFaces()[myEdges[i]];
00357 
00358         forAll(myFaces, myFaceI)
00359         {
00360             label faceI = myFaces[myFaceI];
00361  
00362             if ((faceStatus[faceI] == ANYEDGE) || (faceStatus[faceI] >= 0))
00363             {
00364                 faceStatus[faceI] = NOEDGE;
00365             }
00366        }
00367     }
00368 }
00369 
00370 
00371 //
00372 // Edge collapse helper functions
00373 //
00374 
00375 // Get all faces that will get collapsed if edgeI collapses.
00376 Foam::labelHashSet Foam::triSurfaceTools::getCollapsedFaces
00377 (
00378     const triSurface& surf,
00379     label edgeI
00380 )
00381 {
00382     const edge& e = surf.edges()[edgeI];
00383     label v1 = e.start();
00384     label v2 = e.end();
00385 
00386     // Faces using edge will certainly get collapsed.
00387     const labelList& myFaces = surf.edgeFaces()[edgeI];
00388 
00389     labelHashSet facesToBeCollapsed(2*myFaces.size());
00390 
00391     forAll(myFaces, myFaceI)
00392     {
00393         facesToBeCollapsed.insert(myFaces[myFaceI]);
00394     }
00395     
00396     // From faces using v1 check if they share an edge with faces
00397     // using v2.
00398     //  - share edge: are part of 'splay' tree and will collapse if edge    
00399     //    collapses
00400     const labelList& v1Faces = surf.pointFaces()[v1];
00401 
00402     forAll(v1Faces, v1FaceI)
00403     {
00404         label face1I = v1Faces[v1FaceI];
00405 
00406         label otherEdgeI = oppositeEdge(surf, face1I, v1);
00407 
00408         // Step across edge to other face
00409         label face2I = otherFace(surf, face1I, otherEdgeI);
00410 
00411         if (face2I != -1)
00412         {
00413             // found face on other side of edge. Now check if uses v2.
00414             if (oppositeVertex(surf, face2I, otherEdgeI) == v2)
00415             {
00416                 // triangles face1I and face2I form splay tree and will
00417                 // collapse.
00418                 facesToBeCollapsed.insert(face1I);
00419                 facesToBeCollapsed.insert(face2I);
00420             }
00421         }
00422     }
00423 
00424     return facesToBeCollapsed;
00425 }
00426 
00427 
00428 // Return value of faceUsed for faces using vertI
00429 Foam::label Foam::triSurfaceTools::vertexUsesFace
00430 (
00431     const triSurface& surf,
00432     const labelHashSet& faceUsed,
00433     const label vertI
00434 )
00435 {
00436     const labelList& myFaces = surf.pointFaces()[vertI];
00437 
00438     forAll(myFaces, myFaceI)
00439     {
00440         label face1I = myFaces[myFaceI];
00441 
00442         if (faceUsed.found(face1I))
00443         {
00444             return face1I;
00445         }
00446     }
00447     return -1;
00448 }
00449 
00450 
00451 // Calculate new edge-face addressing resulting from edge collapse
00452 void Foam::triSurfaceTools::getMergedEdges
00453 (
00454     const triSurface& surf,
00455     const label edgeI,
00456     const labelHashSet& collapsedFaces,
00457     HashTable<label, label, Hash<label> >& edgeToEdge,
00458     HashTable<label, label, Hash<label> >& edgeToFace
00459 )
00460 {
00461     const edge& e = surf.edges()[edgeI];
00462     label v1 = e.start();
00463     label v2 = e.end();
00464 
00465     const labelList& v1Faces = surf.pointFaces()[v1];
00466     const labelList& v2Faces = surf.pointFaces()[v2];
00467 
00468     // Mark all (non collapsed) faces using v2
00469     labelHashSet v2FacesHash(v2Faces.size());
00470 
00471     forAll(v2Faces, v2FaceI)
00472     {
00473         if (!collapsedFaces.found(v2Faces[v2FaceI]))
00474         {
00475             v2FacesHash.insert(v2Faces[v2FaceI]);
00476         }
00477     }
00478 
00479 
00480     forAll(v1Faces, v1FaceI)
00481     {
00482         label face1I = v1Faces[v1FaceI];
00483 
00484         if (collapsedFaces.found(face1I))
00485         {
00486             continue;
00487         }
00488 
00489         //
00490         // Check if face1I uses a vertex connected to a face using v2
00491         //
00492 
00493         label vert1I = -1;
00494         label vert2I = -1;
00495         otherVertices
00496         (
00497             surf,
00498             face1I,
00499             v1,
00500             vert1I,
00501             vert2I
00502         );
00503         //Pout<< "Face:" << surf.localFaces()[face1I] << " other vertices:"
00504         //    << vert1I << ' ' << vert2I << endl;
00505 
00506         // Check vert1, vert2 for usage by v2Face.
00507 
00508         label commonVert = vert1I;
00509         label face2I = vertexUsesFace(surf, v2FacesHash, commonVert);
00510         if (face2I == -1)
00511         {
00512             commonVert = vert2I;
00513             face2I = vertexUsesFace(surf, v2FacesHash, commonVert);
00514         }
00515 
00516         if (face2I != -1)
00517         {
00518             // Found one: commonVert is used by both face1I and face2I
00519             label edge1I = getEdge(surf, v1, commonVert);
00520             label edge2I = getEdge(surf, v2, commonVert);
00521 
00522             edgeToEdge.insert(edge1I, edge2I);
00523             edgeToEdge.insert(edge2I, edge1I);
00524 
00525             edgeToFace.insert(edge1I, face2I);
00526             edgeToFace.insert(edge2I, face1I);
00527         }
00528     }
00529 }
00530 
00531 
00532 // Calculates (cos of) angle across edgeI of faceI,
00533 // taking into account updated addressing (resulting from edge collapse)
00534 Foam::scalar Foam::triSurfaceTools::edgeCosAngle
00535 (
00536     const triSurface& surf,
00537     const label v1,
00538     const point& pt,
00539     const labelHashSet& collapsedFaces,
00540     const HashTable<label, label, Hash<label> >& edgeToEdge,
00541     const HashTable<label, label, Hash<label> >& edgeToFace,
00542     const label faceI,
00543     const label edgeI
00544 )
00545 {
00546     const pointField& localPoints = surf.localPoints();
00547 
00548     label A = surf.edges()[edgeI].start();
00549     label B = surf.edges()[edgeI].end();
00550     label C = oppositeVertex(surf, faceI, edgeI);
00551 
00552     label D = -1;
00553 
00554     label face2I = -1;
00555 
00556     if (edgeToEdge.found(edgeI))
00557     {
00558         // Use merged addressing
00559         label edge2I = edgeToEdge[edgeI];
00560         face2I = edgeToFace[edgeI];
00561 
00562         D = oppositeVertex(surf, face2I, edge2I);
00563     }
00564     else
00565     {
00566         // Use normal edge-face addressing
00567         face2I = otherFace(surf, faceI, edgeI);
00568 
00569         if ((face2I != -1) && !collapsedFaces.found(face2I))
00570         {
00571             D = oppositeVertex(surf, face2I, edgeI);
00572         }
00573     }
00574 
00575     scalar cosAngle = 1;
00576 
00577     if (D != -1)
00578     {
00579         if (A == v1)
00580         {
00581             cosAngle = faceCosAngle
00582             (
00583                 pt,
00584                 localPoints[B],
00585                 localPoints[C],
00586                 localPoints[D]
00587             );
00588         }
00589         else if (B == v1)
00590         {
00591             cosAngle = faceCosAngle
00592             (
00593                 localPoints[A],
00594                 pt,
00595                 localPoints[C],
00596                 localPoints[D]
00597             );
00598         }
00599         else if (C == v1)
00600         {
00601             cosAngle = faceCosAngle
00602             (
00603                 localPoints[A],
00604                 localPoints[B],
00605                 pt,
00606                 localPoints[D]
00607             );
00608         }
00609         else if (D == v1)
00610         {
00611             cosAngle = faceCosAngle
00612             (
00613                 localPoints[A],
00614                 localPoints[B],
00615                 localPoints[C],
00616                 pt
00617             );
00618         }
00619         else
00620         {
00621             FatalErrorIn("edgeCosAngle")
00622                 << "face " << faceI << " does not use vertex "
00623                 << v1 << " of collapsed edge" << abort(FatalError);
00624         }
00625     }
00626     return cosAngle;
00627 }
00628 
00629 
00630 //- Calculate minimum (cos of) edge angle using addressing from collapsing
00631 //  edge to v1 at pt.
00632 Foam::scalar Foam::triSurfaceTools::collapseMinCosAngle
00633 (
00634     const triSurface& surf,
00635     const label v1,
00636     const point& pt,
00637     const labelHashSet& collapsedFaces,
00638     const HashTable<label, label, Hash<label> >& edgeToEdge,
00639     const HashTable<label, label, Hash<label> >& edgeToFace
00640 )
00641 {
00642     const labelList& v1Faces = surf.pointFaces()[v1];
00643 
00644     scalar minCos = 1;
00645 
00646     forAll(v1Faces, v1FaceI)
00647     {
00648         label faceI = v1Faces[v1FaceI];
00649 
00650         if (collapsedFaces.found(faceI))
00651         {
00652             continue;
00653         }
00654 
00655         const labelList& myEdges = surf.faceEdges()[faceI];
00656 
00657         forAll(myEdges, myEdgeI)
00658         {
00659             label edgeI = myEdges[myEdgeI];
00660 
00661             minCos =
00662                 min
00663                 (
00664                     minCos,
00665                     edgeCosAngle
00666                     (
00667                         surf,
00668                         v1,
00669                         pt,
00670                         collapsedFaces,
00671                         edgeToEdge,
00672                         edgeToFace,
00673                         faceI,
00674                         edgeI
00675                     )
00676                 );
00677         }
00678     }
00679 
00680     return minCos;
00681 }
00682 
00683 
00684 // Calculate max dihedral angle after collapsing edge to v1 (at pt).
00685 // Note that all edges of all faces using v1 are affected.
00686 bool Foam::triSurfaceTools::collapseCreatesFold
00687 (
00688     const triSurface& surf,
00689     const label v1,
00690     const point& pt,
00691     const labelHashSet& collapsedFaces,
00692     const HashTable<label, label, Hash<label> >& edgeToEdge,
00693     const HashTable<label, label, Hash<label> >& edgeToFace,
00694     const scalar minCos
00695 )
00696 {
00697     const labelList& v1Faces = surf.pointFaces()[v1];
00698 
00699     forAll(v1Faces, v1FaceI)
00700     {
00701         label faceI = v1Faces[v1FaceI];
00702 
00703         if (collapsedFaces.found(faceI))
00704         {
00705             continue;
00706         }
00707 
00708         const labelList& myEdges = surf.faceEdges()[faceI];
00709 
00710         forAll(myEdges, myEdgeI)
00711         {
00712             label edgeI = myEdges[myEdgeI];
00713 
00714             if
00715             (
00716                 edgeCosAngle
00717                 (
00718                     surf,
00719                     v1,
00720                     pt,
00721                     collapsedFaces,
00722                     edgeToEdge,
00723                     edgeToFace,
00724                     faceI,
00725                     edgeI
00726                 )
00727               < minCos
00728             )
00729             {
00730                 return true;
00731             }
00732         }
00733     }
00734 
00735     return false;
00736 }
00737 
00738 
00741 // a vertex.
00742 //bool Foam::triSurfaceTools::collapseCreatesDuplicates
00743 //(
00744 //    const triSurface& surf,
00745 //    const label edgeI,
00746 //    const labelHashSet& collapsedFaces
00747 //)
00748 //{
00749 //Pout<< "duplicate : edgeI:" << edgeI << surf.edges()[edgeI]
00750 //    << " collapsedFaces:" << collapsedFaces.toc() << endl;
00751 //
00752 //    // Mark neighbours of faces to be collapsed, i.e. get the first layer
00753 //    // of triangles outside collapsedFaces.
00754 //    // neighbours actually contains the
00755 //    // edge with which triangle connects to collapsedFaces.
00756 //
00757 //    HashTable<label, label, Hash<label> > neighbours;
00758 //
00759 //    labelList collapsed = collapsedFaces.toc();
00760 //
00761 //    forAll(collapsed, collapseI)
00762 //    {
00763 //        const label faceI = collapsed[collapseI];
00764 //
00765 //        const labelList& myEdges = surf.faceEdges()[faceI];
00766 //
00767 //        Pout<< "collapsing faceI:" << faceI << " uses edges:" << myEdges
00768 //            << endl;
00769 //
00770 //        forAll(myEdges, myEdgeI)
00771 //        {
00772 //            const labelList& myFaces = surf.edgeFaces()[myEdges[myEdgeI]];
00773 //
00774 //            Pout<< "Edge " << myEdges[myEdgeI] << " is used by faces "
00775 //                << myFaces << endl;
00776 //
00777 //            if ((myEdges[myEdgeI] != edgeI) && (myFaces.size() == 2))
00778 //            {
00779 //                // Get the other face
00780 //                label neighbourFaceI = myFaces[0];
00781 //
00782 //                if (neighbourFaceI == faceI)
00783 //                {
00784 //                    neighbourFaceI = myFaces[1];
00785 //                }
00786 //
00787 //                // Is 'outside' face if not in collapsedFaces itself
00788 //                if (!collapsedFaces.found(neighbourFaceI))
00789 //                {
00790 //                    neighbours.insert(neighbourFaceI, myEdges[myEdgeI]);
00791 //                }
00792 //            }
00793 //        }
00794 //    }
00795 //
00796 //    // Now neighbours contains first layer of triangles outside of
00797 //    // collapseFaces
00798 //    // There should be 
00799 //    // -two if edgeI is a boundary edge
00800 //    // since the outside 'edge' of collapseFaces should
00801 //    // form a triangle and the face connected to edgeI is not inserted.
00802 //    // -four if edgeI is not a boundary edge since then the outside edge forms
00803 //    // a diamond.
00804 //
00805 //    // Check if any of the faces in neighbours share an edge. (n^2)
00806 //
00807 //    labelList neighbourList = neighbours.toc();
00808 //
00809 //Pout<< "edgeI:" << edgeI << "  neighbourList:" << neighbourList << endl;
00810 //
00811 //
00812 //    forAll(neighbourList, i)
00813 //    {
00814 //        const labelList& faceIEdges = surf.faceEdges()[neighbourList[i]];
00815 //
00816 //        for (label j = i+1; j < neighbourList.size(); i++)
00817 //        {
00818 //            const labelList& faceJEdges = surf.faceEdges()[neighbourList[j]];
00819 //            
00820 //            // Check if faceI and faceJ share an edge
00821 //            forAll(faceIEdges, fI)
00822 //            {
00823 //                forAll(faceJEdges, fJ)
00824 //                {
00825 //                    Pout<< " comparing " << faceIEdges[fI] << " to "
00826 //                        << faceJEdges[fJ] << endl;
00827 //
00828 //                    if (faceIEdges[fI] == faceJEdges[fJ])
00829 //                    {
00830 //                        return true;
00831 //                    }
00832 //                }
00833 //            }
00834 //        }
00835 //    }
00836 //    Pout<< "Found no match. Returning false" << endl;
00837 //    return false;
00838 //}
00839 
00840 
00841 // Finds the triangle edge cut by the plane between a point inside / on edge
00842 // of a triangle and a point outside. Returns:
00843 //  - cut through edge/point
00844 //  - miss()
00845 Foam::surfaceLocation Foam::triSurfaceTools::cutEdge
00846 (
00847     const triSurface& s,
00848     const label triI,
00849     const label excludeEdgeI,
00850     const label excludePointI,
00851 
00852     const point& triPoint,
00853     const plane& cutPlane,
00854     const point& toPoint
00855 )
00856 {
00857     const pointField& points = s.points();
00858     const labelledTri& f = s[triI];
00859     const labelList& fEdges = s.faceEdges()[triI];
00860 
00861     // Get normal distance to planeN
00862     FixedList<scalar, 3> d;
00863 
00864     scalar norm = 0;
00865     forAll(d, fp)
00866     {
00867         d[fp] = (points[f[fp]]-cutPlane.refPoint()) & cutPlane.normal();
00868         norm += mag(d[fp]);
00869     }
00870 
00871     // Normalise and truncate
00872     forAll(d, i)
00873     {
00874         d[i] /= norm;
00875 
00876         if (mag(d[i]) < 1E-6)
00877         {
00878             d[i] = 0.0;
00879         }
00880     }
00881 
00882     // Return information
00883     surfaceLocation cut;
00884 
00885     if (excludePointI != -1)
00886     {
00887         // Excluded point. Test only opposite edge.
00888 
00889         label fp0 = findIndex(s.localFaces()[triI], excludePointI);
00890 
00891         if (fp0 == -1)
00892         {
00893             FatalErrorIn("cutEdge(..)") << "excludePointI:" << excludePointI
00894                 << " localF:" << s.localFaces()[triI] << abort(FatalError);
00895         }
00896 
00897         label fp1 = f.fcIndex(fp0);
00898         label fp2 = f.fcIndex(fp1);
00899 
00900 
00901         if (d[fp1] == 0.0)
00902         {
00903             cut.setHit();
00904             cut.setPoint(points[f[fp1]]);
00905             cut.elementType() = triPointRef::POINT;
00906             cut.setIndex(s.localFaces()[triI][fp1]);
00907         }
00908         else if (d[fp2] == 0.0)
00909         {
00910             cut.setHit();
00911             cut.setPoint(points[f[fp2]]);
00912             cut.elementType() = triPointRef::POINT;
00913             cut.setIndex(s.localFaces()[triI][fp2]);
00914         }
00915         else if
00916         (
00917             (d[fp1] < 0 && d[fp2] < 0)
00918          || (d[fp1] > 0 && d[fp2] > 0)
00919         )
00920         {
00921             // Both same sign. Not crossing edge at all.
00922             // cut already set to miss().
00923         }
00924         else
00925         {
00926             cut.setHit();
00927             cut.setPoint
00928             (
00929                 (d[fp2]*points[f[fp1]] - d[fp1]*points[f[fp2]])
00930               / (d[fp2] - d[fp1])
00931             );
00932             cut.elementType() = triPointRef::EDGE;
00933             cut.setIndex(fEdges[fp1]);
00934         }
00935     }
00936     else
00937     {
00938         // Find the two intersections
00939         FixedList<surfaceLocation, 2> inters;
00940         label interI = 0;
00941 
00942         forAll(f, fp0)
00943         {
00944             label fp1 = f.fcIndex(fp0);
00945 
00946             if (d[fp0] == 0)
00947             {
00948                 if (interI >= 2)
00949                 {
00950                     FatalErrorIn("cutEdge(..)")
00951                         << "problem : triangle has three intersections." << nl
00952                         << "triangle:" << f.tri(points)
00953                         << " d:" << d << abort(FatalError);
00954                 }
00955                 inters[interI].setHit();
00956                 inters[interI].setPoint(points[f[fp0]]);
00957                 inters[interI].elementType() = triPointRef::POINT;
00958                 inters[interI].setIndex(s.localFaces()[triI][fp0]);
00959                 interI++;
00960             }
00961             else if
00962             (
00963                 (d[fp0] < 0 && d[fp1] > 0)
00964              || (d[fp0] > 0 && d[fp1] < 0)
00965             )
00966             {
00967                 if (interI >= 2)
00968                 {
00969                     FatalErrorIn("cutEdge(..)")
00970                         << "problem : triangle has three intersections." << nl
00971                         << "triangle:" << f.tri(points)
00972                         << " d:" << d << abort(FatalError);
00973                 }
00974                 inters[interI].setHit();
00975                 inters[interI].setPoint
00976                 (
00977                     (d[fp0]*points[f[fp1]] - d[fp1]*points[f[fp0]])
00978                   / (d[fp0] - d[fp1])
00979                 );
00980                 inters[interI].elementType() = triPointRef::EDGE;
00981                 inters[interI].setIndex(fEdges[fp0]);
00982                 interI++;
00983             }
00984         }
00985 
00986 
00987         if (interI == 0)
00988         {
00989             // Return miss
00990         }
00991         else if (interI == 1)
00992         {
00993             // Only one intersection. Should not happen!
00994             cut = inters[0];
00995         }
00996         else if (interI == 2)
00997         {
00998             // Handle excludeEdgeI
00999             if
01000             (
01001                 inters[0].elementType() == triPointRef::EDGE
01002              && inters[0].index() == excludeEdgeI
01003             )
01004             {
01005                 cut = inters[1];
01006             }
01007             else if
01008             (
01009                 inters[1].elementType() == triPointRef::EDGE
01010              && inters[1].index() == excludeEdgeI
01011             )
01012             {
01013                 cut = inters[0];
01014             }
01015             else
01016             {
01017                 // Two cuts. Find nearest.
01018                 if
01019                 (
01020                     magSqr(inters[0].rawPoint() - toPoint)
01021                   < magSqr(inters[1].rawPoint() - toPoint)
01022                 )
01023                 {
01024                     cut = inters[0];
01025                 }
01026                 else
01027                 {
01028                     cut = inters[1];
01029                 }
01030             }
01031         }
01032     }
01033     return cut;
01034 }
01035 
01036 
01037 // 'Snap' point on to endPoint.
01038 void Foam::triSurfaceTools::snapToEnd
01039 (
01040     const triSurface& s,
01041     const surfaceLocation& end,
01042     surfaceLocation& current
01043 )
01044 {
01045     if (end.elementType() == triPointRef::NONE)
01046     {
01047         if (current.elementType() == triPointRef::NONE)
01048         {
01049             // endpoint on triangle; current on triangle
01050             if (current.index() == end.index())
01051             {
01052                 //if (debug)
01053                 //{
01054                 //    Pout<< "snapToEnd : snapping:" << current << " onto:"
01055                 //        << end << endl;
01056                 //}
01057                 current = end;
01058                 current.setHit();
01059             }
01060         }
01061         // No need to handle current on edge/point since tracking handles this.
01062     }
01063     else if (end.elementType() == triPointRef::EDGE)
01064     {
01065         if (current.elementType() == triPointRef::NONE)
01066         {
01067             // endpoint on edge; current on triangle
01068             const labelList& fEdges = s.faceEdges()[current.index()];
01069 
01070             if (findIndex(fEdges, end.index()) != -1)
01071             {
01072                 //if (debug)
01073                 //{
01074                 //    Pout<< "snapToEnd : snapping:" << current << " onto:"
01075                 //        << end << endl;
01076                 //}
01077                 current = end;
01078                 current.setHit();
01079             }
01080         }
01081         else if (current.elementType() == triPointRef::EDGE)
01082         {
01083             // endpoint on edge; current on edge
01084             if (current.index() == end.index())
01085             {
01086                 //if (debug)
01087                 //{
01088                 //    Pout<< "snapToEnd : snapping:" << current << " onto:"
01089                 //        << end << endl;
01090                 //}
01091                 current = end;
01092                 current.setHit();
01093             }
01094         }
01095         else
01096         {
01097             // endpoint on edge; current on point
01098             const edge& e = s.edges()[end.index()];
01099 
01100             if (current.index() == e[0] || current.index() == e[1])
01101             {
01102                 //if (debug)
01103                 //{
01104                 //    Pout<< "snapToEnd : snapping:" << current << " onto:"
01105                 //        << end << endl;
01106                 //}
01107                 current = end;
01108                 current.setHit();
01109             }
01110         }
01111     }
01112     else    // end.elementType() == POINT
01113     {
01114         if (current.elementType() == triPointRef::NONE)
01115         {
01116             // endpoint on point; current on triangle
01117             const labelledTri& f = s.localFaces()[current.index()];
01118 
01119             if (findIndex(f, end.index()) != -1)
01120             {
01121                 //if (debug)
01122                 //{
01123                 //    Pout<< "snapToEnd : snapping:" << current << " onto:"
01124                 //        << end << endl;
01125                 //}
01126                 current = end;
01127                 current.setHit();
01128             }
01129         }
01130         else if (current.elementType() == triPointRef::EDGE)
01131         {
01132             // endpoint on point; current on edge
01133             const edge& e = s.edges()[current.index()];
01134 
01135             if (end.index() == e[0] || end.index() == e[1])
01136             {
01137                 //if (debug)
01138                 //{
01139                 //    Pout<< "snapToEnd : snapping:" << current << " onto:"
01140                 //        << end << endl;
01141                 //}
01142                 current = end;
01143                 current.setHit();
01144             }
01145         }
01146         else
01147         {
01148             // endpoint on point; current on point
01149             if (current.index() == end.index())
01150             {
01151                 //if (debug)
01152                 //{
01153                 //    Pout<< "snapToEnd : snapping:" << current << " onto:"
01154                 //        << end << endl;
01155                 //}
01156                 current = end;
01157                 current.setHit();
01158             }
01159         }
01160     }
01161 }
01162 
01163 
01164 // Start:
01165 //  - location
01166 //  - element type (triangle/edge/point) and index
01167 //  - triangle to exclude
01168 Foam::surfaceLocation Foam::triSurfaceTools::visitFaces
01169 (
01170     const triSurface& s,
01171     const labelList& eFaces,
01172     const surfaceLocation& start,
01173     const label excludeEdgeI,
01174     const label excludePointI,
01175     const surfaceLocation& end,
01176     const plane& cutPlane
01177 )
01178 {
01179     surfaceLocation nearest;
01180 
01181     scalar minDistSqr = Foam::sqr(GREAT);
01182 
01183     forAll(eFaces, i)
01184     {
01185         label triI = eFaces[i];
01186 
01187         // Make sure we don't revisit previous face
01188         if (triI != start.triangle())
01189         {
01190             if (end.elementType() == triPointRef::NONE && end.index() == triI)
01191             {
01192                 // Endpoint is in this triangle. Jump there.
01193                 nearest = end;
01194                 nearest.setHit();
01195                 nearest.triangle() = triI;
01196                 break;
01197             }            
01198             else
01199             {
01200                // Which edge is cut.
01201 
01202                 surfaceLocation cutInfo = cutEdge
01203                 (
01204                     s,
01205                     triI,
01206                     excludeEdgeI,       // excludeEdgeI
01207                     excludePointI,      // excludePointI
01208                     start.rawPoint(),
01209                     cutPlane,
01210                     end.rawPoint()
01211                 );
01212 
01213                 // If crossing an edge we expect next edge to be cut.
01214                 if (excludeEdgeI != -1 && !cutInfo.hit())
01215                 {
01216                     FatalErrorIn("triSurfaceTools::visitFaces(..)")
01217                         << "Triangle:" << triI
01218                         << " excludeEdge:" << excludeEdgeI
01219                         << " point:" << start.rawPoint()
01220                         << " plane:" << cutPlane
01221                         << " . No intersection!" << abort(FatalError);
01222                 }
01223 
01224                 if (cutInfo.hit())
01225                 {
01226                     scalar distSqr = magSqr(cutInfo.rawPoint()-end.rawPoint());
01227 
01228                     if (distSqr < minDistSqr)
01229                     {
01230                         minDistSqr = distSqr;
01231                         nearest = cutInfo;
01232                         nearest.triangle() = triI;
01233                         nearest.setMiss();
01234                     }
01235                 }
01236             }
01237         }
01238     }
01239 
01240     if (nearest.triangle() == -1)
01241     {
01242         // Did not move from edge. Give warning? Return something special?
01243         // For now responsability of caller to make sure that nothing has
01244         // moved.
01245     }
01246 
01247     return nearest;
01248 }
01249 
01250 
01251 // * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //
01252 
01253 
01254 // Write pointField to file
01255 void Foam::triSurfaceTools::writeOBJ
01256 (
01257     const fileName& fName,
01258     const pointField& pts
01259 )
01260 {
01261     OFstream outFile(fName);
01262 
01263     forAll(pts, pointI)
01264     {
01265         const point& pt = pts[pointI];
01266 
01267         outFile<< "v " << pt.x() << ' ' << pt.y() << ' ' << pt.z() << endl;
01268     }
01269     Pout<< "Written " << pts.size() << " vertices to file " << fName << endl;
01270 }
01271 
01272 
01273 // Write vertex subset to OBJ format file
01274 void Foam::triSurfaceTools::writeOBJ
01275 (
01276     const triSurface& surf,
01277     const fileName& fName,
01278     const boolList& markedVerts
01279 )
01280 {
01281     OFstream outFile(fName);
01282 
01283     label nVerts = 0;
01284     forAll(markedVerts, vertI)
01285     {
01286         if (markedVerts[vertI])
01287         {
01288             const point& pt = surf.localPoints()[vertI];
01289 
01290             outFile<< "v " << pt.x() << ' ' << pt.y() << ' ' << pt.z() << endl;
01291 
01292             nVerts++;
01293         }
01294     }
01295     Pout<< "Written " << nVerts << " vertices to file " << fName << endl;
01296 }
01297 
01298 
01299 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
01300 // Addressing helper functions:
01301 
01302 
01303 // Get all triangles using vertices of edge
01304 void Foam::triSurfaceTools::getVertexTriangles
01305 (
01306     const triSurface& surf,
01307     const label edgeI,
01308     labelList& edgeTris
01309 )
01310 {
01311     const edge& e = surf.edges()[edgeI];
01312     const labelList& myFaces = surf.edgeFaces()[edgeI];
01313 
01314     label face1I = myFaces[0];
01315     label face2I = -1;
01316     if (myFaces.size() == 2)
01317     {
01318         face2I = myFaces[1];
01319     }
01320 
01321     const labelList& startFaces = surf.pointFaces()[e.start()];
01322     const labelList& endFaces = surf.pointFaces()[e.end()];
01323 
01324     // Number of triangles is sum of pointfaces - common faces
01325     // (= faces using edge)
01326     edgeTris.setSize(startFaces.size() + endFaces.size() - myFaces.size());
01327 
01328     label nTris = 0;
01329     forAll(startFaces, startFaceI)
01330     {
01331         edgeTris[nTris++] = startFaces[startFaceI];
01332     }
01333 
01334     forAll(endFaces, endFaceI)
01335     {
01336         label faceI = endFaces[endFaceI];
01337 
01338         if ((faceI != face1I) && (faceI != face2I))
01339         {
01340             edgeTris[nTris++] = faceI;
01341         }
01342     }
01343 }
01344 
01345 
01346 // Get all vertices connected to vertices of edge
01347 Foam::labelList Foam::triSurfaceTools::getVertexVertices
01348 (
01349     const triSurface& surf,
01350     const edge& e
01351 )
01352 {
01353     const edgeList& edges = surf.edges();
01354 
01355     label v1 = e.start();
01356     label v2 = e.end();
01357 
01358     // Get all vertices connected to v1 or v2 through an edge
01359     labelHashSet vertexNeighbours;
01360 
01361     const labelList& v1Edges = surf.pointEdges()[v1];
01362 
01363     forAll(v1Edges, v1EdgeI)
01364     {
01365         const edge& e = edges[v1Edges[v1EdgeI]];
01366         vertexNeighbours.insert(e.otherVertex(v1));
01367     }
01368 
01369     const labelList& v2Edges = surf.pointEdges()[v2];
01370 
01371     forAll(v2Edges, v2EdgeI)
01372     {
01373         const edge& e = edges[v2Edges[v2EdgeI]];
01374 
01375         label vertI = e.otherVertex(v2);
01376 
01377         vertexNeighbours.insert(vertI);
01378     }
01379     return vertexNeighbours.toc();
01380 }
01381 
01382 
01384 //void Foam::triSurfaceTools::orderVertices
01385 //(
01386 //    const labelledTri& f,
01387 //    const label v1,
01388 //    const label v2,
01389 //    label& vA,
01390 //    label& vB
01391 //)
01392 //{
01393 //    // Order v1, v2 in anticlockwise order.
01394 //    bool reverse = false;
01395 //
01396 //    if (f[0] == v1)
01397 //    {
01398 //        if (f[1] != v2)
01399 //        {
01400 //            reverse = true;
01401 //        }
01402 //    }
01403 //    else if (f[1] == v1)
01404 //    {
01405 //        if (f[2] != v2)
01406 //        {
01407 //            reverse = true;
01408 //        }
01409 //    }
01410 //    else
01411 //    {
01412 //        if (f[0] != v2)
01413 //        {
01414 //            reverse = true;
01415 //        }
01416 //    }
01417 //
01418 //    if (reverse)
01419 //    {
01420 //        vA = v2;
01421 //        vB = v1;
01422 //    }
01423 //    else
01424 //    {
01425 //        vA = v1;
01426 //        vB = v2;
01427 //    }
01428 //}
01429 
01430 
01431 // Get the other face using edgeI
01432 Foam::label Foam::triSurfaceTools::otherFace
01433 (
01434     const triSurface& surf,
01435     const label faceI,
01436     const label edgeI
01437 )
01438 {
01439     const labelList& myFaces = surf.edgeFaces()[edgeI];
01440 
01441     if (myFaces.size() != 2)
01442     {
01443         return -1;
01444     }
01445     else
01446     {
01447         if (faceI == myFaces[0])
01448         {
01449             return myFaces[1];
01450         }
01451         else
01452         {
01453             return myFaces[0];
01454         }
01455     }
01456 }
01457 
01458 
01459 // Get the two edges on faceI counterclockwise after edgeI
01460 void Foam::triSurfaceTools::otherEdges
01461 (
01462     const triSurface& surf,
01463     const label faceI,
01464     const label edgeI,
01465     label& e1,
01466     label& e2
01467 )
01468 {
01469     const labelList& eFaces = surf.faceEdges()[faceI];
01470 
01471     label i0 = findIndex(eFaces, edgeI);
01472 
01473     if (i0 == -1)
01474     {
01475         FatalErrorIn
01476         (
01477             "otherEdges"
01478             "(const triSurface&, const label, const label,"
01479             " label&, label&)"
01480         )   << "Edge " << surf.edges()[edgeI] << " not in face "
01481             << surf.localFaces()[faceI] << abort(FatalError);
01482     }
01483 
01484     label i1 = eFaces.fcIndex(i0);
01485     label i2 = eFaces.fcIndex(i1);
01486 
01487     e1 = eFaces[i1];
01488     e2 = eFaces[i2];
01489 }
01490 
01491 
01492 // Get the two vertices on faceI counterclockwise vertI
01493 void Foam::triSurfaceTools::otherVertices
01494 (
01495     const triSurface& surf,
01496     const label faceI,
01497     const label vertI,
01498     label& vert1I,
01499     label& vert2I
01500 )
01501 {
01502     const labelledTri& f = surf.localFaces()[faceI];
01503 
01504     if (vertI == f[0])
01505     {
01506         vert1I = f[1];
01507         vert2I = f[2];
01508     }
01509     else if (vertI == f[1])
01510     {
01511         vert1I = f[2];
01512         vert2I = f[0];
01513     }
01514     else if (vertI == f[2])
01515     {
01516         vert1I = f[0];
01517         vert2I = f[1];
01518     }
01519     else
01520     {
01521         FatalErrorIn
01522         (
01523             "otherVertices"
01524             "(const triSurface&, const label, const label,"
01525             " label&, label&)"
01526         )   << "Vertex " << vertI << " not in face " << f << abort(FatalError);
01527     }
01528 }
01529 
01530 
01531 // Get edge opposite vertex
01532 Foam::label Foam::triSurfaceTools::oppositeEdge
01533 (
01534     const triSurface& surf,
01535     const label faceI,
01536     const label vertI
01537 )
01538 {
01539     const labelList& myEdges = surf.faceEdges()[faceI];
01540 
01541     forAll(myEdges, myEdgeI)
01542     {
01543         label edgeI = myEdges[myEdgeI];
01544 
01545         const edge& e = surf.edges()[edgeI];
01546 
01547         if ((e.start() != vertI) && (e.end() != vertI))
01548         {
01549             return edgeI;
01550         }
01551     }
01552 
01553     FatalErrorIn
01554     (
01555         "oppositeEdge"
01556         "(const triSurface&, const label, const label)"
01557     )   << "Cannot find vertex " << vertI << " in edges of face " << faceI
01558         << abort(FatalError);
01559 
01560     return -1;
01561 }
01562 
01563 
01564 // Get vertex opposite edge
01565 Foam::label Foam::triSurfaceTools::oppositeVertex
01566 (
01567     const triSurface& surf,
01568     const label faceI,
01569     const label edgeI
01570 )
01571 {
01572     const labelledTri& f = surf.localFaces()[faceI];
01573 
01574     const edge& e = surf.edges()[edgeI];
01575 
01576     forAll(f, fp)
01577     {
01578         label vertI = f[fp];
01579 
01580         if (vertI != e.start() && vertI != e.end())
01581         {
01582             return vertI;
01583         }
01584     }
01585 
01586     FatalErrorIn("triSurfaceTools::oppositeVertex")
01587         << "Cannot find vertex opposite edge " << edgeI << " vertices " << e
01588         << " in face " << faceI << " vertices " << f << abort(FatalError);
01589 
01590     return -1;
01591 }
01592 
01593 
01594 // Returns edge label connecting v1, v2
01595 Foam::label Foam::triSurfaceTools::getEdge
01596 (
01597     const triSurface& surf,
01598     const label v1,
01599     const label v2
01600 )
01601 {
01602     const labelList& v1Edges = surf.pointEdges()[v1];
01603 
01604     forAll(v1Edges, v1EdgeI)
01605     {
01606         label edgeI = v1Edges[v1EdgeI];
01607 
01608         const edge& e = surf.edges()[edgeI];
01609 
01610         if ((e.start() == v2) || (e.end() == v2))
01611         {
01612             return edgeI;
01613         }
01614     }
01615     return -1;
01616 }
01617 
01618 
01619 // Return index of triangle (or -1) using all three edges
01620 Foam::label Foam::triSurfaceTools::getTriangle
01621 (
01622     const triSurface& surf,
01623     const label e0I,
01624     const label e1I,
01625     const label e2I
01626 )
01627 {
01628     if ((e0I == e1I) || (e0I == e2I) || (e1I == e2I))
01629     {
01630         FatalErrorIn
01631         (
01632             "getTriangle"
01633             "(const triSurface&, const label, const label,"
01634             " const label)"
01635         )   << "Duplicate edge labels : e0:" << e0I << " e1:" << e1I
01636             << " e2:" << e2I
01637             << abort(FatalError);
01638     }
01639 
01640     const labelList& eFaces = surf.edgeFaces()[e0I];
01641 
01642     forAll(eFaces, eFaceI)
01643     {
01644         label faceI = eFaces[eFaceI];
01645 
01646         const labelList& myEdges = surf.faceEdges()[faceI];
01647 
01648         if
01649         (
01650             (myEdges[0] == e1I)
01651          || (myEdges[1] == e1I)
01652          || (myEdges[2] == e1I)
01653         )
01654         {
01655             if
01656             (
01657                 (myEdges[0] == e2I)
01658              || (myEdges[1] == e2I)
01659              || (myEdges[2] == e2I)
01660             )
01661             {
01662                 return faceI;
01663             }
01664         }
01665     }
01666     return -1;
01667 }
01668 
01669 
01670 // Collapse indicated edges. Return new tri surface.
01671 Foam::triSurface Foam::triSurfaceTools::collapseEdges
01672 (
01673     const triSurface& surf,
01674     const labelList& collapsableEdges
01675 )
01676 {
01677     pointField edgeMids(surf.nEdges());
01678 
01679     forAll(edgeMids, edgeI)
01680     {
01681         const edge& e = surf.edges()[edgeI];
01682 
01683         edgeMids[edgeI] =
01684             0.5
01685           * (
01686                 surf.localPoints()[e.start()]
01687               + surf.localPoints()[e.end()]
01688             );
01689     }
01690 
01691 
01692     labelList faceStatus(surf.size(), ANYEDGE);
01693 
01695     //forAll(edges, edgeI)
01696     //{
01697     //    const labelList& neighbours = edgeFaces[edgeI];
01698     //
01699     //    if ((neighbours.size() != 2) && (neighbours.size() != 1))
01700     //    {
01701     //        FatalErrorIn("collapseEdges")
01702     //            << abort(FatalError);
01703     //    }
01704     //
01705     //    if (neighbours.size() == 2)
01706     //    {
01707     //        if (surf[neighbours[0]].region() != surf[neighbours[1]].region())
01708     //        {
01709     //            // Neighbours on different regions. For now dont allow
01710     //            // any collapse.
01711     //            //Pout<< "protecting face " << neighbours[0]
01712     //            //    << ' ' << neighbours[1] << endl;
01713     //            faceStatus[neighbours[0]] = NOEDGE;
01714     //            faceStatus[neighbours[1]] = NOEDGE;
01715     //        }
01716     //    }
01717     //}
01718 
01719     return collapseEdges(surf, collapsableEdges, edgeMids, faceStatus);
01720 }
01721 
01722 
01723 // Collapse indicated edges. Return new tri surface.
01724 Foam::triSurface Foam::triSurfaceTools::collapseEdges
01725 (
01726     const triSurface& surf,
01727     const labelList& collapseEdgeLabels,
01728     const pointField& edgeMids,
01729     labelList& faceStatus
01730 )
01731 {
01732     const labelListList& edgeFaces = surf.edgeFaces();
01733     const pointField& localPoints = surf.localPoints();
01734     const edgeList& edges = surf.edges();
01735 
01736     // Storage for new points
01737     pointField newPoints(localPoints);
01738 
01739     // Map for old to new points
01740     labelList pointMap(localPoints.size());
01741     forAll(localPoints, pointI)
01742     {
01743         pointMap[pointI] = pointI;
01744     }
01745 
01746 
01747     // Do actual 'collapsing' of edges
01748 
01749     forAll(collapseEdgeLabels, collapseEdgeI)
01750     {
01751         const label edgeI = collapseEdgeLabels[collapseEdgeI];
01752 
01753         if ((edgeI < 0) || (edgeI >= surf.nEdges()))
01754         {
01755             FatalErrorIn("collapseEdges")
01756                 << "Edge label outside valid range." << endl
01757                 << "edge label:" << edgeI << endl
01758                 << "total number of edges:" << surf.nEdges() << endl
01759                 << abort(FatalError);
01760         }
01761 
01762         const labelList& neighbours = edgeFaces[edgeI];
01763 
01764         if (neighbours.size() == 2)
01765         {
01766             const label stat0 = faceStatus[neighbours[0]];
01767             const label stat1 = faceStatus[neighbours[1]];
01768 
01769             // Check faceStatus to make sure this one can be collapsed
01770             if
01771             (
01772                 ((stat0 == ANYEDGE) || (stat0 == edgeI))
01773              && ((stat1 == ANYEDGE) || (stat1 == edgeI))
01774             )
01775             {
01776                 const edge& e = edges[edgeI];
01777 
01778                 // Set up mapping to 'collapse' points of edge
01779                 if
01780                 (
01781                     (pointMap[e.start()] != e.start())
01782                  || (pointMap[e.end()] != e.end())
01783                 )
01784                 {
01785                     FatalErrorIn("collapseEdges")
01786                         << "points already mapped. Double collapse." << endl
01787                         << "edgeI:" << edgeI
01788                         << "  start:" << e.start()
01789                         << "  end:" << e.end()
01790                         << "  pointMap[start]:" << pointMap[e.start()]
01791                         << "  pointMap[end]:" << pointMap[e.end()]
01792                         << abort(FatalError);
01793                 }
01794 
01795                 const label minVert = min(e.start(), e.end());
01796                 pointMap[e.start()] = minVert;
01797                 pointMap[e.end()] = minVert;
01798 
01799                 // Move shared vertex to mid of edge
01800                 newPoints[minVert] = edgeMids[edgeI];
01801 
01802                 // Protect neighbouring faces
01803                 protectNeighbours(surf, e.start(), faceStatus);
01804                 protectNeighbours(surf, e.end(), faceStatus);
01805                 protectNeighbours
01806                 (
01807                     surf,
01808                     oppositeVertex(surf, neighbours[0], edgeI),
01809                     faceStatus
01810                 );
01811                 protectNeighbours
01812                 (
01813                     surf,
01814                     oppositeVertex(surf, neighbours[1], edgeI),
01815                     faceStatus
01816                 );
01817 
01818                 // Mark all collapsing faces
01819                 labelList collapseFaces =
01820                     getCollapsedFaces
01821                     (
01822                         surf,
01823                         edgeI
01824                     ).toc();
01825 
01826                 forAll(collapseFaces, collapseI)
01827                 {
01828                      faceStatus[collapseFaces[collapseI]] = COLLAPSED;
01829                 }
01830             }
01831         }
01832     }
01833 
01834 
01835     // Storage for new triangles
01836     List<labelledTri> newTris(surf.size());
01837     label newTriI = 0;
01838 
01839     const List<labelledTri>& localFaces = surf.localFaces();
01840 
01841 
01842     // Get only non-collapsed triangles and renumber vertex labels.
01843     forAll(localFaces, faceI)
01844     {
01845         const labelledTri& f = localFaces[faceI];
01846 
01847         const label a = pointMap[f[0]];
01848         const label b = pointMap[f[1]];
01849         const label c = pointMap[f[2]];
01850 
01851         if
01852         (
01853             (a != b) && (a != c) && (b != c)
01854          && (faceStatus[faceI] != COLLAPSED)
01855         )
01856         {
01857             // uncollapsed triangle
01858             newTris[newTriI++] = labelledTri(a, b, c, f.region());
01859         }
01860         else
01861         {
01862             //Pout<< "Collapsed triangle " << faceI
01863             //    << " vertices:" << f << endl;
01864         }
01865     }
01866     newTris.setSize(newTriI);
01867 
01868 
01869 
01870     // Pack faces
01871 
01872     triSurface tempSurf(newTris, surf.patches(), newPoints);
01873 
01874     return
01875         triSurface
01876         (
01877             tempSurf.localFaces(),
01878             tempSurf.patches(),
01879             tempSurf.localPoints()
01880         );
01881 }
01882 
01883 
01884 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
01885 
01886 Foam::triSurface Foam::triSurfaceTools::redGreenRefine
01887 (
01888     const triSurface& surf,
01889     const labelList& refineFaces
01890 )
01891 {
01892     List<refineType> refineStatus(surf.size(), NONE);
01893 
01894     // Mark & propagate refinement
01895     forAll(refineFaces, refineFaceI)
01896     {
01897         calcRefineStatus(surf, refineFaces[refineFaceI], refineStatus);
01898     }
01899 
01900     // Do actual refinement
01901     return doRefine(surf, refineStatus);
01902 }
01903 
01904 
01905 Foam::triSurface Foam::triSurfaceTools::greenRefine
01906 (
01907     const triSurface& surf,
01908     const labelList& refineEdges
01909 )
01910 {
01911     // Storage for marking faces
01912     List<refineType> refineStatus(surf.size(), NONE);
01913 
01914     // Storage for new faces
01915     DynamicList<labelledTri> newFaces(0);
01916     
01917     pointField newPoints(surf.localPoints());
01918     newPoints.setSize(surf.nPoints() + surf.nEdges());
01919     label newPointI = surf.nPoints();
01920 
01921 
01922     // Refine edges
01923     forAll(refineEdges, refineEdgeI)
01924     {
01925         label edgeI = refineEdges[refineEdgeI];
01926 
01927         const labelList& myFaces = surf.edgeFaces()[edgeI];
01928 
01929         bool neighbourIsRefined= false;
01930 
01931         forAll(myFaces, myFaceI)
01932         {
01933             if (refineStatus[myFaces[myFaceI]] != NONE)
01934             {
01935                 neighbourIsRefined =  true;
01936             }
01937         }
01938 
01939         // Only refine if none of the faces is refined
01940         if (!neighbourIsRefined)
01941         {
01942             // Refine edge
01943             const edge& e = surf.edges()[edgeI];
01944 
01945             point mid =
01946                 0.5
01947               * (
01948                     surf.localPoints()[e.start()]
01949                   + surf.localPoints()[e.end()]
01950                 );
01951 
01952             newPoints[newPointI] = mid;
01953 
01954             // Refine faces using edge
01955             forAll(myFaces, myFaceI)
01956             {
01957                 // Add faces to newFaces
01958                 greenRefine
01959                 (
01960                     surf,
01961                     myFaces[myFaceI],
01962                     edgeI,
01963                     newPointI,
01964                     newFaces
01965                 );
01966 
01967                 // Mark as refined
01968                 refineStatus[myFaces[myFaceI]] = GREEN;
01969             }
01970 
01971             newPointI++;
01972         }
01973     }
01974 
01975     // Add unrefined faces
01976     forAll(surf.localFaces(), faceI)
01977     {
01978         if (refineStatus[faceI] == NONE)
01979         {
01980             newFaces.append(surf.localFaces()[faceI]);
01981         }
01982     }
01983 
01984     newFaces.shrink();
01985     newPoints.setSize(newPointI);
01986 
01987     return triSurface(newFaces, surf.patches(), newPoints, true);
01988 }
01989 
01990 
01991 
01992 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
01993 // Geometric helper functions:
01994 
01995 
01996 // Returns element in edgeIndices with minimum length
01997 Foam::label Foam::triSurfaceTools::minEdge
01998 (
01999     const triSurface& surf,
02000     const labelList& edgeIndices
02001 )
02002 {
02003     scalar minLength = GREAT;
02004     label minIndex = -1;
02005     forAll(edgeIndices, i)
02006     {
02007         const edge& e = surf.edges()[edgeIndices[i]];
02008 
02009         scalar length =
02010             mag
02011             (
02012                 surf.localPoints()[e.end()]
02013               - surf.localPoints()[e.start()]
02014             );
02015 
02016         if (length < minLength)
02017         {
02018             minLength = length;
02019             minIndex = i;
02020         }
02021     }
02022     return edgeIndices[minIndex];
02023 }
02024 
02025 
02026 // Returns element in edgeIndices with maximum length
02027 Foam::label Foam::triSurfaceTools::maxEdge
02028 (
02029     const triSurface& surf,
02030     const labelList& edgeIndices
02031 )
02032 {
02033     scalar maxLength = -GREAT;
02034     label maxIndex = -1;
02035     forAll(edgeIndices, i)
02036     {
02037         const edge& e = surf.edges()[edgeIndices[i]];
02038 
02039         scalar length =
02040             mag
02041             (
02042                 surf.localPoints()[e.end()]
02043               - surf.localPoints()[e.start()]
02044             );
02045 
02046         if (length > maxLength)
02047         {
02048             maxLength = length;
02049             maxIndex = i;
02050         }
02051     }
02052     return edgeIndices[maxIndex];
02053 }
02054 
02055 
02056 // Merge points and reconstruct surface
02057 Foam::triSurface Foam::triSurfaceTools::mergePoints
02058 (
02059     const triSurface& surf,
02060     const scalar mergeTol
02061 )
02062 {
02063     pointField newPoints(surf.nPoints());
02064 
02065     labelList pointMap(surf.nPoints());
02066 
02067     bool hasMerged = Foam::mergePoints
02068     (
02069         surf.localPoints(),
02070         mergeTol,
02071         false,
02072         pointMap,
02073         newPoints
02074     );
02075 
02076     if (hasMerged)
02077     {
02078         // Pack the triangles
02079 
02080         // Storage for new triangles
02081         List<labelledTri> newTriangles(surf.size());
02082         label newTriangleI = 0;
02083 
02084         forAll(surf, faceI)
02085         {
02086             const labelledTri& f = surf.localFaces()[faceI];
02087 
02088             label newA = pointMap[f[0]];
02089             label newB = pointMap[f[1]];
02090             label newC = pointMap[f[2]];
02091 
02092             if ((newA != newB) && (newA != newC) && (newB != newC))
02093             {
02094                 newTriangles[newTriangleI++] =
02095                     labelledTri(newA, newB, newC, f.region());
02096             }
02097         }
02098         newTriangles.setSize(newTriangleI);
02099 
02100         return triSurface
02101         (
02102             newTriangles,
02103             surf.patches(),
02104             newPoints
02105         );
02106     }
02107     else
02108     {
02109         return surf;
02110     }
02111 }
02112 
02113 
02114 // Calculate normal on triangle
02115 Foam::vector Foam::triSurfaceTools::surfaceNormal
02116 (
02117     const triSurface& surf,
02118     const label nearestFaceI,
02119     const point& nearestPt
02120 )
02121 {
02122     const labelledTri& f = surf[nearestFaceI];
02123     const pointField& points = surf.points();
02124 
02125     label nearType;
02126     label nearLabel;
02127     triPointRef
02128     (
02129         points[f[0]],
02130         points[f[1]],
02131         points[f[2]]
02132     ).classify(nearestPt, 1E-6, nearType, nearLabel);
02133 
02134     if (nearType == triPointRef::NONE)
02135     {
02136         // Nearest to face
02137         return surf.faceNormals()[nearestFaceI];
02138     }
02139     else if (nearType == triPointRef::EDGE)
02140     {
02141         // Nearest to edge. Assume order of faceEdges same as face vertices.
02142         label edgeI = surf.faceEdges()[nearestFaceI][nearLabel];
02143 
02144         // Calculate edge normal by averaging face normals
02145         const labelList& eFaces = surf.edgeFaces()[edgeI];
02146 
02147         vector edgeNormal(vector::zero);
02148 
02149         forAll(eFaces, i)
02150         {
02151             edgeNormal += surf.faceNormals()[eFaces[i]];
02152         }
02153         return edgeNormal/(mag(edgeNormal) + VSMALL);
02154     }
02155     else
02156     {
02157         // Nearest to point
02158         const labelledTri& localF = surf.localFaces()[nearestFaceI];
02159         return surf.pointNormals()[localF[nearLabel]];
02160     }
02161 }
02162 
02163 
02164 Foam::triSurfaceTools::sideType Foam::triSurfaceTools::edgeSide
02165 (
02166     const triSurface& surf,
02167     const point& sample,
02168     const point& nearestPoint,
02169     const label edgeI
02170 )
02171 {
02172     const labelList& eFaces = surf.edgeFaces()[edgeI];
02173 
02174     if (eFaces.size() != 2)
02175     {
02176         // Surface not closed.
02177         return UNKNOWN;
02178     }
02179     else
02180     {
02181         const vectorField& faceNormals = surf.faceNormals();
02182 
02183         // Compare to bisector. This is actually correct since edge is
02184         // nearest so there is a knife-edge.
02185 
02186         vector n = 0.5*(faceNormals[eFaces[0]] + faceNormals[eFaces[1]]);
02187 
02188         if (((sample - nearestPoint) & n) > 0)
02189         {
02190             return OUTSIDE;
02191         }
02192         else
02193         {
02194             return INSIDE;
02195         }
02196     }
02197 }
02198 
02199 
02200 // Calculate normal on triangle
02201 Foam::triSurfaceTools::sideType Foam::triSurfaceTools::surfaceSide
02202 (
02203     const triSurface& surf,
02204     const point& sample,
02205     const label nearestFaceI,   // nearest face
02206     const point& nearestPoint,  // nearest point on nearest face
02207     const scalar tol
02208 )
02209 {
02210     const labelledTri& f = surf[nearestFaceI];
02211     const pointField& points = surf.points();
02212 
02213     // Find where point is on triangle. Note tolerance needed. Is relative
02214     // one (used in comparing normalized [0..1] triangle coordinates).
02215     label nearType, nearLabel;
02216     triPointRef
02217     (
02218         points[f[0]],
02219         points[f[1]],
02220         points[f[2]]
02221     ).classify(nearestPoint, tol, nearType, nearLabel);
02222 
02223     if (nearType == triPointRef::NONE)
02224     {
02225         // Nearest to face interior. Use faceNormal to determine side
02226         scalar c = (sample - nearestPoint) & surf.faceNormals()[nearestFaceI];
02227 
02228         if (c > 0)
02229         {
02230             return OUTSIDE;
02231         }
02232         else
02233         {
02234             return INSIDE;
02235         }
02236     }
02237     else if (nearType == triPointRef::EDGE)
02238     {
02239         // Nearest to edge nearLabel. Note that this can only be a knife-edge
02240         // situation since otherwise the nearest point could never be the edge.
02241 
02242         // Get the edge. Assume order of faceEdges same as face vertices.
02243         label edgeI = surf.faceEdges()[nearestFaceI][nearLabel];
02244 
02245         //if (debug)
02246         //{
02247         //    // Check order of faceEdges same as face vertices.
02248         //    const edge& e = surf.edges()[edgeI];
02249         //    const labelList& meshPoints = surf.meshPoints();
02250         //    const edge meshEdge(meshPoints[e[0]], meshPoints[e[1]]);
02251         //
02252         //    if
02253         //    (
02254         //        meshEdge
02255         //     != edge(f[nearLabel], f[f.fcIndex(nearLabel)])
02256         //    )
02257         //    {
02258         //        FatalErrorIn("triSurfaceTools::surfaceSide")
02259         //            << "Edge:" << edgeI << " local vertices:" << e
02260         //            << " mesh vertices:" << meshEdge
02261         //            << " not at position " << nearLabel
02262         //            << " in face " << f
02263         //            << abort(FatalError);
02264         //    }
02265         //}
02266 
02267         return edgeSide(surf, sample, nearestPoint, edgeI);
02268     }
02269     else
02270     {
02271         // Nearest to point. Could use pointNormal here but is not correct.
02272         // Instead determine which edge using point is nearest and use test
02273         // above (nearType == triPointRef::EDGE).
02274 
02275 
02276         const labelledTri& localF = surf.localFaces()[nearestFaceI];
02277         label nearPointI = localF[nearLabel];
02278 
02279         const edgeList& edges = surf.edges();
02280         const pointField& localPoints = surf.localPoints();
02281         const point& base = localPoints[nearPointI];
02282 
02283         const labelList& pEdges = surf.pointEdges()[nearPointI];
02284 
02285         scalar minDistSqr = Foam::sqr(GREAT);
02286         label minEdgeI = -1;
02287 
02288         forAll(pEdges, i)
02289         {
02290             label edgeI = pEdges[i];
02291 
02292             const edge& e = edges[edgeI];
02293 
02294             label otherPointI = e.otherVertex(nearPointI);
02295 
02296             // Get edge normal.
02297             vector eVec(localPoints[otherPointI] - base);
02298             scalar magEVec = mag(eVec);
02299 
02300             if (magEVec > VSMALL)
02301             {
02302                 eVec /= magEVec;
02303 
02304                 // Get point along vector and determine closest.
02305                 const point perturbPoint = base + eVec;
02306 
02307                 scalar distSqr = Foam::magSqr(sample - perturbPoint);
02308 
02309                 if (distSqr < minDistSqr)
02310                 {
02311                     minDistSqr = distSqr;
02312                     minEdgeI = edgeI;
02313                 }
02314             }
02315         }
02316 
02317         if (minEdgeI == -1)
02318         {
02319             FatalErrorIn("treeDataTriSurface::getSide")
02320                 << "Problem: did not find edge closer than " << minDistSqr
02321                 << abort(FatalError);
02322         }
02323 
02324         return edgeSide(surf, sample, nearestPoint, minEdgeI);
02325     }
02326 }
02327 
02328 
02329 // triangulation of boundaryMesh
02330 Foam::triSurface Foam::triSurfaceTools::triangulate
02331 (
02332     const polyBoundaryMesh& bMesh,
02333     const labelHashSet& includePatches,
02334     const bool verbose
02335 )
02336 {
02337     const polyMesh& mesh = bMesh.mesh();
02338 
02339     // Storage for surfaceMesh. Size estimate.
02340     DynamicList<labelledTri> triangles
02341     (
02342         mesh.nFaces() - mesh.nInternalFaces()
02343     );
02344 
02345     label newPatchI = 0;
02346 
02347     for
02348     (
02349         labelHashSet::const_iterator iter = includePatches.begin();
02350         iter != includePatches.end();
02351         ++iter
02352     )
02353     {
02354         label patchI = iter.key();
02355 
02356         const polyPatch& patch = bMesh[patchI];
02357 
02358         const pointField& points = patch.points();
02359 
02360         label nTriTotal = 0;
02361 
02362         forAll(patch, patchFaceI)
02363         {
02364             const face& f = patch[patchFaceI];
02365 
02366             faceList triFaces(f.nTriangles(points));
02367 
02368             label nTri = 0;
02369 
02370             f.triangles(points, nTri, triFaces);
02371 
02372             forAll(triFaces, triFaceI)
02373             {
02374                 const face& f = triFaces[triFaceI];
02375 
02376                 triangles.append(labelledTri(f[0], f[1], f[2], newPatchI));
02377 
02378                 nTriTotal++;
02379             }
02380         }
02381 
02382         if (verbose)
02383         {
02384             Pout<< patch.name() << " : generated " << nTriTotal
02385                 << " triangles from " << patch.size() << " faces with"
02386                 << " new patchid " << newPatchI << endl;
02387         }
02388 
02389         newPatchI++;
02390     }
02391     triangles.shrink();
02392 
02393     // Create globally numbered tri surface
02394     triSurface rawSurface(triangles, mesh.points());
02395 
02396     // Create locally numbered tri surface
02397     triSurface surface
02398     (
02399         rawSurface.localFaces(),
02400         rawSurface.localPoints()
02401     );
02402 
02403     // Add patch names to surface
02404     surface.patches().setSize(newPatchI);
02405 
02406     newPatchI = 0;
02407 
02408     for
02409     (
02410         labelHashSet::const_iterator iter = includePatches.begin();
02411         iter != includePatches.end();
02412         ++iter
02413     )
02414     {
02415         label patchI = iter.key();
02416 
02417         const polyPatch& patch = bMesh[patchI];
02418 
02419         surface.patches()[newPatchI].name() = patch.name();
02420 
02421         surface.patches()[newPatchI].geometricType() = patch.type();
02422 
02423         newPatchI++;
02424     }
02425 
02426     return surface;
02427 }
02428 
02429 
02430 // triangulation of boundaryMesh
02431 Foam::triSurface Foam::triSurfaceTools::triangulateFaceCentre
02432 (
02433     const polyBoundaryMesh& bMesh,
02434     const labelHashSet& includePatches,
02435     const bool verbose
02436 )
02437 {
02438     const polyMesh& mesh = bMesh.mesh();
02439 
02440     // Storage for new points = meshpoints + face centres.
02441     const pointField& points = mesh.points();
02442     const pointField& faceCentres = mesh.faceCentres();
02443 
02444     pointField newPoints(points.size() + faceCentres.size());
02445 
02446     label newPointI = 0;
02447 
02448     forAll(points, pointI)
02449     {
02450         newPoints[newPointI++] = points[pointI];
02451     }
02452     forAll(faceCentres, faceI)
02453     {
02454         newPoints[newPointI++] = faceCentres[faceI];
02455     }
02456 
02457 
02458     // Count number of faces.
02459     DynamicList<labelledTri> triangles
02460     (
02461         mesh.nFaces() - mesh.nInternalFaces()
02462     );
02463 
02464     label newPatchI = 0;
02465 
02466     for
02467     (
02468         labelHashSet::const_iterator iter = includePatches.begin();
02469         iter != includePatches.end();
02470         ++iter
02471     )
02472     {
02473         label patchI = iter.key();
02474 
02475         const polyPatch& patch = bMesh[patchI];
02476 
02477         label nTriTotal = 0;
02478 
02479         forAll(patch, patchFaceI)
02480         {
02481             // Face in global coords.
02482             const face& f = patch[patchFaceI];
02483 
02484             // Index in newPointI of face centre.
02485             label fc = points.size() + patchFaceI + patch.start();
02486 
02487             forAll(f, fp)
02488             {
02489                 label fp1 = (fp + 1) % f.size();
02490 
02491                 triangles.append(labelledTri(f[fp], f[fp1], fc, newPatchI));
02492 
02493                 nTriTotal++;
02494             }
02495         }
02496 
02497         if (verbose)
02498         {
02499             Pout<< patch.name() << " : generated " << nTriTotal
02500                 << " triangles from " << patch.size() << " faces with"
02501                 << " new patchid " << newPatchI << endl;
02502         }
02503 
02504         newPatchI++;
02505     }
02506     triangles.shrink();
02507 
02508 
02509     // Create globally numbered tri surface
02510     triSurface rawSurface(triangles, newPoints);
02511 
02512     // Create locally numbered tri surface
02513     triSurface surface
02514     (
02515         rawSurface.localFaces(),
02516         rawSurface.localPoints()
02517     );
02518 
02519     // Add patch names to surface
02520     surface.patches().setSize(newPatchI);
02521 
02522     newPatchI = 0;
02523 
02524     for
02525     (
02526         labelHashSet::const_iterator iter = includePatches.begin();
02527         iter != includePatches.end();
02528         ++iter
02529     )
02530     {
02531         label patchI = iter.key();
02532 
02533         const polyPatch& patch = bMesh[patchI];
02534 
02535         surface.patches()[newPatchI].name() = patch.name();
02536 
02537         surface.patches()[newPatchI].geometricType() = patch.type();
02538 
02539         newPatchI++;
02540     }
02541 
02542     return surface;
02543 }
02544 
02545 
02546 Foam::triSurface Foam::triSurfaceTools::delaunay2D(const List<vector2D>& pts)
02547 {
02548     // Vertices in geompack notation. Note that could probably just use
02549     // pts.begin() if double precision.
02550     List<doubleScalar> geompackVertices(2*pts.size());
02551     label doubleI = 0;
02552     forAll(pts, i)
02553     {
02554         geompackVertices[doubleI++] = pts[i][0];
02555         geompackVertices[doubleI++] = pts[i][1];
02556     }
02557 
02558     // Storage for triangles
02559     int m2 = 3;
02560     List<int> triangle_node(m2*3*pts.size());
02561     List<int> triangle_neighbor(m2*3*pts.size());
02562 
02563     // Triangulate
02564     int nTris = 0;
02565     dtris2
02566     (
02567         pts.size(),
02568         geompackVertices.begin(),
02569         &nTris,
02570         triangle_node.begin(),
02571         triangle_neighbor.begin()
02572     );
02573 
02574     // Trim
02575     triangle_node.setSize(3*nTris);
02576     triangle_neighbor.setSize(3*nTris);
02577 
02578     // Convert to triSurface.
02579     List<labelledTri> faces(nTris);
02580 
02581     forAll(faces, i)
02582     {
02583         faces[i] = labelledTri
02584         (
02585             triangle_node[3*i]-1,
02586             triangle_node[3*i+1]-1,
02587             triangle_node[3*i+2]-1,
02588             0
02589         );
02590     }
02591 
02592     pointField points(pts.size());
02593     forAll(pts, i)
02594     {
02595         points[i][0] = pts[i][0];
02596         points[i][1] = pts[i][1];
02597         points[i][2] = 0.0;
02598     }
02599 
02600     return triSurface(faces, points);
02601 }
02602 
02603 
02605 //#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
02606 //#include <CGAL/Delaunay_triangulation_2.h>
02607 //#include <CGAL/Triangulation_vertex_base_with_info_2.h>
02608 //#include <cassert>
02609 //
02610 //struct K : CGAL::Exact_predicates_inexact_constructions_kernel {};
02611 //
02612 //typedef CGAL::Triangulation_vertex_base_with_info_2<Foam::label, K> Vb;
02613 //typedef CGAL::Triangulation_data_structure_2<Vb> Tds;
02614 //typedef CGAL::Delaunay_triangulation_2<K,Tds> Triangulation;
02615 //
02616 //typedef Triangulation::Vertex_handle Vertex_handle;
02617 //typedef Triangulation::Vertex_iterator Vertex_iterator;
02618 //typedef Triangulation::Face_handle Face_handle;
02619 //typedef Triangulation::Finite_faces_iterator Finite_faces_iterator;
02620 //typedef Triangulation::Point Point;
02621 //Foam::triSurface Foam::triSurfaceTools::delaunay2D(const List<vector2D>& pts)
02622 //{
02623 //    Triangulation T;
02624 //
02625 //    // Insert 2D vertices; building triangulation
02626 //    forAll(pts, i)
02627 //    {
02628 //        const point& pt = pts[i];
02629 //
02630 //        T.insert(Point(pt[0], pt[1]));
02631 //    }
02632 //
02633 //
02634 //    // Number vertices
02635 //    // ~~~~~~~~~~~~~~~
02636 //
02637 //    label vertI = 0;
02638 //    for 
02639 //    (
02640 //        Vertex_iterator it = T.vertices_begin();
02641 //        it != T.vertices_end();
02642 //        ++it
02643 //    )
02644 //    {
02645 //        it->info() = vertI++;
02646 //    }
02647 //
02648 //    // Extract faces
02649 //    // ~~~~~~~~~~~~~
02650 //
02651 //    List<labelledTri> faces(T.number_of_faces());
02652 //
02653 //    label faceI = 0;
02654 //
02655 //    for
02656 //    (
02657 //        Finite_faces_iterator fc = T.finite_faces_begin();
02658 //        fc != T.finite_faces_end();
02659 //        ++fc
02660 //    )
02661 //    {
02662 //        faces[faceI++] = labelledTri
02663 //        (
02664 //            fc->vertex(0)->info(),
02665 //            f[1] = fc->vertex(1)->info(),
02666 //            f[2] = fc->vertex(2)->info()
02667 //        );
02668 //    }
02669 //
02670 //    pointField points(pts.size());
02671 //    forAll(pts, i)
02672 //    {
02673 //        points[i][0] = pts[i][0];
02674 //        points[i][1] = pts[i][1];
02675 //        points[i][2] = 0.0;
02676 //    }
02677 //
02678 //    return triSurface(faces, points);
02679 //}
02680 
02681 
02682 void Foam::triSurfaceTools::calcInterpolationWeights
02683 (
02684     const triPointRef& tri,
02685     const point& p,
02686     FixedList<scalar, 3>& weights
02687 )
02688 {
02689     // calculate triangle edge vectors and triangle face normal
02690     // the 'i':th edge is opposite node i
02691     FixedList<vector, 3> edge;
02692     edge[0] = tri.c()-tri.b();
02693     edge[1] = tri.a()-tri.c();
02694     edge[2] = tri.b()-tri.a();
02695 
02696     vector triangleFaceNormal = edge[1] ^ edge[2];
02697 
02698     // calculate edge normal (pointing inwards)
02699     FixedList<vector, 3> normal;
02700     for(label i=0; i<3; i++)
02701     {
02702         normal[i] = triangleFaceNormal ^ edge[i];
02703         normal[i] /= mag(normal[i]) + VSMALL;
02704     }
02705 
02706     weights[0] = ((p-tri.b()) & normal[0]) / max(VSMALL, normal[0] & edge[1]);
02707     weights[1] = ((p-tri.c()) & normal[1]) / max(VSMALL, normal[1] & edge[2]);
02708     weights[2] = ((p-tri.a()) & normal[2]) / max(VSMALL, normal[2] & edge[0]);
02709 }
02710 
02711 
02712 // Calculate weighting factors from samplePts to triangle it is in.
02713 // Uses linear search.
02714 void Foam::triSurfaceTools::calcInterpolationWeights
02715 (
02716     const triSurface& s,
02717     const pointField& samplePts,
02718     List<FixedList<label, 3> >& allVerts,
02719     List<FixedList<scalar, 3> >& allWeights
02720 )
02721 {
02722     allVerts.setSize(samplePts.size());
02723     allWeights.setSize(samplePts.size());
02724 
02725     const pointField& points = s.points();
02726 
02727     forAll(samplePts, i)
02728     {
02729         const point& samplePt = samplePts[i];
02730 
02731 
02732         FixedList<label, 3>& verts = allVerts[i];
02733         FixedList<scalar, 3>& weights = allWeights[i];
02734 
02735         scalar minDistance = GREAT;
02736 
02737         forAll(s, faceI)
02738         {
02739             const labelledTri& f = s[faceI];
02740 
02741             triPointRef tri(f.tri(points));
02742 
02743             pointHit nearest = tri.nearestPoint(samplePt);
02744 
02745             if (nearest.hit())
02746             {
02747                 // samplePt inside triangle
02748                 verts[0] = f[0];
02749                 verts[1] = f[1];
02750                 verts[2] = f[2];
02751 
02752                 calcInterpolationWeights(tri, nearest.rawPoint(), weights);
02753 
02754                 //Pout<< "calcScalingFactors : samplePt:" << samplePt
02755                 //    << " inside triangle:" << faceI
02756                 //    << " verts:" << verts
02757                 //    << " weights:" << weights
02758                 //    << endl;
02759 
02760                 break;
02761             }
02762             else if (nearest.distance() < minDistance)
02763             {
02764                 minDistance = nearest.distance();
02765 
02766                 // Outside triangle. Store nearest.
02767                 label nearType, nearLabel;
02768                 tri.classify
02769                 (
02770                     nearest.rawPoint(),
02771                     1E-6,               // relative tolerance
02772                     nearType,
02773                     nearLabel
02774                 );
02775 
02776                 if (nearType == triPointRef::POINT)
02777                 {
02778                     verts[0] = f[nearLabel];
02779                     weights[0] = 1;
02780                     verts[1] = -1;
02781                     weights[1] = -GREAT;
02782                     verts[2] = -1;
02783                     weights[2] = -GREAT;
02784 
02785                     //Pout<< "calcScalingFactors : samplePt:" << samplePt
02786                     //    << " distance:" << nearest.distance()
02787                     //    << " from point:" << points[f[nearLabel]]
02788                     //    << endl;
02789                 }
02790                 else if (nearType == triPointRef::EDGE)
02791                 {
02792                     verts[0] = f[nearLabel];
02793                     verts[1] = f[f.fcIndex(nearLabel)];
02794                     verts[2] = -1;
02795 
02796                     const point& p0 = points[verts[0]];
02797                     const point& p1 = points[verts[1]];
02798 
02799                     scalar s = min
02800                     (
02801                         1,
02802                         max
02803                         (
02804                             0,
02805                             mag(nearest.rawPoint()-p0)/mag(p1-p0)
02806                         )
02807                     );
02808 
02809                     // Interpolate
02810                     weights[0] = 1-s;
02811                     weights[1] = s;
02812                     weights[2] = -GREAT;
02813 
02814                     //Pout<< "calcScalingFactors : samplePt:" << samplePt
02815                     //    << " distance:" << nearest.distance()
02816                     //    << " from edge:" << p0 << p1 << " s:" << s
02817                     //    << endl;
02818                 }
02819                 else
02820                 {
02821                     // triangle. Can only happen because of truncation errors.
02822                     verts[0] = f[0];
02823                     verts[1] = f[1];
02824                     verts[2] = f[2];
02825 
02826                     calcInterpolationWeights(tri, nearest.rawPoint(), weights);
02827 
02828                     break;
02829                 }
02830             }
02831         }
02832     }
02833 }
02834 
02835 
02836 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
02837 // Tracking:
02838 
02839 
02840 // Test point on surface to see if is on face,edge or point.
02841 Foam::surfaceLocation Foam::triSurfaceTools::classify
02842 (
02843     const triSurface& s,
02844     const label triI,
02845     const point& trianglePoint
02846 )
02847 {
02848     surfaceLocation nearest;
02849 
02850     // Nearest point could be on point or edge. Retest.
02851     label index, elemType;
02852     //bool inside = 
02853     triPointRef(s[triI].tri(s.points())).classify
02854     (
02855         trianglePoint,
02856         1E-6,
02857         elemType,
02858         index
02859     );
02860 
02861     nearest.setPoint(trianglePoint);
02862 
02863     if (elemType == triPointRef::NONE)
02864     {
02865         nearest.setHit();
02866         nearest.setIndex(triI);
02867         nearest.elementType() = triPointRef::NONE;
02868     }    
02869     else if (elemType == triPointRef::EDGE)
02870     {
02871         nearest.setMiss();
02872         nearest.setIndex(s.faceEdges()[triI][index]);
02873         nearest.elementType() = triPointRef::EDGE;
02874     }
02875     else //if (elemType == triPointRef::POINT)
02876     {
02877         nearest.setMiss();
02878         nearest.setIndex(s.localFaces()[triI][index]);
02879         nearest.elementType() = triPointRef::POINT;
02880     }
02881 
02882     return nearest;
02883 }
02884 
02885 
02886 Foam::surfaceLocation Foam::triSurfaceTools::trackToEdge
02887 (
02888     const triSurface& s,
02889     const surfaceLocation& start,
02890     const surfaceLocation& end,
02891     const plane& cutPlane
02892 )
02893 {
02894     // Start off from starting point
02895     surfaceLocation nearest = start;
02896     nearest.setMiss();
02897 
02898     // See if in same triangle as endpoint. If so snap.
02899     snapToEnd(s, end, nearest);
02900 
02901     if (!nearest.hit())
02902     {
02903         // Not yet at end point
02904 
02905         if (start.elementType() == triPointRef::NONE)
02906         {
02907             // Start point is inside triangle. Trivial cases already handled
02908             // above.
02909 
02910             // end point is on edge or point so cross currrent triangle to
02911             // see which edge is cut.
02912 
02913             nearest = cutEdge
02914             (
02915                 s,
02916                 start.index(),          // triangle
02917                 -1,                     // excludeEdge
02918                 -1,                     // excludePoint
02919                 start.rawPoint(),
02920                 cutPlane,
02921                 end.rawPoint()
02922             );
02923             nearest.elementType() = triPointRef::EDGE;
02924             nearest.triangle() = start.index();
02925             nearest.setMiss();
02926         }
02927         else if (start.elementType() == triPointRef::EDGE)
02928         {
02929             // Pick connected triangle that is most in direction.
02930             const labelList& eFaces = s.edgeFaces()[start.index()];
02931 
02932             nearest = visitFaces
02933             (
02934                 s,
02935                 eFaces,
02936                 start,
02937                 start.index(),      // excludeEdgeI
02938                 -1,                 // excludePointI
02939                 end,
02940                 cutPlane
02941             );
02942         }
02943         else    // start.elementType() == triPointRef::POINT
02944         {
02945             const labelList& pFaces = s.pointFaces()[start.index()];
02946 
02947             nearest = visitFaces
02948             (
02949                 s,
02950                 pFaces,
02951                 start,
02952                 -1,                 // excludeEdgeI
02953                 start.index(),      // excludePointI
02954                 end,
02955                 cutPlane
02956             );
02957         }
02958         snapToEnd(s, end, nearest);
02959     }
02960     return nearest;
02961 }
02962 
02963 
02964 void Foam::triSurfaceTools::track
02965 (
02966     const triSurface& s,
02967     const surfaceLocation& endInfo,
02968     const plane& cutPlane,
02969     surfaceLocation& hitInfo
02970 )
02971 {
02972     //OFstream str("track.obj");
02973     //label vertI = 0;
02974     //meshTools::writeOBJ(str, hitInfo.rawPoint());
02975     //vertI++;
02976 
02977     // Track across surface.
02978     while (true)
02979     {
02980         //Pout<< "Tracking from:" << nl
02981         //    << "    " << hitInfo.info()
02982         //    << endl;
02983 
02984         hitInfo = trackToEdge
02985         (
02986             s,
02987             hitInfo,
02988             endInfo,
02989             cutPlane
02990         );
02991 
02992         //meshTools::writeOBJ(str, hitInfo.rawPoint());
02993         //vertI++;
02994         //str<< "l " << vertI-1 << ' ' << vertI << nl;
02995 
02996         //Pout<< "Tracked to:" << nl
02997         //    << "    " << hitInfo.info() << endl;
02998 
02999         if (hitInfo.hit() || hitInfo.triangle() == -1)
03000         {
03001             break;
03002         }
03003     }
03004 }
03005 
03006 
03007 // ************************************************************************* //
Copyright © 2000-2009 OpenCFD Ltd