1 // SMESH SMESH : idl implementation based on 'SMESH' unit's classes
3 // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
24 // File : SMESH_MeshEditor.cxx
25 // Created : Mon Apr 12 16:10:22 2004
26 // Author : Edward AGAPOV (eap)
29 #include "SMESH_MeshEditor.hxx"
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
37 #include "SMESHDS_Group.hxx"
38 #include "SMESHDS_Mesh.hxx"
40 #include "SMESH_subMesh.hxx"
41 #include "SMESH_ControlsDef.hxx"
43 #include "utilities.h"
45 #include <TopTools_ListIteratorOfListOfShape.hxx>
46 #include <TopTools_ListOfShape.hxx>
51 #include <gp_Trsf.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Surface.hxx>
59 #include <Geom2d_Curve.hxx>
60 #include <Extrema_GenExtPS.hxx>
61 #include <Extrema_POnSurf.hxx>
62 #include <GeomAdaptor_Surface.hxx>
68 using namespace SMESH::Controls;
70 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
71 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
72 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
73 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
74 typedef TNodeOfNodeListMap::iterator TNodeOfNodeListMapItr;
75 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
77 //=======================================================================
78 //function : SMESH_MeshEditor
80 //=======================================================================
82 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
87 //=======================================================================
89 //purpose : Remove a node or an element.
90 // Modify a compute state of sub-meshes which become empty
91 //=======================================================================
93 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
97 SMESHDS_Mesh* aMesh = GetMeshDS();
98 set< SMESH_subMesh *> smmap;
100 list<int>::const_iterator it = theIDs.begin();
101 for ( ; it != theIDs.end(); it++ )
103 const SMDS_MeshElement * elem;
105 elem = aMesh->FindNode( *it );
107 elem = aMesh->FindElement( *it );
111 // Find sub-meshes to notify about modification
112 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
113 while ( nodeIt->more() )
115 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
116 const SMDS_PositionPtr& aPosition = node->GetPosition();
117 if ( aPosition.get() ) {
118 int aShapeID = aPosition->GetShapeId();
120 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
121 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
130 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
132 aMesh->RemoveElement( elem );
135 // Notify sub-meshes about modification
136 if ( !smmap.empty() ) {
137 set< SMESH_subMesh *>::iterator smIt;
138 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
139 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
144 //=======================================================================
145 //function : FindShape
146 //purpose : Return an index of the shape theElem is on
147 // or zero if a shape not found
148 //=======================================================================
150 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
152 SMESHDS_Mesh * aMesh = GetMeshDS();
153 if ( aMesh->ShapeToMesh().IsNull() )
156 if ( theElem->GetType() == SMDSAbs_Node )
158 const SMDS_PositionPtr& aPosition =
159 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
160 if ( aPosition.get() )
161 return aPosition->GetShapeId();
166 TopoDS_Shape aShape; // the shape a node is on
167 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
168 while ( nodeIt->more() )
170 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
171 const SMDS_PositionPtr& aPosition = node->GetPosition();
172 if ( aPosition.get() ) {
173 int aShapeID = aPosition->GetShapeId();
174 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
177 if ( sm->Contains( theElem ))
179 if ( aShape.IsNull() )
180 aShape = aMesh->IndexToShape( aShapeID );
184 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
189 // None of nodes is on a proper shape,
190 // find the shape among ancestors of aShape on which a node is
191 if ( aShape.IsNull() ) {
192 //MESSAGE ("::FindShape() - NONE node is on shape")
195 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
196 for ( ; ancIt.More(); ancIt.Next() )
198 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
199 if ( sm && sm->Contains( theElem ))
200 return aMesh->ShapeToIndex( ancIt.Value() );
203 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
207 //=======================================================================
208 //function : InverseDiag
209 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
210 // but having other common link.
211 // Return False if args are improper
212 //=======================================================================
214 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
215 const SMDS_MeshElement * theTria2 )
217 if (!theTria1 || !theTria2)
219 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
220 if (!F1) return false;
221 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
222 if (!F2) return false;
224 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
225 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
229 // put nodes in array and find out indices of the same ones
230 const SMDS_MeshNode* aNodes [6];
231 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
233 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
236 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
238 if ( i > 2 ) // theTria2
239 // find same node of theTria1
240 for ( int j = 0; j < 3; j++ )
241 if ( aNodes[ i ] == aNodes[ j ]) {
250 return false; // theTria1 is not a triangle
251 it = theTria2->nodesIterator();
253 if ( i == 6 && it->more() )
254 return false; // theTria2 is not a triangle
257 // find indices of 1,2 and of A,B in theTria1
258 int iA = 0, iB = 0, i1 = 0, i2 = 0;
259 for ( i = 0; i < 6; i++ )
261 if ( sameInd [ i ] == 0 )
268 // nodes 1 and 2 should not be the same
269 if ( aNodes[ i1 ] == aNodes[ i2 ] )
274 aNodes[ iA ] = aNodes[ i2 ];
276 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
278 //MESSAGE( theTria1 << theTria2 );
280 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
281 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
283 //MESSAGE( theTria1 << theTria2 );
288 //=======================================================================
289 //function : findTriangles
290 //purpose : find triangles sharing theNode1-theNode2 link
291 //=======================================================================
293 static bool findTriangles(const SMDS_MeshNode * theNode1,
294 const SMDS_MeshNode * theNode2,
295 const SMDS_MeshElement*& theTria1,
296 const SMDS_MeshElement*& theTria2)
298 if ( !theNode1 || !theNode2 ) return false;
300 theTria1 = theTria2 = 0;
302 set< const SMDS_MeshElement* > emap;
303 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
305 const SMDS_MeshElement* elem = it->next();
306 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
309 it = theNode2->GetInverseElementIterator();
311 const SMDS_MeshElement* elem = it->next();
312 if ( elem->GetType() == SMDSAbs_Face &&
313 emap.find( elem ) != emap.end() )
321 return ( theTria1 && theTria2 );
324 //=======================================================================
325 //function : InverseDiag
326 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
327 // with ones built on the same 4 nodes but having other common link.
328 // Return false if proper faces not found
329 //=======================================================================
331 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
332 const SMDS_MeshNode * theNode2)
334 MESSAGE( "::InverseDiag()" );
336 const SMDS_MeshElement *tr1, *tr2;
337 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
340 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
341 if (!F1) return false;
342 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
343 if (!F2) return false;
345 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
346 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
350 // put nodes in array
351 // and find indices of 1,2 and of A in tr1 and of B in tr2
352 int i, iA1 = 0, i1 = 0;
353 const SMDS_MeshNode* aNodes1 [3];
354 SMDS_ElemIteratorPtr it;
355 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
356 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
357 if ( aNodes1[ i ] == theNode1 )
358 iA1 = i; // node A in tr1
359 else if ( aNodes1[ i ] != theNode2 )
363 const SMDS_MeshNode* aNodes2 [3];
364 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
365 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
366 if ( aNodes2[ i ] == theNode2 )
367 iB2 = i; // node B in tr2
368 else if ( aNodes2[ i ] != theNode1 )
372 // nodes 1 and 2 should not be the same
373 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
377 aNodes1[ iA1 ] = aNodes2[ i2 ];
379 aNodes2[ iB2 ] = aNodes1[ i1 ];
381 //MESSAGE( tr1 << tr2 );
383 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
384 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
386 //MESSAGE( tr1 << tr2 );
392 //=======================================================================
393 //function : getQuadrangleNodes
394 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
395 // fusion of triangles tr1 and tr2 having shared link on
396 // theNode1 and theNode2
397 //=======================================================================
399 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
400 const SMDS_MeshNode * theNode1,
401 const SMDS_MeshNode * theNode2,
402 const SMDS_MeshElement * tr1,
403 const SMDS_MeshElement * tr2 )
405 // find the 4-th node to insert into tr1
406 const SMDS_MeshNode* n4 = 0;
407 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
408 while ( !n4 && it->more() )
410 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
411 bool isDiag = ( n == theNode1 || n == theNode2 );
415 // Make an array of nodes to be in a quadrangle
416 int iNode = 0, iFirstDiag = -1;
417 it = tr1->nodesIterator();
420 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
421 bool isDiag = ( n == theNode1 || n == theNode2 );
424 if ( iFirstDiag < 0 )
426 else if ( iNode - iFirstDiag == 1 )
427 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
431 return false; // tr1 and tr2 should not have all the same nodes
433 theQuadNodes[ iNode++ ] = n;
435 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
436 theQuadNodes[ iNode ] = n4;
441 //=======================================================================
442 //function : DeleteDiag
443 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
444 // with a quadrangle built on the same 4 nodes.
445 // Return false if proper faces not found
446 //=======================================================================
448 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
449 const SMDS_MeshNode * theNode2)
451 MESSAGE( "::DeleteDiag()" );
453 const SMDS_MeshElement *tr1, *tr2;
454 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
457 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
458 if (!F1) return false;
459 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
460 if (!F2) return false;
462 const SMDS_MeshNode* aNodes [ 4 ];
463 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
466 //MESSAGE( endl << tr1 << tr2 );
468 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
469 GetMeshDS()->RemoveElement( tr2 );
471 //MESSAGE( endl << tr1 );
476 //=======================================================================
477 //function : Reorient
478 //purpose : Reverse theElement orientation
479 //=======================================================================
481 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
485 SMDS_ElemIteratorPtr it = theElem->nodesIterator();
486 if ( !it || !it->more() )
489 switch ( theElem->GetType() ) {
494 int i = theElem->NbNodes();
495 vector<const SMDS_MeshNode*> aNodes( i );
497 aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
498 return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
502 if (theElem->IsPoly()) {
503 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
504 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
506 MESSAGE("Warning: bad volumic element");
510 int nbFaces = aPolyedre->NbFaces();
511 vector<const SMDS_MeshNode *> poly_nodes;
512 vector<int> quantities (nbFaces);
514 // reverse each face of the polyedre
515 for (int iface = 1; iface <= nbFaces; iface++) {
516 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
517 quantities[iface - 1] = nbFaceNodes;
519 for (inode = nbFaceNodes; inode >= 1; inode--) {
520 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
521 poly_nodes.push_back(curNode);
525 return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
528 SMDS_VolumeTool vTool;
529 if ( !vTool.Set( theElem ))
532 return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
541 //=======================================================================
542 //function : getBadRate
544 //=======================================================================
546 static double getBadRate (const SMDS_MeshElement* theElem,
547 SMESH::Controls::NumericalFunctorPtr& theCrit)
549 SMESH::Controls::TSequenceOfXYZ P;
550 if ( !theElem || !theCrit->GetPoints( theElem, P ))
552 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
555 //=======================================================================
556 //function : QuadToTri
557 //purpose : Cut quadrangles into triangles.
558 // theCrit is used to select a diagonal to cut
559 //=======================================================================
561 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
562 SMESH::Controls::NumericalFunctorPtr theCrit)
564 MESSAGE( "::QuadToTri()" );
566 if ( !theCrit.get() )
569 SMESHDS_Mesh * aMesh = GetMeshDS();
571 set< const SMDS_MeshElement * >::iterator itElem;
572 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
574 const SMDS_MeshElement* elem = (*itElem);
575 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
578 // retrieve element nodes
579 const SMDS_MeshNode* aNodes [4];
580 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
582 while ( itN->more() )
583 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
585 // compare two sets of possible triangles
586 double aBadRate1, aBadRate2; // to what extent a set is bad
587 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
588 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
589 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
591 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
592 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
593 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
595 int aShapeId = FindShape( elem );
596 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
597 // << " ShapeID = " << aShapeId << endl << elem );
599 if ( aBadRate1 <= aBadRate2 ) {
600 // tr1 + tr2 is better
601 aMesh->ChangeElementNodes( elem, aNodes, 3 );
602 //MESSAGE( endl << elem );
604 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
607 // tr3 + tr4 is better
608 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
609 //MESSAGE( endl << elem );
611 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
613 //MESSAGE( endl << elem );
615 // put a new triangle on the same shape
617 aMesh->SetMeshElementOnShape( elem, aShapeId );
623 //=======================================================================
624 //function : AddToSameGroups
625 //purpose : add elemToAdd to the groups the elemInGroups belongs to
626 //=======================================================================
628 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
629 const SMDS_MeshElement* elemInGroups,
630 SMESHDS_Mesh * aMesh)
632 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
633 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
634 for ( ; grIt != groups.end(); grIt++ ) {
635 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
636 if ( group && group->SMDSGroup().Contains( elemInGroups ))
637 group->SMDSGroup().Add( elemToAdd );
641 //=======================================================================
642 //function : QuadToTri
643 //purpose : Cut quadrangles into triangles.
644 // theCrit is used to select a diagonal to cut
645 //=======================================================================
647 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
648 const bool the13Diag)
650 MESSAGE( "::QuadToTri()" );
652 SMESHDS_Mesh * aMesh = GetMeshDS();
654 set< const SMDS_MeshElement * >::iterator itElem;
655 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
657 const SMDS_MeshElement* elem = (*itElem);
658 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
661 // retrieve element nodes
662 const SMDS_MeshNode* aNodes [4];
663 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
665 while ( itN->more() )
666 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
668 int aShapeId = FindShape( elem );
669 const SMDS_MeshElement* newElem = 0;
672 aMesh->ChangeElementNodes( elem, aNodes, 3 );
673 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
677 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
678 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
681 // put a new triangle on the same shape and add to the same groups
684 aMesh->SetMeshElementOnShape( newElem, aShapeId );
686 AddToSameGroups( newElem, elem, aMesh );
692 //=======================================================================
693 //function : getAngle
695 //=======================================================================
697 double getAngle(const SMDS_MeshElement * tr1,
698 const SMDS_MeshElement * tr2,
699 const SMDS_MeshNode * n1,
700 const SMDS_MeshNode * n2)
702 double angle = 2*PI; // bad angle
705 SMESH::Controls::TSequenceOfXYZ P1, P2;
706 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
707 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
709 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
710 if ( N1.SquareMagnitude() <= gp::Resolution() )
712 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
713 if ( N2.SquareMagnitude() <= gp::Resolution() )
716 // find the first diagonal node n1 in the triangles:
717 // take in account a diagonal link orientation
718 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
719 for ( int t = 0; t < 2; t++ )
721 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
722 int i = 0, iDiag = -1;
723 while ( it->more()) {
724 const SMDS_MeshElement *n = it->next();
725 if ( n == n1 || n == n2 )
729 if ( i - iDiag == 1 )
730 nFirst[ t ] = ( n == n1 ? n2 : n1 );
738 if ( nFirst[ 0 ] == nFirst[ 1 ] )
741 angle = N1.Angle( N2 );
746 // =================================================
747 // class generating a unique ID for a pair of nodes
748 // and able to return nodes by that ID
749 // =================================================
754 LinkID_Gen( const SMESHDS_Mesh* theMesh )
755 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
758 long GetLinkID (const SMDS_MeshNode * n1,
759 const SMDS_MeshNode * n2) const
761 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
764 bool GetNodes (const long theLinkID,
765 const SMDS_MeshNode* & theNode1,
766 const SMDS_MeshNode* & theNode2) const
768 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
769 if ( !theNode1 ) return false;
770 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
771 if ( !theNode2 ) return false;
777 const SMESHDS_Mesh* myMesh;
781 //=======================================================================
782 //function : TriToQuad
783 //purpose : Fuse neighbour triangles into quadrangles.
784 // theCrit is used to select a neighbour to fuse with.
785 // theMaxAngle is a max angle between element normals at which
786 // fusion is still performed.
787 //=======================================================================
789 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
790 SMESH::Controls::NumericalFunctorPtr theCrit,
791 const double theMaxAngle)
793 MESSAGE( "::TriToQuad()" );
795 if ( !theCrit.get() )
798 SMESHDS_Mesh * aMesh = GetMeshDS();
799 LinkID_Gen aLinkID_Gen( aMesh );
802 // Prepare data for algo: build
803 // 1. map of elements with their linkIDs
804 // 2. map of linkIDs with their elements
806 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
807 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
808 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
809 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
811 set<const SMDS_MeshElement*>::iterator itElem;
812 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
814 const SMDS_MeshElement* elem = (*itElem);
815 if ( !elem || elem->NbNodes() != 3 )
818 // retrieve element nodes
819 const SMDS_MeshNode* aNodes [4];
820 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
822 while ( itN->more() )
823 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
825 aNodes[ 3 ] = aNodes[ 0 ];
828 for ( i = 0; i < 3; i++ )
830 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
831 // check if elements sharing a link can be fused
832 itLE = mapLi_listEl.find( linkID );
833 if ( itLE != mapLi_listEl.end() )
835 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
837 const SMDS_MeshElement* elem2 = (*itLE).second.front();
838 // if ( FindShape( elem ) != FindShape( elem2 ))
839 // continue; // do not fuse triangles laying on different shapes
840 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
841 continue; // avoid making badly shaped quads
842 (*itLE).second.push_back( elem );
845 mapLi_listEl[ linkID ].push_back( elem );
846 mapEl_setLi [ elem ].insert( linkID );
849 // Clean the maps from the links shared by a sole element, ie
850 // links to which only one element is bound in mapLi_listEl
852 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
854 int nbElems = (*itLE).second.size();
856 const SMDS_MeshElement* elem = (*itLE).second.front();
857 long link = (*itLE).first;
858 mapEl_setLi[ elem ].erase( link );
859 if ( mapEl_setLi[ elem ].empty() )
860 mapEl_setLi.erase( elem );
864 // Algo: fuse triangles into quadrangles
866 while ( ! mapEl_setLi.empty() )
868 // Look for the start element:
869 // the element having the least nb of shared links
871 const SMDS_MeshElement* startElem = 0;
873 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
875 int nbLinks = (*itEL).second.size();
876 if ( nbLinks < minNbLinks )
878 startElem = (*itEL).first;
879 minNbLinks = nbLinks;
880 if ( minNbLinks == 1 )
885 // search elements to fuse starting from startElem or links of elements
886 // fused earlyer - startLinks
887 list< long > startLinks;
888 while ( startElem || !startLinks.empty() )
890 while ( !startElem && !startLinks.empty() )
892 // Get an element to start, by a link
893 long linkId = startLinks.front();
894 startLinks.pop_front();
895 itLE = mapLi_listEl.find( linkId );
896 if ( itLE != mapLi_listEl.end() )
898 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
899 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
900 for ( ; itE != listElem.end() ; itE++ )
901 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
903 mapLi_listEl.erase( itLE );
909 // Get candidates to be fused
911 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
914 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
915 set< long >& setLi = mapEl_setLi[ tr1 ];
916 ASSERT( !setLi.empty() );
917 set< long >::iterator itLi;
918 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
920 long linkID = (*itLi);
921 itLE = mapLi_listEl.find( linkID );
922 if ( itLE == mapLi_listEl.end() )
924 const SMDS_MeshElement* elem = (*itLE).second.front();
926 elem = (*itLE).second.back();
927 mapLi_listEl.erase( itLE );
928 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
941 // add other links of elem to list of links to re-start from
942 set< long >& links = mapEl_setLi[ elem ];
943 set< long >::iterator it;
944 for ( it = links.begin(); it != links.end(); it++ )
946 long linkID2 = (*it);
947 if ( linkID2 != linkID )
948 startLinks.push_back( linkID2 );
952 // Get nodes of possible quadrangles
954 const SMDS_MeshNode *n12 [4], *n13 [4];
955 bool Ok12 = false, Ok13 = false;
956 const SMDS_MeshNode *linkNode1, *linkNode2;
958 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
959 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
962 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
963 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
966 // Choose a pair to fuse
970 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
971 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
972 double aBadRate12 = getBadRate( &quad12, theCrit );
973 double aBadRate13 = getBadRate( &quad13, theCrit );
974 if ( aBadRate13 < aBadRate12 )
982 // and remove fused elems and removed links from the maps
984 mapEl_setLi.erase( tr1 );
987 mapEl_setLi.erase( tr2 );
988 mapLi_listEl.erase( link12 );
989 aMesh->ChangeElementNodes( tr1, n12, 4 );
990 aMesh->RemoveElement( tr2 );
994 mapEl_setLi.erase( tr3 );
995 mapLi_listEl.erase( link13 );
996 aMesh->ChangeElementNodes( tr1, n13, 4 );
997 aMesh->RemoveElement( tr3 );
1000 // Next element to fuse: the rejected one
1002 startElem = Ok12 ? tr3 : tr2;
1004 } // if ( startElem )
1005 } // while ( startElem || !startLinks.empty() )
1006 } // while ( ! mapEl_setLi.empty() )
1012 /*#define DUMPSO(txt) \
1013 // cout << txt << endl;
1014 //=============================================================================
1018 //=============================================================================
1019 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1023 int tmp = idNodes[ i1 ];
1024 idNodes[ i1 ] = idNodes[ i2 ];
1025 idNodes[ i2 ] = tmp;
1026 gp_Pnt Ptmp = P[ i1 ];
1029 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1032 //=======================================================================
1033 //function : SortQuadNodes
1034 //purpose : Set 4 nodes of a quadrangle face in a good order.
1035 // Swap 1<->2 or 2<->3 nodes and correspondingly return
1037 //=======================================================================
1039 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1044 for ( i = 0; i < 4; i++ ) {
1045 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1047 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1050 gp_Vec V1(P[0], P[1]);
1051 gp_Vec V2(P[0], P[2]);
1052 gp_Vec V3(P[0], P[3]);
1054 gp_Vec Cross1 = V1 ^ V2;
1055 gp_Vec Cross2 = V2 ^ V3;
1058 if (Cross1.Dot(Cross2) < 0)
1063 if (Cross1.Dot(Cross2) < 0)
1067 swap ( i, i + 1, idNodes, P );
1069 // for ( int ii = 0; ii < 4; ii++ ) {
1070 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1071 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1077 //=======================================================================
1078 //function : SortHexaNodes
1079 //purpose : Set 8 nodes of a hexahedron in a good order.
1080 // Return success status
1081 //=======================================================================
1083 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1088 DUMPSO( "INPUT: ========================================");
1089 for ( i = 0; i < 8; i++ ) {
1090 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1091 if ( !n ) return false;
1092 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1093 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1095 DUMPSO( "========================================");
1098 set<int> faceNodes; // ids of bottom face nodes, to be found
1099 set<int> checkedId1; // ids of tried 2-nd nodes
1100 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1101 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1102 int iMin, iLoop1 = 0;
1104 // Loop to try the 2-nd nodes
1106 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1108 // Find not checked 2-nd node
1109 for ( i = 1; i < 8; i++ )
1110 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1111 int id1 = idNodes[i];
1112 swap ( 1, i, idNodes, P );
1113 checkedId1.insert ( id1 );
1117 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1118 // ie that all but meybe one (id3 which is on the same face) nodes
1119 // lay on the same side from the triangle plane.
1121 bool manyInPlane = false; // more than 4 nodes lay in plane
1123 while ( ++iLoop2 < 6 ) {
1125 // get 1-2-3 plane coeffs
1126 Standard_Real A, B, C, D;
1127 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1128 if ( N.SquareMagnitude() > gp::Resolution() )
1130 gp_Pln pln ( P[0], N );
1131 pln.Coefficients( A, B, C, D );
1133 // find the node (iMin) closest to pln
1134 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1136 for ( i = 3; i < 8; i++ ) {
1137 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1138 if ( fabs( dist[i] ) < minDist ) {
1139 minDist = fabs( dist[i] );
1142 if ( fabs( dist[i] ) <= tol )
1143 idInPln.insert( idNodes[i] );
1146 // there should not be more than 4 nodes in bottom plane
1147 if ( idInPln.size() > 1 )
1149 DUMPSO( "### idInPln.size() = " << idInPln.size());
1150 // idInPlane does not contain the first 3 nodes
1151 if ( manyInPlane || idInPln.size() == 5)
1152 return false; // all nodes in one plane
1155 // set the 1-st node to be not in plane
1156 for ( i = 3; i < 8; i++ ) {
1157 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1158 DUMPSO( "### Reset 0-th node");
1159 swap( 0, i, idNodes, P );
1164 // reset to re-check second nodes
1165 leastDist = DBL_MAX;
1169 break; // from iLoop2;
1172 // check that the other 4 nodes are on the same side
1173 bool sameSide = true;
1174 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1175 for ( i = 3; sameSide && i < 8; i++ ) {
1177 sameSide = ( isNeg == dist[i] <= 0.);
1180 // keep best solution
1181 if ( sameSide && minDist < leastDist ) {
1182 leastDist = minDist;
1184 faceNodes.insert( idNodes[ 1 ] );
1185 faceNodes.insert( idNodes[ 2 ] );
1186 faceNodes.insert( idNodes[ iMin ] );
1187 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1188 << " leastDist = " << leastDist);
1189 if ( leastDist <= DBL_MIN )
1194 // set next 3-d node to check
1195 int iNext = 2 + iLoop2;
1197 DUMPSO( "Try 2-nd");
1198 swap ( 2, iNext, idNodes, P );
1200 } // while ( iLoop2 < 6 )
1203 if ( faceNodes.empty() ) return false;
1205 // Put the faceNodes in proper places
1206 for ( i = 4; i < 8; i++ ) {
1207 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1208 // find a place to put
1210 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1212 DUMPSO( "Set faceNodes");
1213 swap ( iTo, i, idNodes, P );
1218 // Set nodes of the found bottom face in good order
1219 DUMPSO( " Found bottom face: ");
1220 i = SortQuadNodes( theMesh, idNodes );
1222 gp_Pnt Ptmp = P[ i ];
1227 // for ( int ii = 0; ii < 4; ii++ ) {
1228 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1229 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1232 // Gravity center of the top and bottom faces
1233 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1234 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1236 // Get direction from the bottom to the top face
1237 gp_Vec upDir ( aGCb, aGCt );
1238 Standard_Real upDirSize = upDir.Magnitude();
1239 if ( upDirSize <= gp::Resolution() ) return false;
1242 // Assure that the bottom face normal points up
1243 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1244 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1245 if ( Nb.Dot( upDir ) < 0 ) {
1246 DUMPSO( "Reverse bottom face");
1247 swap( 1, 3, idNodes, P );
1250 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1251 Standard_Real minDist = DBL_MAX;
1252 for ( i = 4; i < 8; i++ ) {
1253 // projection of P[i] to the plane defined by P[0] and upDir
1254 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1255 Standard_Real sqDist = P[0].SquareDistance( Pp );
1256 if ( sqDist < minDist ) {
1261 DUMPSO( "Set 4-th");
1262 swap ( 4, iMin, idNodes, P );
1264 // Set nodes of the top face in good order
1265 DUMPSO( "Sort top face");
1266 i = SortQuadNodes( theMesh, &idNodes[4] );
1269 gp_Pnt Ptmp = P[ i ];
1274 // Assure that direction of the top face normal is from the bottom face
1275 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1276 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1277 if ( Nt.Dot( upDir ) < 0 ) {
1278 DUMPSO( "Reverse top face");
1279 swap( 5, 7, idNodes, P );
1282 // DUMPSO( "OUTPUT: ========================================");
1283 // for ( i = 0; i < 8; i++ ) {
1284 // float *p = ugrid->GetPoint(idNodes[i]);
1285 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1291 //=======================================================================
1292 //function : laplacianSmooth
1293 //purpose : pulls theNode toward the center of surrounding nodes directly
1294 // connected to that node along an element edge
1295 //=======================================================================
1297 void laplacianSmooth(const SMDS_MeshNode* theNode,
1298 const Handle(Geom_Surface)& theSurface,
1299 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1301 // find surrounding nodes
1303 set< const SMDS_MeshNode* > nodeSet;
1304 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1305 while ( elemIt->more() )
1307 const SMDS_MeshElement* elem = elemIt->next();
1309 // put all nodes in array
1310 int nbNodes = 0, iNode = 0;
1311 vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1312 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1313 while ( itN->more() )
1315 aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1316 if ( aNodes[ nbNodes ] == theNode )
1317 iNode = nbNodes; // index of theNode within aNodes
1321 int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1322 nodeSet.insert( aNodes[ iAfter ]);
1323 int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1324 nodeSet.insert( aNodes[ iBefore ]);
1327 // compute new coodrs
1329 double coord[] = { 0., 0., 0. };
1330 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1331 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1332 const SMDS_MeshNode* node = (*nodeSetIt);
1333 if ( theSurface.IsNull() ) { // smooth in 3D
1334 coord[0] += node->X();
1335 coord[1] += node->Y();
1336 coord[2] += node->Z();
1338 else { // smooth in 2D
1339 gp_XY* uv = theUVMap[ node ];
1340 coord[0] += uv->X();
1341 coord[1] += uv->Y();
1344 int nbNodes = nodeSet.size();
1345 coord[0] /= nbNodes;
1346 coord[1] /= nbNodes;
1348 if ( !theSurface.IsNull() ) {
1349 theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1350 gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1356 coord[2] /= nbNodes;
1360 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1363 //=======================================================================
1364 //function : centroidalSmooth
1365 //purpose : pulls theNode toward the element-area-weighted centroid of the
1366 // surrounding elements
1367 //=======================================================================
1369 void centroidalSmooth(const SMDS_MeshNode* theNode,
1370 const Handle(Geom_Surface)& theSurface,
1371 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1373 gp_XYZ aNewXYZ(0.,0.,0.);
1374 SMESH::Controls::Area anAreaFunc;
1375 double totalArea = 0.;
1380 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1381 while ( elemIt->more() )
1383 const SMDS_MeshElement* elem = elemIt->next();
1386 gp_XYZ elemCenter(0.,0.,0.);
1387 SMESH::Controls::TSequenceOfXYZ aNodePoints;
1388 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1389 while ( itN->more() )
1391 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1392 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1393 aNodePoints.push_back( aP );
1394 if ( !theSurface.IsNull() ) { // smooth in 2D
1395 gp_XY* uv = theUVMap[ aNode ];
1396 aP.SetCoord( uv->X(), uv->Y(), 0. );
1400 double elemArea = anAreaFunc.GetValue( aNodePoints );
1401 totalArea += elemArea;
1402 elemCenter /= elem->NbNodes();
1403 aNewXYZ += elemCenter * elemArea;
1405 aNewXYZ /= totalArea;
1406 if ( !theSurface.IsNull() ) {
1407 theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1408 aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1413 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1416 //=======================================================================
1417 //function : getClosestUV
1418 //purpose : return UV of closest projection
1419 //=======================================================================
1421 static bool getClosestUV (Extrema_GenExtPS& projector,
1422 const gp_Pnt& point,
1425 projector.Perform( point );
1426 if ( projector.IsDone() ) {
1427 double u, v, minVal = DBL_MAX;
1428 for ( int i = projector.NbExt(); i > 0; i-- )
1429 if ( projector.Value( i ) < minVal ) {
1430 minVal = projector.Value( i );
1431 projector.Point( i ).Parameter( u, v );
1433 result.SetCoord( u, v );
1438 //=======================================================================
1440 //purpose : Smooth theElements during theNbIterations or until a worst
1441 // element has aspect ratio <= theTgtAspectRatio.
1442 // Aspect Ratio varies in range [1.0, inf].
1443 // If theElements is empty, the whole mesh is smoothed.
1444 // theFixedNodes contains additionally fixed nodes. Nodes built
1445 // on edges and boundary nodes are always fixed.
1446 //=======================================================================
1448 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1449 set<const SMDS_MeshNode*> & theFixedNodes,
1450 const SmoothMethod theSmoothMethod,
1451 const int theNbIterations,
1452 double theTgtAspectRatio)
1454 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1456 if ( theTgtAspectRatio < 1.0 )
1457 theTgtAspectRatio = 1.0;
1459 SMESH::Controls::AspectRatio aQualityFunc;
1461 SMESHDS_Mesh* aMesh = GetMeshDS();
1463 if ( theElems.empty() ) {
1464 // add all faces to theElems
1465 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1466 while ( fIt->more() )
1467 theElems.insert( fIt->next() );
1469 // get all face ids theElems are on
1470 set< int > faceIdSet;
1471 set< const SMDS_MeshElement* >::iterator itElem;
1472 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1473 int fId = FindShape( *itElem );
1474 // check that corresponding submesh exists and a shape is face
1476 faceIdSet.find( fId ) == faceIdSet.end() &&
1477 aMesh->MeshElements( fId )) {
1478 TopoDS_Shape F = aMesh->IndexToShape( fId );
1479 if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1480 faceIdSet.insert( fId );
1483 faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1485 // ===============================================
1486 // smooth elements on each TopoDS_Face separately
1487 // ===============================================
1489 set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1490 for ( ; fId != faceIdSet.rend(); ++fId )
1492 // get face surface and submesh
1493 Handle(Geom_Surface) surface;
1494 SMESHDS_SubMesh* faceSubMesh = 0;
1496 double fToler2 = 0, vPeriod = 0., uPeriod = 0.;
1497 double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1498 bool isUPeriodic = false, isVPeriodic = false;
1500 face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1501 surface = BRep_Tool::Surface( face );
1502 faceSubMesh = aMesh->MeshElements( *fId );
1503 fToler2 = BRep_Tool::Tolerance( face );
1505 isUPeriodic = surface->IsUPeriodic();
1507 vPeriod = surface->UPeriod();
1508 isVPeriodic = surface->IsVPeriodic();
1510 uPeriod = surface->VPeriod();
1511 surface->Bounds( u1, u2, v1, v2 );
1513 // ---------------------------------------------------------
1514 // for elements on a face, find movable and fixed nodes and
1515 // compute UV for them
1516 // ---------------------------------------------------------
1517 bool checkBoundaryNodes = false;
1518 set<const SMDS_MeshNode*> setMovableNodes, checkedNodes;
1519 map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1520 list< gp_XY > listUV; // uvs the 2 maps refer to
1521 list< const SMDS_MeshElement* > elemsOnFace;
1523 Extrema_GenExtPS projector;
1524 GeomAdaptor_Surface surfAdaptor;
1525 if ( !surface.IsNull() ) {
1526 surfAdaptor.Load( surface );
1527 projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1529 int nbElemOnFace = 0;
1530 itElem = theElems.begin();
1531 while ( itElem != theElems.end() ) // loop on not yet smoothed elements
1533 const SMDS_MeshElement* elem = (*itElem);
1534 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1535 ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1539 elemsOnFace.push_back( elem );
1540 theElems.erase( itElem++ );
1543 // loop on elem nodes
1544 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1545 while ( itN->more() )
1547 const SMDS_MeshNode* node =
1548 static_cast<const SMDS_MeshNode*>( itN->next() );
1549 if ( !checkedNodes.insert( node ).second )
1553 bool project = !surface.IsNull();
1554 gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1555 const SMDS_PositionPtr& pos = node->GetPosition();
1556 SMDS_TypeOfPosition posType = SMDS_TOP_3DSPACE;
1557 if ( faceSubMesh && pos.get() ) {
1558 posType = pos->GetTypeOfPosition();
1559 if ( posType == SMDS_TOP_FACE ) {
1560 SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1561 uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1562 gp_Pnt pSurf = surface->Value( uv.X(), uv.Y() );
1563 project = pSurf.SquareDistance( pNode ) > fToler2;
1567 if ( !getClosestUV( projector, pNode, uv ))
1568 MESSAGE("Node Projection Failed " << node);
1570 uv.SetX( ElCLib::InPeriod( uv.X(), u1, u2 ));
1572 uv.SetY( ElCLib::InPeriod( uv.Y(), v1, v2 ));
1574 if ( !surface.IsNull() ) {
1575 listUV.push_back( uv );
1576 uvMap.insert( make_pair( node, &listUV.back() ));
1579 if ( posType == SMDS_TOP_3DSPACE )
1580 checkBoundaryNodes = true;
1583 if (posType != SMDS_TOP_EDGE &&
1584 posType != SMDS_TOP_VERTEX &&
1585 theFixedNodes.find( node ) == theFixedNodes.end())
1587 // check if all faces around the node are on faceSubMesh
1588 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1590 while ( eIt->more() && all ) {
1591 const SMDS_MeshElement* e = eIt->next();
1592 if ( e->GetType() == SMDSAbs_Face )
1593 all = faceSubMesh->Contains( e );
1596 setMovableNodes.insert( node );
1598 checkBoundaryNodes = true;
1601 } // loop on elem nodes
1603 if ( nbElemOnFace == faceSubMesh->NbElements() )
1604 break; // all elements found
1606 } // loop on not yet smoothed elements
1608 if ( !faceSubMesh || elemsOnFace.size() != nbElemOnFace )
1609 checkBoundaryNodes = true;
1611 // fix nodes on boundary of elemsOnFace
1613 if ( checkBoundaryNodes )
1615 typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1616 map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1617 map< TLink, int >::iterator link_nb;
1618 // put all elements links to linkNbMap
1619 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1620 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1622 // put elem nodes in array
1623 vector< const SMDS_MeshNode* > nodes;
1624 nodes.reserve( (*elemIt)->NbNodes() + 1 );
1625 SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1626 while ( itN->more() )
1627 nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1628 nodes.push_back( nodes.front() );
1629 // loop on elem links: insert them in linkNbMap
1630 for ( int iN = 1; iN < nodes.size(); ++iN ) {
1632 if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1633 link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1635 link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1636 link_nb = linkNbMap.find( link );
1637 if ( link_nb == linkNbMap.end() )
1638 linkNbMap.insert( make_pair ( link, 1 ));
1643 // remove nodes that are in links encountered only once from setMovableNodes
1644 for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1645 if ( link_nb->second == 1 ) {
1646 setMovableNodes.erase( link_nb->first.first );
1647 setMovableNodes.erase( link_nb->first.second );
1652 // -----------------------------------------------------
1653 // for nodes on seam edge, compute one more UV ( uvMap2 );
1654 // find movable nodes linked to nodes on seam and which
1655 // are to be smoothed using the second UV ( uvMap2 )
1656 // -----------------------------------------------------
1658 set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1659 if ( !surface.IsNull() )
1661 TopExp_Explorer eExp( face, TopAbs_EDGE );
1662 for ( ; eExp.More(); eExp.Next() )
1664 TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1665 if ( !BRep_Tool::IsClosed( edge, face ))
1667 SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1668 if ( !sm ) continue;
1669 // find out which parameter varies for a node on seam
1672 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1673 if ( pcurve.IsNull() ) continue;
1674 uv1 = pcurve->Value( f );
1676 pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1677 if ( pcurve.IsNull() ) continue;
1678 uv2 = pcurve->Value( f );
1679 int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1681 if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1682 gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1684 // get nodes on seam and its vertices
1685 list< const SMDS_MeshNode* > seamNodes;
1686 SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1687 while ( nSeamIt->more() )
1688 seamNodes.push_back( nSeamIt->next() );
1689 TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1690 for ( ; vExp.More(); vExp.Next() ) {
1691 sm = aMesh->MeshElements( vExp.Current() );
1693 nSeamIt = sm->GetNodes();
1694 while ( nSeamIt->more() )
1695 seamNodes.push_back( nSeamIt->next() );
1698 // loop on nodes on seam
1699 list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1700 for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1702 const SMDS_MeshNode* nSeam = *noSeIt;
1703 map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1704 if ( n_uv == uvMap.end() )
1707 n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1708 // set the second UV
1709 listUV.push_back( *n_uv->second );
1710 listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1711 if ( uvMap2.empty() )
1712 uvMap2 = uvMap; // copy the uvMap contents
1713 uvMap2[ nSeam ] = &listUV.back();
1715 // collect movable nodes linked to ones on seam in nodesNearSeam
1716 SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1717 while ( eIt->more() )
1719 const SMDS_MeshElement* e = eIt->next();
1720 if ( e->GetType() != SMDSAbs_Face )
1722 int nbUseMap1 = 0, nbUseMap2 = 0;
1723 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1724 while ( nIt->more() )
1726 const SMDS_MeshNode* n =
1727 static_cast<const SMDS_MeshNode*>( nIt->next() );
1729 setMovableNodes.find( n ) == setMovableNodes.end() )
1731 // add only nodes being closer to uv2 than to uv1
1732 gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1733 0.5 * ( n->Y() + nSeam->Y() ),
1734 0.5 * ( n->Z() + nSeam->Z() ));
1736 getClosestUV( projector, pMid, uv );
1737 if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1738 nodesNearSeam.insert( n );
1744 // for centroidalSmooth all element nodes must
1745 // be on one side of a seam
1746 if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1748 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1749 while ( nIt->more() ) {
1750 const SMDS_MeshNode* n =
1751 static_cast<const SMDS_MeshNode*>( nIt->next() );
1752 setMovableNodes.erase( n );
1756 } // loop on nodes on seam
1757 } // loop on edge of a face
1758 } // if ( !face.IsNull() )
1764 set<const SMDS_MeshNode*>::iterator nodeToMove;
1766 double maxRatio = -1., maxDisplacement = -1.;
1767 for ( it = 0; it < theNbIterations; it++ )
1769 maxDisplacement = 0.;
1770 nodeToMove = setMovableNodes.begin();
1771 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1773 const SMDS_MeshNode* node = (*nodeToMove);
1774 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1777 bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1778 if ( theSmoothMethod == LAPLACIAN )
1779 laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1781 centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1783 // node displacement
1784 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1785 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1786 if ( aDispl > maxDisplacement )
1787 maxDisplacement = aDispl;
1789 // no node movement => exit
1790 if ( maxDisplacement < 1.e-16 ) {
1791 MESSAGE("-- no node movement --");
1795 // check elements quality
1797 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1799 const SMDS_MeshElement* elem = (*itElem);
1800 if ( !elem || elem->GetType() != SMDSAbs_Face )
1802 SMESH::Controls::TSequenceOfXYZ aPoints;
1803 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1804 double aValue = aQualityFunc.GetValue( aPoints );
1805 if ( aValue > maxRatio )
1809 if ( maxRatio <= theTgtAspectRatio ) {
1810 MESSAGE("-- quality achived --");
1813 if (it+1 == theNbIterations) {
1814 MESSAGE("-- Iteration limit exceeded --");
1816 } // smoothing iterations
1818 MESSAGE(" Face id: " << *fId <<
1819 " Nb iterstions: " << it <<
1820 " Displacement: " << maxDisplacement <<
1821 " Aspect Ratio " << maxRatio);
1823 // ---------------------------------------
1824 // new nodes positions are computed,
1825 // record movement in DS and set new UV
1826 // ---------------------------------------
1828 nodeToMove = setMovableNodes.begin();
1829 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1831 SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1832 aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1833 map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1834 if ( node_uv != uvMap.end() ) {
1835 gp_XY* uv = node_uv->second;
1837 ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1841 } // loop on face ids
1844 //=======================================================================
1845 //function : isReverse
1846 //purpose : Return true if normal of prevNodes is not co-directied with
1847 // gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1848 // iNotSame is where prevNodes and nextNodes are different
1849 //=======================================================================
1851 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1852 const SMDS_MeshNode* nextNodes[],
1856 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1857 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1859 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1860 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1861 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1862 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1864 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1865 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1866 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1867 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1869 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1871 return (vA ^ vB) * vN < 0.0;
1874 //=======================================================================
1875 //function : sweepElement
1877 //=======================================================================
1879 static void sweepElement(SMESHDS_Mesh* aMesh,
1880 const SMDS_MeshElement* elem,
1881 const vector<TNodeOfNodeListMapItr> & newNodesItVec,
1882 list<const SMDS_MeshElement*>& newElems)
1884 // Loop on elem nodes:
1885 // find new nodes and detect same nodes indices
1886 int nbNodes = elem->NbNodes();
1887 list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
1888 const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
1889 int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
1891 for ( iNode = 0; iNode < nbNodes; iNode++ )
1893 TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
1894 const SMDS_MeshNode* node = nnIt->first;
1895 const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
1896 if ( listNewNodes.empty() )
1899 itNN[ iNode ] = listNewNodes.begin();
1900 prevNod[ iNode ] = node;
1901 nextNod[ iNode ] = listNewNodes.front();
1902 if ( prevNod[ iNode ] != nextNod [ iNode ])
1903 iNotSameNode = iNode;
1909 if ( nbSame == nbNodes || nbSame > 2) {
1910 MESSAGE( " Too many same nodes of element " << elem->GetID() );
1914 int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
1916 iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
1917 iAfterSame = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
1918 iOpposSame = ( iSameNode - 2 < 0 ? iSameNode + 2 : iSameNode - 2 );
1921 // check element orientation
1923 if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
1924 //MESSAGE("Reversed elem " << elem );
1928 int iAB = iAfterSame + iBeforeSame;
1929 iBeforeSame = iAB - iBeforeSame;
1930 iAfterSame = iAB - iAfterSame;
1934 // make new elements
1935 int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
1936 for (iStep = 0; iStep < nbSteps; iStep++ )
1939 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
1940 nextNod[ iNode ] = *itNN[ iNode ];
1943 SMDS_MeshElement* aNewElem = 0;
1950 aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
1956 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
1957 nextNod[ 1 ], nextNod[ 0 ] );
1959 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
1960 nextNod[ iNotSameNode ] );
1963 case 3: { // TRIANGLE
1965 if ( nbSame == 0 ) // --- pentahedron
1966 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1967 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
1969 else if ( nbSame == 1 ) // --- pyramid
1970 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iBeforeSame ],
1971 nextNod[ iBeforeSame ], nextNod[ iAfterSame ],
1972 nextNod[ iSameNode ]);
1974 else // 2 same nodes: --- tetrahedron
1975 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1976 nextNod[ iNotSameNode ]);
1979 case 4: { // QUADRANGLE
1981 if ( nbSame == 0 ) // --- hexahedron
1982 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
1983 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
1985 else if ( nbSame == 1 ) // --- pyramid + pentahedron
1987 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iBeforeSame ],
1988 nextNod[ iBeforeSame ], nextNod[ iAfterSame ],
1989 nextNod[ iSameNode ]);
1990 newElems.push_back( aNewElem );
1991 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
1992 prevNod[ iAfterSame ], nextNod[ iBeforeSame ],
1993 nextNod[ iOpposSame ], nextNod[ iAfterSame ] );
1995 else if ( nbSame == 2 ) // pentahedron
1997 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
1998 // iBeforeSame is same too
1999 aNewElem = aMesh->AddVolume (prevNod[ iOpposSame ], prevNod[ iBeforeSame ],
2000 nextNod[ iOpposSame ], prevNod[ iAfterSame ],
2001 prevNod[ iSameNode ], nextNod[ iAfterSame ]);
2003 // iAfterSame is same too
2004 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iSameNode ],
2005 nextNod[ iBeforeSame ], prevNod[ iOpposSame ],
2006 prevNod[ iAfterSame ], nextNod[ iOpposSame ]);
2011 // realized for extrusion only
2012 vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2013 vector<int> quantities (nbNodes + 2);
2015 quantities[0] = nbNodes; // bottom of prism
2016 for (int inode = 0; inode < nbNodes; inode++) {
2017 polyedre_nodes[inode] = prevNod[inode];
2020 quantities[1] = nbNodes; // top of prism
2021 for (int inode = 0; inode < nbNodes; inode++) {
2022 polyedre_nodes[nbNodes + inode] = nextNod[inode];
2025 for (int iface = 0; iface < nbNodes; iface++) {
2026 quantities[iface + 2] = 4;
2027 int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2028 polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2029 polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2030 polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2031 polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2033 aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2037 newElems.push_back( aNewElem );
2039 // set new prev nodes
2040 for ( iNode = 0; iNode < nbNodes; iNode++ )
2041 prevNod[ iNode ] = nextNod[ iNode ];
2046 //=======================================================================
2047 //function : makeWalls
2048 //purpose : create 1D and 2D elements around swept elements
2049 //=======================================================================
2051 static void makeWalls (SMESHDS_Mesh* aMesh,
2052 TNodeOfNodeListMap & mapNewNodes,
2053 TElemOfElemListMap & newElemsMap,
2054 TElemOfVecOfNnlmiMap & elemNewNodesMap,
2055 set<const SMDS_MeshElement*>& elemSet)
2057 ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2059 // Find nodes belonging to only one initial element - sweep them to get edges.
2061 TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2062 for ( ; nList != mapNewNodes.end(); nList++ )
2064 const SMDS_MeshNode* node =
2065 static_cast<const SMDS_MeshNode*>( nList->first );
2066 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2067 int nbInitElems = 0;
2068 while ( eIt->more() && nbInitElems < 2 )
2069 if ( elemSet.find( eIt->next() ) != elemSet.end() )
2071 if ( nbInitElems < 2 ) {
2072 vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2073 list<const SMDS_MeshElement*> newEdges;
2074 sweepElement( aMesh, node, newNodesItVec, newEdges );
2078 // Make a ceiling for each element ie an equal element of last new nodes.
2079 // Find free links of faces - make edges and sweep them into faces.
2081 TElemOfElemListMap::iterator itElem = newElemsMap.begin();
2082 TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2083 for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2085 const SMDS_MeshElement* elem = itElem->first;
2086 vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2088 if ( elem->GetType() == SMDSAbs_Edge )
2090 // create a ceiling edge
2091 aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2092 vecNewNodes[ 1 ]->second.back() );
2094 if ( elem->GetType() != SMDSAbs_Face )
2097 bool hasFreeLinks = false;
2099 set<const SMDS_MeshElement*> avoidSet;
2100 avoidSet.insert( elem );
2102 // loop on a face nodes
2103 set<const SMDS_MeshNode*> aFaceLastNodes;
2104 int iNode, nbNodes = vecNewNodes.size();
2105 for ( iNode = 0; iNode < nbNodes; iNode++ )
2107 aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2108 // look for free links of a face
2109 int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2110 const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2111 const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2112 // check if a link is free
2113 if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2115 hasFreeLinks = true;
2116 // make an edge and a ceiling for a new edge
2117 if ( !aMesh->FindEdge( n1, n2 ))
2118 aMesh->AddEdge( n1, n2 );
2119 n1 = vecNewNodes[ iNode ]->second.back();
2120 n2 = vecNewNodes[ iNext ]->second.back();
2121 if ( !aMesh->FindEdge( n1, n2 ))
2122 aMesh->AddEdge( n1, n2 );
2125 // sweep free links into faces
2129 list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2130 int iStep, nbSteps = vecNewNodes[0]->second.size();
2131 int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2133 set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2134 for ( iNode = 0; iNode < nbNodes; iNode++ )
2135 initNodeSet.insert( vecNewNodes[ iNode ]->first );
2137 for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2139 list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2141 while ( iVol++ < volNb ) v++;
2142 // find indices of free faces of a volume
2144 SMDS_VolumeTool vTool( *v );
2145 int iF, nbF = vTool.NbFaces();
2146 for ( iF = 0; iF < nbF; iF ++ )
2147 if (vTool.IsFreeFace( iF ) &&
2148 vTool.GetFaceNodes( iF, faceNodeSet ) &&
2149 initNodeSet != faceNodeSet) // except an initial face
2150 fInd.push_back( iF );
2154 // create faces for all steps
2155 for ( iStep = 0; iStep < nbSteps; iStep++ )
2158 vTool.SetExternalNormal();
2159 list< int >::iterator ind = fInd.begin();
2160 for ( ; ind != fInd.end(); ind++ )
2162 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2163 switch ( vTool.NbFaceNodes( *ind ) ) {
2165 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2167 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2170 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2171 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2172 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2173 polygon_nodes[inode] = nodes[inode];
2175 aMesh->AddPolygonalFace(polygon_nodes);
2180 // go to the next volume
2182 while ( iVol++ < nbVolumesByStep ) v++;
2185 } // sweep free links into faces
2187 // make a ceiling face with a normal external to a volume
2189 SMDS_VolumeTool lastVol( itElem->second.back() );
2190 int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2193 lastVol.SetExternalNormal();
2194 const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2195 switch ( lastVol.NbFaceNodes( iF ) ) {
2197 if (!hasFreeLinks ||
2198 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2199 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2202 if (!hasFreeLinks ||
2203 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2204 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2208 int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2209 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2210 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2211 polygon_nodes[inode] = nodes[inode];
2213 if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2214 aMesh->AddPolygonalFace(polygon_nodes);
2220 } // loop on swept elements
2223 //=======================================================================
2224 //function : RotationSweep
2226 //=======================================================================
2228 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2229 const gp_Ax1& theAxis,
2230 const double theAngle,
2231 const int theNbSteps,
2232 const double theTol)
2234 MESSAGE( "RotationSweep()");
2236 aTrsf.SetRotation( theAxis, theAngle );
2238 gp_Lin aLine( theAxis );
2239 double aSqTol = theTol * theTol;
2241 SMESHDS_Mesh* aMesh = GetMeshDS();
2243 TNodeOfNodeListMap mapNewNodes;
2244 TElemOfVecOfNnlmiMap mapElemNewNodes;
2245 TElemOfElemListMap newElemsMap;
2248 set< const SMDS_MeshElement* >::iterator itElem;
2249 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2251 const SMDS_MeshElement* elem = (*itElem);
2254 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2255 newNodesItVec.reserve( elem->NbNodes() );
2257 // loop on elem nodes
2258 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2259 while ( itN->more() ) {
2261 // check if a node has been already sweeped
2262 const SMDS_MeshNode* node =
2263 static_cast<const SMDS_MeshNode*>( itN->next() );
2264 TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2265 if ( nIt == mapNewNodes.end() )
2267 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2268 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2271 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2273 aXYZ.Coord( coord[0], coord[1], coord[2] );
2274 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2275 const SMDS_MeshNode * newNode = node;
2276 for ( int i = 0; i < theNbSteps; i++ ) {
2278 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2279 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2281 listNewNodes.push_back( newNode );
2284 newNodesItVec.push_back( nIt );
2286 // make new elements
2287 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2290 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2293 //=======================================================================
2294 //function : ExtrusionSweep
2296 //=======================================================================
2298 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
2299 const gp_Vec& theStep,
2300 const int theNbSteps)
2303 aTrsf.SetTranslation( theStep );
2305 SMESHDS_Mesh* aMesh = GetMeshDS();
2307 TNodeOfNodeListMap mapNewNodes;
2308 TElemOfVecOfNnlmiMap mapElemNewNodes;
2309 TElemOfElemListMap newElemsMap;
2312 set< const SMDS_MeshElement* >::iterator itElem;
2313 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2315 // check element type
2316 const SMDS_MeshElement* elem = (*itElem);
2320 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2321 newNodesItVec.reserve( elem->NbNodes() );
2323 // loop on elem nodes
2324 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2325 while ( itN->more() ) {
2327 // check if a node has been already sweeped
2328 const SMDS_MeshNode* node =
2329 static_cast<const SMDS_MeshNode*>( itN->next() );
2330 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2331 if ( nIt == mapNewNodes.end() )
2333 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2334 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2337 double coord[] = { node->X(), node->Y(), node->Z() };
2338 for ( int i = 0; i < theNbSteps; i++ ) {
2339 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2340 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2341 listNewNodes.push_back( newNode );
2344 newNodesItVec.push_back( nIt );
2346 // make new elements
2347 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2349 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2352 //=======================================================================
2353 //class : SMESH_MeshEditor_PathPoint
2354 //purpose : auxiliary class
2355 //=======================================================================
2356 class SMESH_MeshEditor_PathPoint {
2358 SMESH_MeshEditor_PathPoint() {
2359 myPnt.SetCoord(99., 99., 99.);
2360 myTgt.SetCoord(1.,0.,0.);
2364 void SetPnt(const gp_Pnt& aP3D){
2367 void SetTangent(const gp_Dir& aTgt){
2370 void SetAngle(const double& aBeta){
2373 void SetParameter(const double& aPrm){
2376 const gp_Pnt& Pnt()const{
2379 const gp_Dir& Tangent()const{
2382 double Angle()const{
2385 double Parameter()const{
2396 //=======================================================================
2397 //function : ExtrusionAlongTrack
2399 //=======================================================================
2400 SMESH_MeshEditor::Extrusion_Error
2401 SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2402 SMESH_subMesh* theTrack,
2403 const SMDS_MeshNode* theN1,
2404 const bool theHasAngles,
2405 std::list<double>& theAngles,
2406 const bool theHasRefPoint,
2407 const gp_Pnt& theRefPoint)
2409 MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2410 int j, aNbTP, aNbE, aNb;
2411 double aT1, aT2, aT, aAngle, aX, aY, aZ;
2412 std::list<double> aPrms;
2413 std::list<double>::iterator aItD;
2414 std::set< const SMDS_MeshElement* >::iterator itElem;
2416 Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2420 Handle(Geom_Curve) aC3D;
2421 TopoDS_Edge aTrackEdge;
2422 TopoDS_Vertex aV1, aV2;
2424 SMDS_ElemIteratorPtr aItE;
2425 SMDS_NodeIteratorPtr aItN;
2426 SMDSAbs_ElementType aTypeE;
2428 TNodeOfNodeListMap mapNewNodes;
2429 TElemOfVecOfNnlmiMap mapElemNewNodes;
2430 TElemOfElemListMap newElemsMap;
2433 aTolVec2=aTolVec*aTolVec;
2436 aNbE = theElements.size();
2439 return EXTR_NO_ELEMENTS;
2441 // 1.1 Track Pattern
2444 SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2446 aItE = pSubMeshDS->GetElements();
2447 while ( aItE->more() ) {
2448 const SMDS_MeshElement* pE = aItE->next();
2449 aTypeE = pE->GetType();
2450 // Pattern must contain links only
2451 if ( aTypeE != SMDSAbs_Edge )
2452 return EXTR_PATH_NOT_EDGE;
2455 const TopoDS_Shape& aS = theTrack->GetSubShape();
2456 // Sub shape for the Pattern must be an Edge
2457 if ( aS.ShapeType() != TopAbs_EDGE )
2458 return EXTR_BAD_PATH_SHAPE;
2460 aTrackEdge = TopoDS::Edge( aS );
2461 // the Edge must not be degenerated
2462 if ( BRep_Tool::Degenerated( aTrackEdge ) )
2463 return EXTR_BAD_PATH_SHAPE;
2465 TopExp::Vertices( aTrackEdge, aV1, aV2 );
2466 aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2467 aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2469 aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2470 const SMDS_MeshNode* aN1 = aItN->next();
2472 aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2473 const SMDS_MeshNode* aN2 = aItN->next();
2475 // starting node must be aN1 or aN2
2476 if ( !( aN1 == theN1 || aN2 == theN1 ) )
2477 return EXTR_BAD_STARTING_NODE;
2479 aNbTP = pSubMeshDS->NbNodes() + 2;
2482 vector<double> aAngles( aNbTP );
2484 for ( j=0; j < aNbTP; ++j ) {
2488 if ( theHasAngles ) {
2489 aItD = theAngles.begin();
2490 for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2492 aAngles[j] = aAngle;
2496 // 2. Collect parameters on the track edge
2497 aPrms.push_back( aT1 );
2498 aPrms.push_back( aT2 );
2500 aItN = pSubMeshDS->GetNodes();
2501 while ( aItN->more() ) {
2502 const SMDS_MeshNode* pNode = aItN->next();
2503 const SMDS_EdgePosition* pEPos =
2504 static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2505 aT = pEPos->GetUParameter();
2506 aPrms.push_back( aT );
2511 if ( aN1 == theN1 ) {
2523 SMESH_MeshEditor_PathPoint aPP;
2524 vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2526 aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2528 aItD = aPrms.begin();
2529 for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2531 aC3D->D1( aT, aP3D, aVec );
2532 aL2 = aVec.SquareMagnitude();
2533 if ( aL2 < aTolVec2 )
2534 return EXTR_CANT_GET_TANGENT;
2536 gp_Dir aTgt( aVec );
2537 aAngle = aAngles[j];
2540 aPP.SetTangent( aTgt );
2541 aPP.SetAngle( aAngle );
2542 aPP.SetParameter( aT );
2546 // 3. Center of rotation aV0
2548 if ( !theHasRefPoint ) {
2550 aGC.SetCoord( 0.,0.,0. );
2552 itElem = theElements.begin();
2553 for ( ; itElem != theElements.end(); itElem++ ) {
2554 const SMDS_MeshElement* elem = (*itElem);
2556 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2557 while ( itN->more() ) {
2558 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2563 if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2564 list<const SMDS_MeshNode*> aLNx;
2565 mapNewNodes[node] = aLNx;
2567 gp_XYZ aXYZ( aX, aY, aZ );
2575 } // if (!theHasRefPoint) {
2576 mapNewNodes.clear();
2578 // 4. Processing the elements
2579 SMESHDS_Mesh* aMesh = GetMeshDS();
2581 for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2582 // check element type
2583 const SMDS_MeshElement* elem = (*itElem);
2584 aTypeE = elem->GetType();
2585 if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2588 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2589 newNodesItVec.reserve( elem->NbNodes() );
2591 // loop on elem nodes
2592 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2593 while ( itN->more() ) {
2595 // check if a node has been already processed
2596 const SMDS_MeshNode* node =
2597 static_cast<const SMDS_MeshNode*>( itN->next() );
2598 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2599 if ( nIt == mapNewNodes.end() ) {
2600 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2601 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2604 aX = node->X(); aY = node->Y(); aZ = node->Z();
2606 Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2607 gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2608 gp_Ax1 anAx1, anAxT1T0;
2609 gp_Dir aDT1x, aDT0x, aDT1T0;
2614 aPN0.SetCoord(aX, aY, aZ);
2616 const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2618 aDT0x= aPP0.Tangent();
2620 for ( j = 1; j < aNbTP; ++j ) {
2621 const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2623 aDT1x = aPP1.Tangent();
2624 aAngle1x = aPP1.Angle();
2626 gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2628 gp_Vec aV01x( aP0x, aP1x );
2629 aTrsf.SetTranslation( aV01x );
2632 aV1x = aV0x.Transformed( aTrsf );
2633 aPN1 = aPN0.Transformed( aTrsf );
2635 // rotation 1 [ T1,T0 ]
2636 aAngleT1T0=-aDT1x.Angle( aDT0x );
2637 if (fabs(aAngleT1T0) > aTolAng) {
2639 anAxT1T0.SetLocation( aV1x );
2640 anAxT1T0.SetDirection( aDT1T0 );
2641 aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2643 aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2647 if ( theHasAngles ) {
2648 anAx1.SetLocation( aV1x );
2649 anAx1.SetDirection( aDT1x );
2650 aTrsfRot.SetRotation( anAx1, aAngle1x );
2652 aPN1 = aPN1.Transformed( aTrsfRot );
2659 const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2660 listNewNodes.push_back( newNode );
2668 newNodesItVec.push_back( nIt );
2670 // make new elements
2671 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2674 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2679 //=======================================================================
2680 //function : Transform
2682 //=======================================================================
2684 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2685 const gp_Trsf& theTrsf,
2689 switch ( theTrsf.Form() ) {
2695 needReverse = false;
2698 SMESHDS_Mesh* aMesh = GetMeshDS();
2700 // map old node to new one
2701 TNodeNodeMap nodeMap;
2703 // elements sharing moved nodes; those of them which have all
2704 // nodes mirrored but are not in theElems are to be reversed
2705 set<const SMDS_MeshElement*> inverseElemSet;
2708 set< const SMDS_MeshElement* >::iterator itElem;
2709 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2711 const SMDS_MeshElement* elem = (*itElem);
2715 // loop on elem nodes
2716 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2717 while ( itN->more() ) {
2719 // check if a node has been already transformed
2720 const SMDS_MeshNode* node =
2721 static_cast<const SMDS_MeshNode*>( itN->next() );
2722 if (nodeMap.find( node ) != nodeMap.end() )
2726 coord[0] = node->X();
2727 coord[1] = node->Y();
2728 coord[2] = node->Z();
2729 theTrsf.Transforms( coord[0], coord[1], coord[2] );
2730 const SMDS_MeshNode * newNode = node;
2732 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2734 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2735 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2737 // keep inverse elements
2738 if ( !theCopy && needReverse ) {
2739 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2740 while ( invElemIt->more() )
2741 inverseElemSet.insert( invElemIt->next() );
2746 // either new elements are to be created
2747 // or a mirrored element are to be reversed
2748 if ( !theCopy && !needReverse)
2751 if ( !inverseElemSet.empty()) {
2752 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2753 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2754 theElems.insert( *invElemIt );
2757 // replicate or reverse elements
2760 REV_TETRA = 0, // = nbNodes - 4
2761 REV_PYRAMID = 1, // = nbNodes - 4
2762 REV_PENTA = 2, // = nbNodes - 4
2764 REV_HEXA = 4, // = nbNodes - 4
2768 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
2769 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
2770 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
2771 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
2772 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
2773 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
2776 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2778 const SMDS_MeshElement* elem = (*itElem);
2779 if ( !elem || elem->GetType() == SMDSAbs_Node )
2782 int nbNodes = elem->NbNodes();
2783 int elemType = elem->GetType();
2785 if (elem->IsPoly()) {
2786 // Polygon or Polyhedral Volume
2787 switch ( elemType ) {
2790 vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2792 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2793 while (itN->more()) {
2794 const SMDS_MeshNode* node =
2795 static_cast<const SMDS_MeshNode*>(itN->next());
2796 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2797 if (nodeMapIt == nodeMap.end())
2798 break; // not all nodes transformed
2800 // reverse mirrored faces and volumes
2801 poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2803 poly_nodes[iNode] = (*nodeMapIt).second;
2807 if ( iNode != nbNodes )
2808 continue; // not all nodes transformed
2811 aMesh->AddPolygonalFace(poly_nodes);
2813 aMesh->ChangePolygonNodes(elem, poly_nodes);
2817 case SMDSAbs_Volume:
2819 // ATTENTION: Reversing is not yet done!!!
2820 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2821 (const SMDS_PolyhedralVolumeOfNodes*) elem;
2823 MESSAGE("Warning: bad volumic element");
2827 vector<const SMDS_MeshNode*> poly_nodes;
2828 vector<int> quantities;
2830 bool allTransformed = true;
2831 int nbFaces = aPolyedre->NbFaces();
2832 for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2833 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2834 for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2835 const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
2836 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2837 if (nodeMapIt == nodeMap.end()) {
2838 allTransformed = false; // not all nodes transformed
2840 poly_nodes.push_back((*nodeMapIt).second);
2843 quantities.push_back(nbFaceNodes);
2845 if ( !allTransformed )
2846 continue; // not all nodes transformed
2849 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
2851 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
2861 int* i = index[ FORWARD ];
2862 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2863 if ( elemType == SMDSAbs_Face )
2864 i = index[ REV_FACE ];
2866 i = index[ nbNodes - 4 ];
2868 // find transformed nodes
2869 const SMDS_MeshNode* nodes[8];
2871 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2872 while ( itN->more() )
2874 const SMDS_MeshNode* node =
2875 static_cast<const SMDS_MeshNode*>( itN->next() );
2876 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
2877 if ( nodeMapIt == nodeMap.end() )
2878 break; // not all nodes transformed
2879 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
2881 if ( iNode != nbNodes )
2882 continue; // not all nodes transformed
2886 // add a new element
2887 switch ( elemType ) {
2889 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
2893 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2895 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
2897 case SMDSAbs_Volume:
2899 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
2900 else if ( nbNodes == 8 )
2901 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2902 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
2903 else if ( nbNodes == 6 )
2904 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2905 nodes[ 4 ], nodes[ 5 ]);
2906 else if ( nbNodes == 5 )
2907 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2915 // reverse element as it was reversed by transformation
2917 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
2922 //=======================================================================
2923 //function : FindCoincidentNodes
2924 //purpose : Return list of group of nodes close to each other within theTolerance
2925 // Search among theNodes or in the whole mesh if theNodes is empty.
2926 //=======================================================================
2928 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
2929 const double theTolerance,
2930 TListOfListOfNodes & theGroupsOfNodes)
2932 double tol2 = theTolerance * theTolerance;
2934 list<const SMDS_MeshNode*> nodes;
2935 if ( theNodes.empty() )
2936 { // get all nodes in the mesh
2937 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
2938 while ( nIt->more() )
2939 nodes.push_back( nIt->next() );
2943 nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
2946 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
2947 for ( ; it1 != nodes.end(); it1++ )
2949 const SMDS_MeshNode* n1 = *it1;
2950 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
2952 list<const SMDS_MeshNode*> * groupPtr = 0;
2954 for ( it2++; it2 != nodes.end(); it2++ )
2956 const SMDS_MeshNode* n2 = *it2;
2957 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
2958 if ( p1.SquareDistance( p2 ) <= tol2 )
2961 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
2962 groupPtr = & theGroupsOfNodes.back();
2963 groupPtr->push_back( n1 );
2965 groupPtr->push_back( n2 );
2966 it2 = nodes.erase( it2 );
2973 //=======================================================================
2974 //function : SimplifyFace
2976 //=======================================================================
2977 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
2978 vector<const SMDS_MeshNode *>& poly_nodes,
2979 vector<int>& quantities) const
2981 int nbNodes = faceNodes.size();
2986 set<const SMDS_MeshNode*> nodeSet;
2988 // get simple seq of nodes
2989 const SMDS_MeshNode* simpleNodes[ nbNodes ];
2990 int iSimple = 0, nbUnique = 0;
2992 simpleNodes[iSimple++] = faceNodes[0];
2994 for (int iCur = 1; iCur < nbNodes; iCur++) {
2995 if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
2996 simpleNodes[iSimple++] = faceNodes[iCur];
2997 if (nodeSet.insert( faceNodes[iCur] ).second)
3001 int nbSimple = iSimple;
3002 if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3012 bool foundLoop = (nbSimple > nbUnique);
3015 set<const SMDS_MeshNode*> loopSet;
3016 for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3017 const SMDS_MeshNode* n = simpleNodes[iSimple];
3018 if (!loopSet.insert( n ).second) {
3022 int iC = 0, curLast = iSimple;
3023 for (; iC < curLast; iC++) {
3024 if (simpleNodes[iC] == n) break;
3026 int loopLen = curLast - iC;
3028 // create sub-element
3030 quantities.push_back(loopLen);
3031 for (; iC < curLast; iC++) {
3032 poly_nodes.push_back(simpleNodes[iC]);
3035 // shift the rest nodes (place from the first loop position)
3036 for (iC = curLast + 1; iC < nbSimple; iC++) {
3037 simpleNodes[iC - loopLen] = simpleNodes[iC];
3039 nbSimple -= loopLen;
3042 } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3043 } // while (foundLoop)
3047 quantities.push_back(iSimple);
3048 for (int i = 0; i < iSimple; i++)
3049 poly_nodes.push_back(simpleNodes[i]);
3055 //=======================================================================
3056 //function : MergeNodes
3057 //purpose : In each group, the cdr of nodes are substituted by the first one
3059 //=======================================================================
3061 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3063 SMESHDS_Mesh* aMesh = GetMeshDS();
3065 TNodeNodeMap nodeNodeMap; // node to replace - new node
3066 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3067 list< int > rmElemIds, rmNodeIds;
3069 // Fill nodeNodeMap and elems
3071 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3072 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3074 list<const SMDS_MeshNode*>& nodes = *grIt;
3075 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3076 const SMDS_MeshNode* nToKeep = *nIt;
3077 for ( ; nIt != nodes.end(); nIt++ )
3079 const SMDS_MeshNode* nToRemove = *nIt;
3080 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3081 if ( nToRemove != nToKeep ) {
3082 rmNodeIds.push_back( nToRemove->GetID() );
3083 AddToSameGroups( nToKeep, nToRemove, aMesh );
3086 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3087 while ( invElemIt->more() )
3088 elems.insert( invElemIt->next() );
3091 // Change element nodes or remove an element
3093 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3094 for ( ; eIt != elems.end(); eIt++ )
3096 const SMDS_MeshElement* elem = *eIt;
3097 int nbNodes = elem->NbNodes();
3098 int aShapeId = FindShape( elem );
3100 set<const SMDS_MeshNode*> nodeSet;
3101 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3102 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3104 // get new seq of nodes
3105 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3106 while ( itN->more() )
3108 const SMDS_MeshNode* n =
3109 static_cast<const SMDS_MeshNode*>( itN->next() );
3111 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3112 if ( nnIt != nodeNodeMap.end() ) { // n sticks
3114 iRepl[ nbRepl++ ] = iCur;
3116 curNodes[ iCur ] = n;
3117 bool isUnique = nodeSet.insert( n ).second;
3119 uniqueNodes[ iUnique++ ] = n;
3123 // Analyse element topology after replacement
3126 int nbUniqueNodes = nodeSet.size();
3127 if ( nbNodes != nbUniqueNodes ) // some nodes stick
3129 // Polygons and Polyhedral volumes
3130 if (elem->IsPoly()) {
3132 if (elem->GetType() == SMDSAbs_Face) {
3134 vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3136 for (; inode < nbNodes; inode++) {
3137 face_nodes[inode] = curNodes[inode];
3140 vector<const SMDS_MeshNode *> polygons_nodes;
3141 vector<int> quantities;
3142 int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3146 for (int iface = 0; iface < nbNew - 1; iface++) {
3147 int nbNodes = quantities[iface];
3148 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3149 for (int ii = 0; ii < nbNodes; ii++, inode++) {
3150 poly_nodes[ii] = polygons_nodes[inode];
3152 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3154 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3156 aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3158 rmElemIds.push_back(elem->GetID());
3161 } else if (elem->GetType() == SMDSAbs_Volume) {
3162 // Polyhedral volume
3163 if (nbUniqueNodes < 4) {
3164 rmElemIds.push_back(elem->GetID());
3166 // each face has to be analized in order to check volume validity
3167 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3168 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3170 int nbFaces = aPolyedre->NbFaces();
3172 vector<const SMDS_MeshNode *> poly_nodes;
3173 vector<int> quantities;
3175 for (int iface = 1; iface <= nbFaces; iface++) {
3176 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3177 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3179 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3180 const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3181 TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3182 if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3183 faceNode = (*nnIt).second;
3185 faceNodes[inode - 1] = faceNode;
3188 SimplifyFace(faceNodes, poly_nodes, quantities);
3191 if (quantities.size() > 3) {
3192 // to be done: remove coincident faces
3195 if (quantities.size() > 3)
3196 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3198 rmElemIds.push_back(elem->GetID());
3201 rmElemIds.push_back(elem->GetID());
3211 switch ( nbNodes ) {
3212 case 2: ///////////////////////////////////// EDGE
3213 isOk = false; break;
3214 case 3: ///////////////////////////////////// TRIANGLE
3215 isOk = false; break;
3217 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3219 else { //////////////////////////////////// QUADRANGLE
3220 if ( nbUniqueNodes < 3 )
3222 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3223 isOk = false; // opposite nodes stick
3226 case 6: ///////////////////////////////////// PENTAHEDRON
3227 if ( nbUniqueNodes == 4 ) {
3228 // ---------------------------------> tetrahedron
3230 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3231 // all top nodes stick: reverse a bottom
3232 uniqueNodes[ 0 ] = curNodes [ 1 ];
3233 uniqueNodes[ 1 ] = curNodes [ 0 ];
3235 else if (nbRepl == 3 &&
3236 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3237 // all bottom nodes stick: set a top before
3238 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3239 uniqueNodes[ 0 ] = curNodes [ 3 ];
3240 uniqueNodes[ 1 ] = curNodes [ 4 ];
3241 uniqueNodes[ 2 ] = curNodes [ 5 ];
3243 else if (nbRepl == 4 &&
3244 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3245 // a lateral face turns into a line: reverse a bottom
3246 uniqueNodes[ 0 ] = curNodes [ 1 ];
3247 uniqueNodes[ 1 ] = curNodes [ 0 ];
3252 else if ( nbUniqueNodes == 5 ) {
3253 // PENTAHEDRON --------------------> 2 tetrahedrons
3254 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3255 // a bottom node sticks with a linked top one
3257 SMDS_MeshElement* newElem =
3258 aMesh->AddVolume(curNodes[ 3 ],
3261 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3263 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3264 // 2. : reverse a bottom
3265 uniqueNodes[ 0 ] = curNodes [ 1 ];
3266 uniqueNodes[ 1 ] = curNodes [ 0 ];
3275 case 8: { //////////////////////////////////// HEXAHEDRON
3277 SMDS_VolumeTool hexa (elem);
3278 hexa.SetExternalNormal();
3279 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3280 //////////////////////// ---> tetrahedron
3281 for ( int iFace = 0; iFace < 6; iFace++ ) {
3282 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3283 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3284 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3285 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3286 // one face turns into a point ...
3287 int iOppFace = hexa.GetOppFaceIndex( iFace );
3288 ind = hexa.GetFaceNodesIndices( iOppFace );
3290 iUnique = 2; // reverse a tetrahedron bottom
3291 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3292 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3294 else if ( iUnique >= 0 )
3295 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3297 if ( nbStick == 1 ) {
3298 // ... and the opposite one - into a triangle.
3300 ind = hexa.GetFaceNodesIndices( iFace );
3301 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3308 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3309 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3310 for ( int iFace = 0; iFace < 6; iFace++ ) {
3311 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3312 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3313 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3314 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3315 // one face turns into a point ...
3316 int iOppFace = hexa.GetOppFaceIndex( iFace );
3317 ind = hexa.GetFaceNodesIndices( iOppFace );
3319 iUnique = 2; // reverse a tetrahedron 1 bottom
3320 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3321 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3323 else if ( iUnique >= 0 )
3324 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3326 if ( nbStick == 0 ) {
3327 // ... and the opposite one is a quadrangle
3329 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3330 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3333 SMDS_MeshElement* newElem =
3334 aMesh->AddVolume(curNodes[ind[ 0 ]],
3337 curNodes[indTop[ 0 ]]);
3339 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3346 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3347 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3348 // find indices of quad and tri faces
3349 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3350 for ( iFace = 0; iFace < 6; iFace++ ) {
3351 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3353 for ( iCur = 0; iCur < 4; iCur++ )
3354 nodeSet.insert( curNodes[ind[ iCur ]] );
3355 nbUniqueNodes = nodeSet.size();
3356 if ( nbUniqueNodes == 3 )
3357 iTriFace[ nbTri++ ] = iFace;
3358 else if ( nbUniqueNodes == 4 )
3359 iQuadFace[ nbQuad++ ] = iFace;
3361 if (nbQuad == 2 && nbTri == 4 &&
3362 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3363 // 2 opposite quadrangles stuck with a diagonal;
3364 // sample groups of merged indices: (0-4)(2-6)
3365 // --------------------------------------------> 2 tetrahedrons
3366 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3367 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3368 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3369 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3370 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3371 // stuck with 0-2 diagonal
3379 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3380 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3381 // stuck with 1-3 diagonal
3393 uniqueNodes[ 0 ] = curNodes [ i0 ];
3394 uniqueNodes[ 1 ] = curNodes [ i1d ];
3395 uniqueNodes[ 2 ] = curNodes [ i3d ];
3396 uniqueNodes[ 3 ] = curNodes [ i0t ];
3399 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3404 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3407 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3408 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3409 // --------------------------------------------> prism
3410 // find 2 opposite triangles
3412 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3413 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3414 // find indices of kept and replaced nodes
3415 // and fill unique nodes of 2 opposite triangles
3416 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3417 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3418 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3419 // fill unique nodes
3422 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3423 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
3424 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3426 // iCur of a linked node of the opposite face (make normals co-directed):
3427 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3428 // check that correspondent corners of triangles are linked
3429 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3432 uniqueNodes[ iUnique ] = n;
3433 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3442 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3448 } // switch ( nbNodes )
3450 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3453 if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3454 // Change nodes of polyedre
3455 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3456 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3458 int nbFaces = aPolyedre->NbFaces();
3460 vector<const SMDS_MeshNode *> poly_nodes;
3461 vector<int> quantities (nbFaces);
3463 for (int iface = 1; iface <= nbFaces; iface++) {
3464 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3465 quantities[iface - 1] = nbFaceNodes;
3467 for (inode = 1; inode <= nbFaceNodes; inode++) {
3468 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3470 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3471 if (nnIt != nodeNodeMap.end()) { // curNode sticks
3472 curNode = (*nnIt).second;
3474 poly_nodes.push_back(curNode);
3477 aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3480 // Change regular element or polygon
3481 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3484 // Remove invalid regular element or invalid polygon
3485 rmElemIds.push_back( elem->GetID() );
3488 } // loop on elements
3490 // Remove equal nodes and bad elements
3492 Remove( rmNodeIds, true );
3493 Remove( rmElemIds, false );
3497 //=======================================================================
3498 //function : MergeEqualElements
3499 //purpose : Remove all but one of elements built on the same nodes.
3500 //=======================================================================
3502 void SMESH_MeshEditor::MergeEqualElements()
3504 SMESHDS_Mesh* aMesh = GetMeshDS();
3506 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
3507 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
3508 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3510 list< int > rmElemIds; // IDs of elems to remove
3512 for ( int iDim = 1; iDim <= 3; iDim++ ) {
3514 set< set <const SMDS_MeshElement*> > setOfNodeSet;
3518 const SMDS_MeshElement* elem = 0;
3520 if ( eIt->more() ) elem = eIt->next();
3521 } else if ( iDim == 2 ) {
3522 if ( fIt->more() ) elem = fIt->next();
3524 if ( vIt->more() ) elem = vIt->next();
3529 set <const SMDS_MeshElement*> nodeSet;
3530 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3531 while ( nodeIt->more() )
3532 nodeSet.insert( nodeIt->next() );
3535 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3537 rmElemIds.push_back( elem->GetID() );
3541 Remove( rmElemIds, false );
3544 //=======================================================================
3545 //function : FindFaceInSet
3546 //purpose : Return a face having linked nodes n1 and n2 and which is
3547 // - not in avoidSet,
3548 // - in elemSet provided that !elemSet.empty()
3549 //=======================================================================
3551 const SMDS_MeshElement*
3552 SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode* n1,
3553 const SMDS_MeshNode* n2,
3554 const set<const SMDS_MeshElement*>& elemSet,
3555 const set<const SMDS_MeshElement*>& avoidSet)
3558 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3559 while ( invElemIt->more() ) { // loop on inverse elements of n1
3560 const SMDS_MeshElement* elem = invElemIt->next();
3561 if (elem->GetType() != SMDSAbs_Face ||
3562 avoidSet.find( elem ) != avoidSet.end() )
3564 if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3566 // get face nodes and find index of n1
3567 int i1, nbN = elem->NbNodes(), iNode = 0;
3568 const SMDS_MeshNode* faceNodes[ nbN ], *n;
3569 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3570 while ( nIt->more() ) {
3571 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3572 if ( faceNodes[ iNode++ ] == n1 )
3575 // find a n2 linked to n1
3576 for ( iNode = 0; iNode < 2; iNode++ ) {
3577 if ( iNode ) // node before n1
3578 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3579 else // node after n1
3580 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3588 //=======================================================================
3589 //function : findAdjacentFace
3591 //=======================================================================
3593 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3594 const SMDS_MeshNode* n2,
3595 const SMDS_MeshElement* elem)
3597 set<const SMDS_MeshElement*> elemSet, avoidSet;
3599 avoidSet.insert ( elem );
3600 return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3603 //=======================================================================
3604 //function : findFreeBorder
3606 //=======================================================================
3608 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3610 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
3611 const SMDS_MeshNode* theSecondNode,
3612 const SMDS_MeshNode* theLastNode,
3613 list< const SMDS_MeshNode* > & theNodes,
3614 list< const SMDS_MeshElement* > & theFaces)
3616 if ( !theFirstNode || !theSecondNode )
3618 // find border face between theFirstNode and theSecondNode
3619 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3623 theFaces.push_back( curElem );
3624 theNodes.push_back( theFirstNode );
3625 theNodes.push_back( theSecondNode );
3627 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3628 set < const SMDS_MeshElement* > foundElems;
3629 bool needTheLast = ( theLastNode != 0 );
3631 while ( nStart != theLastNode )
3633 if ( nStart == theFirstNode )
3634 return !needTheLast;
3636 // find all free border faces sharing form nStart
3638 list< const SMDS_MeshElement* > curElemList;
3639 list< const SMDS_MeshNode* > nStartList;
3640 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3641 while ( invElemIt->more() ) {
3642 const SMDS_MeshElement* e = invElemIt->next();
3643 if ( e == curElem || foundElems.insert( e ).second )
3646 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3647 int iNode = 0, nbNodes = e->NbNodes();
3648 while ( nIt->more() )
3649 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3650 nodes[ iNode ] = nodes[ 0 ];
3652 for ( iNode = 0; iNode < nbNodes; iNode++ )
3653 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3654 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3655 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3657 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3658 curElemList.push_back( e );
3662 // analyse the found
3664 int nbNewBorders = curElemList.size();
3665 if ( nbNewBorders == 0 ) {
3666 // no free border furthermore
3667 return !needTheLast;
3669 else if ( nbNewBorders == 1 ) {
3670 // one more element found
3672 nStart = nStartList.front();
3673 curElem = curElemList.front();
3674 theFaces.push_back( curElem );
3675 theNodes.push_back( nStart );
3678 // several continuations found
3679 list< const SMDS_MeshElement* >::iterator curElemIt;
3680 list< const SMDS_MeshNode* >::iterator nStartIt;
3681 // check if one of them reached the last node
3682 if ( needTheLast ) {
3683 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3684 curElemIt!= curElemList.end();
3685 curElemIt++, nStartIt++ )
3686 if ( *nStartIt == theLastNode ) {
3687 theFaces.push_back( *curElemIt );
3688 theNodes.push_back( *nStartIt );
3692 // find the best free border by the continuations
3693 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
3694 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3695 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3696 curElemIt!= curElemList.end();
3697 curElemIt++, nStartIt++ )
3699 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3700 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3701 // find one more free border
3702 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3706 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3707 // choice: clear a worse one
3708 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3709 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3710 contNodes[ iWorse ].clear();
3711 contFaces[ iWorse ].clear();
3714 if ( contNodes[0].empty() && contNodes[1].empty() )
3717 // append the best free border
3718 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3719 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3720 theNodes.pop_back(); // remove nIgnore
3721 theNodes.pop_back(); // remove nStart
3722 theFaces.pop_back(); // remove curElem
3723 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3724 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3725 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3726 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3729 } // several continuations found
3730 } // while ( nStart != theLastNode )
3735 //=======================================================================
3736 //function : CheckFreeBorderNodes
3737 //purpose : Return true if the tree nodes are on a free border
3738 //=======================================================================
3740 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3741 const SMDS_MeshNode* theNode2,
3742 const SMDS_MeshNode* theNode3)
3744 list< const SMDS_MeshNode* > nodes;
3745 list< const SMDS_MeshElement* > faces;
3746 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3749 //=======================================================================
3750 //function : SewFreeBorder
3752 //=======================================================================
3754 SMESH_MeshEditor::Sew_Error
3755 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3756 const SMDS_MeshNode* theBordSecondNode,
3757 const SMDS_MeshNode* theBordLastNode,
3758 const SMDS_MeshNode* theSideFirstNode,
3759 const SMDS_MeshNode* theSideSecondNode,
3760 const SMDS_MeshNode* theSideThirdNode,
3761 const bool theSideIsFreeBorder,
3762 const bool toCreatePolygons,
3763 const bool toCreatePolyedrs)
3765 MESSAGE("::SewFreeBorder()");
3766 Sew_Error aResult = SEW_OK;
3768 // ====================================
3769 // find side nodes and elements
3770 // ====================================
3772 list< const SMDS_MeshNode* > nSide[ 2 ];
3773 list< const SMDS_MeshElement* > eSide[ 2 ];
3774 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3775 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3779 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3780 nSide[0], eSide[0])) {
3781 MESSAGE(" Free Border 1 not found " );
3782 aResult = SEW_BORDER1_NOT_FOUND;
3784 if (theSideIsFreeBorder)
3788 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3789 nSide[1], eSide[1])) {
3790 MESSAGE(" Free Border 2 not found " );
3791 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3794 if ( aResult != SEW_OK )
3797 if (!theSideIsFreeBorder)
3802 // -------------------------------------------------------------------------
3804 // 1. If nodes to merge are not coincident, move nodes of the free border
3805 // from the coord sys defined by the direction from the first to last
3806 // nodes of the border to the correspondent sys of the side 2
3807 // 2. On the side 2, find the links most co-directed with the correspondent
3808 // links of the free border
3809 // -------------------------------------------------------------------------
3811 // 1. Since sewing may brake if there are volumes to split on the side 2,
3812 // we wont move nodes but just compute new coordinates for them
3813 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3814 TNodeXYZMap nBordXYZ;
3815 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3816 list< const SMDS_MeshNode* >::iterator nBordIt;
3818 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3819 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3820 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3821 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3822 double tol2 = 1.e-8;
3823 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3824 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3826 // Need node movement.
3828 // find X and Z axes to create trsf
3829 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3831 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3833 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3836 gp_Ax3 toBordAx( Pb1, Zb, X );
3837 gp_Ax3 fromSideAx( Ps1, Zs, X );
3838 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
3840 gp_Trsf toBordSys, fromSide2Sys;
3841 toBordSys.SetTransformation( toBordAx );
3842 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
3843 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
3846 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3847 const SMDS_MeshNode* n = *nBordIt;
3848 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
3849 toBordSys.Transforms( xyz );
3850 fromSide2Sys.Transforms( xyz );
3851 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
3856 // just insert nodes XYZ in the nBordXYZ map
3857 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3858 const SMDS_MeshNode* n = *nBordIt;
3859 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
3863 // 2. On the side 2, find the links most co-directed with the correspondent
3864 // links of the free border
3866 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
3867 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
3868 sideNodes.push_back( theSideFirstNode );
3870 bool hasVolumes = false;
3871 LinkID_Gen aLinkID_Gen( GetMeshDS() );
3872 set<long> foundSideLinkIDs, checkedLinkIDs;
3873 SMDS_VolumeTool volume;
3874 //const SMDS_MeshNode* faceNodes[ 4 ];
3876 const SMDS_MeshNode* sideNode;
3877 const SMDS_MeshElement* sideElem;
3878 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
3879 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
3880 nBordIt = bordNodes.begin();
3882 // border node position and border link direction to compare with
3883 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
3884 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
3885 // choose next side node by link direction or by closeness to
3886 // the current border node:
3887 bool searchByDir = ( *nBordIt != theBordLastNode );
3889 // find the next node on the Side 2
3891 double maxDot = -DBL_MAX, minDist = DBL_MAX;
3893 checkedLinkIDs.clear();
3894 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
3896 SMDS_ElemIteratorPtr invElemIt
3897 = prevSideNode->GetInverseElementIterator();
3898 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
3899 const SMDS_MeshElement* elem = invElemIt->next();
3900 // prepare data for a loop on links, of a face or a volume
3901 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
3902 const SMDS_MeshNode* faceNodes[ nbNodes ];
3903 bool isVolume = volume.Set( elem );
3904 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
3905 if ( isVolume ) // --volume
3907 else if ( nbNodes > 2 ) { // --face
3908 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
3909 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3910 while ( nIt->more() ) {
3911 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3912 if ( nodes[ iNode++ ] == prevSideNode )
3913 iPrevNode = iNode - 1;
3915 // there are 2 links to check
3920 // loop on links, to be precise, on the second node of links
3921 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
3922 const SMDS_MeshNode* n = nodes[ iNode ];
3924 if ( !volume.IsLinked( n, prevSideNode ))
3927 if ( iNode ) // a node before prevSideNode
3928 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
3929 else // a node after prevSideNode
3930 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
3932 // check if this link was already used
3933 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
3934 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
3935 if (!isJustChecked &&
3936 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
3937 // test a link geometrically
3938 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
3939 bool linkIsBetter = false;
3941 if ( searchByDir ) { // choose most co-directed link
3942 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
3943 linkIsBetter = ( dot > maxDot );
3945 else { // choose link with the node closest to bordPos
3946 dist = ( nextXYZ - bordPos ).SquareModulus();
3947 linkIsBetter = ( dist < minDist );
3949 if ( linkIsBetter ) {
3958 } // loop on inverse elements of prevSideNode
3961 MESSAGE(" Cant find path by links of the Side 2 ");
3962 return SEW_BAD_SIDE_NODES;
3964 sideNodes.push_back( sideNode );
3965 sideElems.push_back( sideElem );
3966 foundSideLinkIDs.insert ( linkID );
3967 prevSideNode = sideNode;
3969 if ( *nBordIt == theBordLastNode )
3970 searchByDir = false;
3972 // find the next border link to compare with
3973 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
3974 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
3975 while ( *nBordIt != theBordLastNode && !searchByDir ) {
3976 prevBordNode = *nBordIt;
3978 bordPos = nBordXYZ[ *nBordIt ];
3979 bordDir = bordPos - nBordXYZ[ prevBordNode ];
3980 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
3984 while ( sideNode != theSideSecondNode );
3986 if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
3987 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
3988 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
3990 } // end nodes search on the side 2
3992 // ============================
3993 // sew the border to the side 2
3994 // ============================
3996 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
3997 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
3999 TListOfListOfNodes nodeGroupsToMerge;
4000 if ( nbNodes[0] == nbNodes[1] ||
4001 ( theSideIsFreeBorder && !theSideThirdNode)) {
4003 // all nodes are to be merged
4005 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4006 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4007 nIt[0]++, nIt[1]++ )
4009 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4010 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4011 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4016 // insert new nodes into the border and the side to get equal nb of segments
4018 // get normalized parameters of nodes on the borders
4019 double param[ 2 ][ maxNbNodes ];
4021 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4022 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4023 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4024 const SMDS_MeshNode* nPrev = *nIt;
4025 double bordLength = 0;
4026 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4027 const SMDS_MeshNode* nCur = *nIt;
4028 gp_XYZ segment (nCur->X() - nPrev->X(),
4029 nCur->Y() - nPrev->Y(),
4030 nCur->Z() - nPrev->Z());
4031 double segmentLen = segment.Modulus();
4032 bordLength += segmentLen;
4033 param[ iBord ][ iNode ] = bordLength;
4036 // normalize within [0,1]
4037 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4038 param[ iBord ][ iNode ] /= bordLength;
4042 // loop on border segments
4043 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4044 int i[ 2 ] = { 0, 0 };
4045 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4046 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4048 TElemOfNodeListMap insertMap;
4049 TElemOfNodeListMap::iterator insertMapIt;
4051 // key: elem to insert nodes into
4052 // value: 2 nodes to insert between + nodes to be inserted
4054 bool next[ 2 ] = { false, false };
4056 // find min adjacent segment length after sewing
4057 double nextParam = 10., prevParam = 0;
4058 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4059 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4060 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4061 if ( i[ iBord ] > 0 )
4062 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4064 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4065 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4066 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4068 // choose to insert or to merge nodes
4069 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4070 if ( Abs( du ) <= minSegLen * 0.2 ) {
4073 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4074 const SMDS_MeshNode* n0 = *nIt[0];
4075 const SMDS_MeshNode* n1 = *nIt[1];
4076 nodeGroupsToMerge.back().push_back( n1 );
4077 nodeGroupsToMerge.back().push_back( n0 );
4078 // position of node of the border changes due to merge
4079 param[ 0 ][ i[0] ] += du;
4080 // move n1 for the sake of elem shape evaluation during insertion.
4081 // n1 will be removed by MergeNodes() anyway
4082 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4083 next[0] = next[1] = true;
4088 int intoBord = ( du < 0 ) ? 0 : 1;
4089 const SMDS_MeshElement* elem = *eIt[ intoBord ];
4090 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
4091 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
4092 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
4093 if ( intoBord == 1 ) {
4094 // move node of the border to be on a link of elem of the side
4095 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4096 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4097 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4098 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4099 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4101 insertMapIt = insertMap.find( elem );
4102 bool notFound = ( insertMapIt == insertMap.end() );
4103 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4105 // insert into another link of the same element:
4106 // 1. perform insertion into the other link of the elem
4107 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4108 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4109 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4110 InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4111 // 2. perform insertion into the link of adjacent faces
4113 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4115 InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4119 if (toCreatePolyedrs) {
4120 // perform insertion into the links of adjacent volumes
4121 UpdateVolumes(n12, n22, nodeList);
4123 // 3. find an element appeared on n1 and n2 after the insertion
4124 insertMap.erase( elem );
4125 elem = findAdjacentFace( n1, n2, 0 );
4127 if ( notFound || otherLink ) {
4128 // add element and nodes of the side into the insertMap
4129 insertMapIt = insertMap.insert
4130 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4131 (*insertMapIt).second.push_back( n1 );
4132 (*insertMapIt).second.push_back( n2 );
4134 // add node to be inserted into elem
4135 (*insertMapIt).second.push_back( nIns );
4136 next[ 1 - intoBord ] = true;
4139 // go to the next segment
4140 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4141 if ( next[ iBord ] ) {
4142 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4144 nPrev[ iBord ] = *nIt[ iBord ];
4145 nIt[ iBord ]++; i[ iBord ]++;
4149 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4151 // perform insertion of nodes into elements
4153 for (insertMapIt = insertMap.begin();
4154 insertMapIt != insertMap.end();
4157 const SMDS_MeshElement* elem = (*insertMapIt).first;
4158 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4159 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4160 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4162 InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4164 if ( !theSideIsFreeBorder ) {
4165 // look for and insert nodes into the faces adjacent to elem
4167 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4169 InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4174 if (toCreatePolyedrs) {
4175 // perform insertion into the links of adjacent volumes
4176 UpdateVolumes(n1, n2, nodeList);
4180 } // end: insert new nodes
4182 MergeNodes ( nodeGroupsToMerge );
4187 //=======================================================================
4188 //function : InsertNodesIntoLink
4189 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
4190 // and theBetweenNode2 and split theElement
4191 //=======================================================================
4193 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
4194 const SMDS_MeshNode* theBetweenNode1,
4195 const SMDS_MeshNode* theBetweenNode2,
4196 list<const SMDS_MeshNode*>& theNodesToInsert,
4197 const bool toCreatePoly)
4199 if ( theFace->GetType() != SMDSAbs_Face ) return;
4201 // find indices of 2 link nodes and of the rest nodes
4202 int iNode = 0, il1, il2, i3, i4;
4203 il1 = il2 = i3 = i4 = -1;
4204 const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4205 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4206 while ( nodeIt->more() ) {
4207 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4208 if ( n == theBetweenNode1 )
4210 else if ( n == theBetweenNode2 )
4216 nodes[ iNode++ ] = n;
4218 if ( il1 < 0 || il2 < 0 || i3 < 0 )
4221 // arrange link nodes to go one after another regarding the face orientation
4222 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4223 list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4228 aNodesToInsert.reverse();
4230 // check that not link nodes of a quadrangles are in good order
4231 int nbFaceNodes = theFace->NbNodes();
4232 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4238 if (toCreatePoly || theFace->IsPoly()) {
4241 vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4243 // add nodes of face up to first node of link
4245 nodeIt = theFace->nodesIterator();
4246 while ( nodeIt->more() && !isFLN ) {
4247 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4248 poly_nodes[iNode++] = n;
4249 if (n == nodes[il1]) {
4254 // add nodes to insert
4255 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4256 for (; nIt != aNodesToInsert.end(); nIt++) {
4257 poly_nodes[iNode++] = *nIt;
4260 // add nodes of face starting from last node of link
4261 while ( nodeIt->more() ) {
4262 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4263 poly_nodes[iNode++] = n;
4266 // edit or replace the face
4267 SMESHDS_Mesh *aMesh = GetMeshDS();
4269 if (theFace->IsPoly()) {
4270 aMesh->ChangePolygonNodes(theFace, poly_nodes);
4273 int aShapeId = FindShape( theFace );
4275 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4276 if ( aShapeId && newElem )
4277 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4279 aMesh->RemoveElement(theFace);
4284 // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4285 int nbLinkNodes = 2 + aNodesToInsert.size();
4286 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4287 linkNodes[ 0 ] = nodes[ il1 ];
4288 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4289 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4290 for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4291 linkNodes[ iNode++ ] = *nIt;
4293 // decide how to split a quadrangle: compare possible variants
4294 // and choose which of splits to be a quadrangle
4295 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4296 if ( nbFaceNodes == 3 )
4298 iBestQuad = nbSplits;
4301 else if ( nbFaceNodes == 4 )
4303 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4304 double aBestRate = DBL_MAX;
4305 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4307 double aBadRate = 0;
4308 // evaluate elements quality
4309 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4310 if ( iSplit == iQuad ) {
4311 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4315 aBadRate += getBadRate( &quad, aCrit );
4318 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4320 nodes[ iSplit < iQuad ? i4 : i3 ]);
4321 aBadRate += getBadRate( &tria, aCrit );
4325 if ( aBadRate < aBestRate ) {
4327 aBestRate = aBadRate;
4332 // create new elements
4333 SMESHDS_Mesh *aMesh = GetMeshDS();
4334 int aShapeId = FindShape( theFace );
4337 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4338 SMDS_MeshElement* newElem = 0;
4339 if ( iSplit == iBestQuad )
4340 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4345 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4347 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4348 if ( aShapeId && newElem )
4349 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4352 // change nodes of theFace
4353 const SMDS_MeshNode* newNodes[ 4 ];
4354 newNodes[ 0 ] = linkNodes[ i1 ];
4355 newNodes[ 1 ] = linkNodes[ i2 ];
4356 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4357 newNodes[ 3 ] = nodes[ i4 ];
4358 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4361 //=======================================================================
4362 //function : UpdateVolumes
4364 //=======================================================================
4365 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode* theBetweenNode1,
4366 const SMDS_MeshNode* theBetweenNode2,
4367 list<const SMDS_MeshNode*>& theNodesToInsert)
4369 SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4370 while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4371 const SMDS_MeshElement* elem = invElemIt->next();
4372 if (elem->GetType() != SMDSAbs_Volume)
4375 // check, if current volume has link theBetweenNode1 - theBetweenNode2
4376 SMDS_VolumeTool aVolume (elem);
4377 if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4380 // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4381 int iface, nbFaces = aVolume.NbFaces();
4382 vector<const SMDS_MeshNode *> poly_nodes;
4383 vector<int> quantities (nbFaces);
4385 for (iface = 0; iface < nbFaces; iface++) {
4386 int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4387 // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4388 const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4390 for (int inode = 0; inode < nbFaceNodes; inode++) {
4391 poly_nodes.push_back(faceNodes[inode]);
4393 if (nbInserted == 0) {
4394 if (faceNodes[inode] == theBetweenNode1) {
4395 if (faceNodes[inode + 1] == theBetweenNode2) {
4396 nbInserted = theNodesToInsert.size();
4398 // add nodes to insert
4399 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4400 for (; nIt != theNodesToInsert.end(); nIt++) {
4401 poly_nodes.push_back(*nIt);
4404 } else if (faceNodes[inode] == theBetweenNode2) {
4405 if (faceNodes[inode + 1] == theBetweenNode1) {
4406 nbInserted = theNodesToInsert.size();
4408 // add nodes to insert in reversed order
4409 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4411 for (; nIt != theNodesToInsert.begin(); nIt--) {
4412 poly_nodes.push_back(*nIt);
4414 poly_nodes.push_back(*nIt);
4420 quantities[iface] = nbFaceNodes + nbInserted;
4423 // Replace or update the volume
4424 SMESHDS_Mesh *aMesh = GetMeshDS();
4426 if (elem->IsPoly()) {
4427 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4430 int aShapeId = FindShape( elem );
4432 SMDS_MeshElement* newElem =
4433 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4434 if (aShapeId && newElem)
4435 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4437 aMesh->RemoveElement(elem);
4442 //=======================================================================
4443 //function : SewSideElements
4445 //=======================================================================
4447 SMESH_MeshEditor::Sew_Error
4448 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4449 set<const SMDS_MeshElement*>& theSide2,
4450 const SMDS_MeshNode* theFirstNode1,
4451 const SMDS_MeshNode* theFirstNode2,
4452 const SMDS_MeshNode* theSecondNode1,
4453 const SMDS_MeshNode* theSecondNode2)
4455 MESSAGE ("::::SewSideElements()");
4456 if ( theSide1.size() != theSide2.size() )
4457 return SEW_DIFF_NB_OF_ELEMENTS;
4459 Sew_Error aResult = SEW_OK;
4461 // 1. Build set of faces representing each side
4462 // 2. Find which nodes of the side 1 to merge with ones on the side 2
4463 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4465 // =======================================================================
4466 // 1. Build set of faces representing each side:
4467 // =======================================================================
4468 // a. build set of nodes belonging to faces
4469 // b. complete set of faces: find missing fices whose nodes are in set of nodes
4470 // c. create temporary faces representing side of volumes if correspondent
4471 // face does not exist
4473 SMESHDS_Mesh* aMesh = GetMeshDS();
4474 SMDS_Mesh aTmpFacesMesh;
4475 set<const SMDS_MeshElement*> faceSet1, faceSet2;
4476 set<const SMDS_MeshElement*> volSet1, volSet2;
4477 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
4478 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4479 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
4480 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4481 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4482 int iSide, iFace, iNode;
4484 for ( iSide = 0; iSide < 2; iSide++ ) {
4485 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
4486 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4487 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4488 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
4489 set<const SMDS_MeshElement*>::iterator vIt, eIt;
4490 set<const SMDS_MeshNode*>::iterator nIt;
4492 // -----------------------------------------------------------
4493 // 1a. Collect nodes of existing faces
4494 // and build set of face nodes in order to detect missing
4495 // faces corresponing to sides of volumes
4496 // -----------------------------------------------------------
4498 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4500 // loop on the given element of a side
4501 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4502 const SMDS_MeshElement* elem = *eIt;
4503 if ( elem->GetType() == SMDSAbs_Face ) {
4504 faceSet->insert( elem );
4505 set <const SMDS_MeshNode*> faceNodeSet;
4506 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4507 while ( nodeIt->more() ) {
4508 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4509 nodeSet->insert( n );
4510 faceNodeSet.insert( n );
4512 setOfFaceNodeSet.insert( faceNodeSet );
4514 else if ( elem->GetType() == SMDSAbs_Volume )
4515 volSet->insert( elem );
4517 // ------------------------------------------------------------------------------
4518 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4519 // ------------------------------------------------------------------------------
4521 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4522 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4523 while ( fIt->more() ) { // loop on faces sharing a node
4524 const SMDS_MeshElement* f = fIt->next();
4525 if ( faceSet->find( f ) == faceSet->end() ) {
4526 // check if all nodes are in nodeSet and
4527 // complete setOfFaceNodeSet if they are
4528 set <const SMDS_MeshNode*> faceNodeSet;
4529 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4530 bool allInSet = true;
4531 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4532 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4533 if ( nodeSet->find( n ) == nodeSet->end() )
4536 faceNodeSet.insert( n );
4539 faceSet->insert( f );
4540 setOfFaceNodeSet.insert( faceNodeSet );
4546 // -------------------------------------------------------------------------
4547 // 1c. Create temporary faces representing sides of volumes if correspondent
4548 // face does not exist
4549 // -------------------------------------------------------------------------
4551 if ( !volSet->empty() )
4553 //int nodeSetSize = nodeSet->size();
4555 // loop on given volumes
4556 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4557 SMDS_VolumeTool vol (*vIt);
4558 // loop on volume faces: find free faces
4559 // --------------------------------------
4560 list<const SMDS_MeshElement* > freeFaceList;
4561 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4562 if ( !vol.IsFreeFace( iFace ))
4564 // check if there is already a face with same nodes in a face set
4565 const SMDS_MeshElement* aFreeFace = 0;
4566 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4567 int nbNodes = vol.NbFaceNodes( iFace );
4568 set <const SMDS_MeshNode*> faceNodeSet;
4569 vol.GetFaceNodes( iFace, faceNodeSet );
4570 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4572 // no such a face is given but it still can exist, check it
4573 if ( nbNodes == 3 ) {
4574 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4575 } else if ( nbNodes == 4 ) {
4576 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4578 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4579 for (int inode = 0; inode < nbNodes; inode++) {
4580 poly_nodes[inode] = fNodes[inode];
4582 aFreeFace = aMesh->FindFace(poly_nodes);
4586 // create a temporary face
4587 if ( nbNodes == 3 ) {
4588 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4589 } else if ( nbNodes == 4 ) {
4590 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4592 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4593 for (int inode = 0; inode < nbNodes; inode++) {
4594 poly_nodes[inode] = fNodes[inode];
4596 aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4600 freeFaceList.push_back( aFreeFace );
4602 } // loop on faces of a volume
4604 // choose one of several free faces
4605 // --------------------------------------
4606 if ( freeFaceList.size() > 1 ) {
4607 // choose a face having max nb of nodes shared by other elems of a side
4608 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4609 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4610 while ( fIt != freeFaceList.end() ) { // loop on free faces
4611 int nbSharedNodes = 0;
4612 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4613 while ( nodeIt->more() ) { // loop on free face nodes
4614 const SMDS_MeshNode* n =
4615 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4616 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4617 while ( invElemIt->more() ) {
4618 const SMDS_MeshElement* e = invElemIt->next();
4619 if ( faceSet->find( e ) != faceSet->end() )
4621 if ( elemSet->find( e ) != elemSet->end() )
4625 if ( nbSharedNodes >= maxNbNodes ) {
4626 maxNbNodes = nbSharedNodes;
4630 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4632 if ( freeFaceList.size() > 1 )
4634 // could not choose one face, use another way
4635 // choose a face most close to the bary center of the opposite side
4636 gp_XYZ aBC( 0., 0., 0. );
4637 set <const SMDS_MeshNode*> addedNodes;
4638 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4639 eIt = elemSet2->begin();
4640 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4641 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4642 while ( nodeIt->more() ) { // loop on free face nodes
4643 const SMDS_MeshNode* n =
4644 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4645 if ( addedNodes.insert( n ).second )
4646 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4649 aBC /= addedNodes.size();
4650 double minDist = DBL_MAX;
4651 fIt = freeFaceList.begin();
4652 while ( fIt != freeFaceList.end() ) { // loop on free faces
4654 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4655 while ( nodeIt->more() ) { // loop on free face nodes
4656 const SMDS_MeshNode* n =
4657 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4658 gp_XYZ p( n->X(),n->Y(),n->Z() );
4659 dist += ( aBC - p ).SquareModulus();
4661 if ( dist < minDist ) {
4663 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4666 fIt = freeFaceList.erase( fIt++ );
4669 } // choose one of several free faces of a volume
4671 if ( freeFaceList.size() == 1 ) {
4672 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4673 faceSet->insert( aFreeFace );
4674 // complete a node set with nodes of a found free face
4675 // for ( iNode = 0; iNode < ; iNode++ )
4676 // nodeSet->insert( fNodes[ iNode ] );
4679 } // loop on volumes of a side
4681 // // complete a set of faces if new nodes in a nodeSet appeared
4682 // // ----------------------------------------------------------
4683 // if ( nodeSetSize != nodeSet->size() ) {
4684 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4685 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4686 // while ( fIt->more() ) { // loop on faces sharing a node
4687 // const SMDS_MeshElement* f = fIt->next();
4688 // if ( faceSet->find( f ) == faceSet->end() ) {
4689 // // check if all nodes are in nodeSet and
4690 // // complete setOfFaceNodeSet if they are
4691 // set <const SMDS_MeshNode*> faceNodeSet;
4692 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4693 // bool allInSet = true;
4694 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4695 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4696 // if ( nodeSet->find( n ) == nodeSet->end() )
4697 // allInSet = false;
4699 // faceNodeSet.insert( n );
4701 // if ( allInSet ) {
4702 // faceSet->insert( f );
4703 // setOfFaceNodeSet.insert( faceNodeSet );
4709 } // Create temporary faces, if there are volumes given
4712 if ( faceSet1.size() != faceSet2.size() ) {
4713 // delete temporary faces: they are in reverseElements of actual nodes
4714 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4715 while ( tmpFaceIt->more() )
4716 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4717 MESSAGE("Diff nb of faces");
4718 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4721 // ============================================================
4722 // 2. Find nodes to merge:
4723 // bind a node to remove to a node to put instead
4724 // ============================================================
4726 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4727 if ( theFirstNode1 != theFirstNode2 )
4728 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4729 if ( theSecondNode1 != theSecondNode2 )
4730 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4732 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4733 set< long > linkIdSet; // links to process
4734 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4736 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4737 list< TPairOfNodes > linkList[2];
4738 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4739 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4740 // loop on links in linkList; find faces by links and append links
4741 // of the found faces to linkList
4742 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4743 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4745 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4746 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4747 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4750 // by links, find faces in the face sets,
4751 // and find indices of link nodes in the found faces;
4752 // in a face set, there is only one or no face sharing a link
4753 // ---------------------------------------------------------------
4755 const SMDS_MeshElement* face[] = { 0, 0 };
4756 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4757 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4758 int iLinkNode[2][2];
4759 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4760 const SMDS_MeshNode* n1 = link[iSide].first;
4761 const SMDS_MeshNode* n2 = link[iSide].second;
4762 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4763 set< const SMDS_MeshElement* > fMap;
4764 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4765 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4766 SMDS_ElemIteratorPtr fIt = n->facesIterator();
4767 while ( fIt->more() ) { // loop on faces sharing a node
4768 const SMDS_MeshElement* f = fIt->next();
4769 if (faceSet->find( f ) != faceSet->end() && // f is in face set
4770 ! fMap.insert( f ).second ) // f encounters twice
4772 if ( face[ iSide ] ) {
4773 MESSAGE( "2 faces per link " );
4774 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4778 faceSet->erase( f );
4779 // get face nodes and find ones of a link
4781 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4782 while ( nIt->more() ) {
4783 const SMDS_MeshNode* n =
4784 static_cast<const SMDS_MeshNode*>( nIt->next() );
4786 iLinkNode[ iSide ][ 0 ] = iNode;
4788 iLinkNode[ iSide ][ 1 ] = iNode;
4789 else if ( notLinkNodes[ iSide ][ 0 ] )
4790 notLinkNodes[ iSide ][ 1 ] = n;
4792 notLinkNodes[ iSide ][ 0 ] = n;
4793 faceNodes[ iSide ][ iNode++ ] = n;
4795 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4800 // check similarity of elements of the sides
4801 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4802 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4803 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4804 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4806 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4807 break; // do not return because it s necessary to remove tmp faces
4810 // set nodes to merge
4811 // -------------------
4813 if ( face[0] && face[1] )
4815 int nbNodes = face[0]->NbNodes();
4816 if ( nbNodes != face[1]->NbNodes() ) {
4817 MESSAGE("Diff nb of face nodes");
4818 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4819 break; // do not return because it s necessary to remove tmp faces
4821 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4823 nReplaceMap.insert( TNodeNodeMap::value_type
4824 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4826 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4827 // analyse link orientation in faces
4828 int i1 = iLinkNode[ iSide ][ 0 ];
4829 int i2 = iLinkNode[ iSide ][ 1 ];
4830 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4831 // if notLinkNodes are the first and the last ones, then
4832 // their order does not correspond to the link orientation
4833 if (( i1 == 1 && i2 == 2 ) ||
4834 ( i1 == 2 && i2 == 1 ))
4835 reverse[ iSide ] = !reverse[ iSide ];
4837 if ( reverse[0] == reverse[1] ) {
4838 nReplaceMap.insert( TNodeNodeMap::value_type
4839 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4840 nReplaceMap.insert( TNodeNodeMap::value_type
4841 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
4844 nReplaceMap.insert( TNodeNodeMap::value_type
4845 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
4846 nReplaceMap.insert( TNodeNodeMap::value_type
4847 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
4851 // add other links of the faces to linkList
4852 // -----------------------------------------
4854 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
4855 for ( iNode = 0; iNode < nbNodes; iNode++ )
4857 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
4858 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
4859 if ( !iter_isnew.second ) { // already in a set: no need to process
4860 linkIdSet.erase( iter_isnew.first );
4862 else // new in set == encountered for the first time: add
4864 const SMDS_MeshNode* n1 = nodes[ iNode ];
4865 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
4866 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
4867 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
4871 } // loop on link lists
4873 if ( aResult == SEW_OK &&
4874 ( linkIt[0] != linkList[0].end() ||
4875 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
4876 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
4877 " " << (faceSetPtr[1]->empty()));
4878 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4881 // ====================================================================
4882 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4883 // ====================================================================
4885 // delete temporary faces: they are in reverseElements of actual nodes
4886 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4887 while ( tmpFaceIt->more() )
4888 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4890 if ( aResult != SEW_OK)
4893 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
4894 // loop on nodes replacement map
4895 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
4896 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
4897 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
4899 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
4900 nodeIDsToRemove.push_back( nToRemove->GetID() );
4901 // loop on elements sharing nToRemove
4902 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
4903 while ( invElemIt->more() ) {
4904 const SMDS_MeshElement* e = invElemIt->next();
4905 // get a new suite of nodes: make replacement
4906 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
4907 const SMDS_MeshNode* nodes[ 8 ];
4908 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4909 while ( nIt->more() ) {
4910 const SMDS_MeshNode* n =
4911 static_cast<const SMDS_MeshNode*>( nIt->next() );
4912 nnIt = nReplaceMap.find( n );
4913 if ( nnIt != nReplaceMap.end() ) {
4919 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
4920 // elemIDsToRemove.push_back( e->GetID() );
4923 aMesh->ChangeElementNodes( e, nodes, nbNodes );
4927 Remove( nodeIDsToRemove, true );