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 "SMESHDS_Group.hxx"
34 #include "SMESHDS_Mesh.hxx"
35 #include "SMESH_subMesh.hxx"
36 #include "SMESH_ControlsDef.hxx"
38 #include "utilities.h"
40 #include <TopTools_ListIteratorOfListOfShape.hxx>
41 #include <TopTools_ListOfShape.hxx>
44 #include <gp_Trsf.hxx>
53 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
54 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
55 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
56 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
57 typedef TNodeOfNodeListMap::iterator TNodeOfNodeListMapItr;
58 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
60 //=======================================================================
61 //function : SMESH_MeshEditor
63 //=======================================================================
65 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
70 //=======================================================================
72 //purpose : Remove a node or an element.
73 // Modify a compute state of sub-meshes which become empty
74 //=======================================================================
76 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
80 SMESHDS_Mesh* aMesh = GetMeshDS();
81 set< SMESH_subMesh *> smmap;
83 list<int>::const_iterator it = theIDs.begin();
84 for ( ; it != theIDs.end(); it++ )
86 const SMDS_MeshElement * elem;
88 elem = aMesh->FindNode( *it );
90 elem = aMesh->FindElement( *it );
94 // Find sub-meshes to notify about modification
95 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
96 while ( nodeIt->more() )
98 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
99 const SMDS_PositionPtr& aPosition = node->GetPosition();
100 if ( aPosition.get() ) {
101 int aShapeID = aPosition->GetShapeId();
103 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
104 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
113 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
115 aMesh->RemoveElement( elem );
118 // Notify sub-meshes about modification
119 if ( !smmap.empty() ) {
120 set< SMESH_subMesh *>::iterator smIt;
121 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
122 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
127 //=======================================================================
128 //function : FindShape
129 //purpose : Return an index of the shape theElem is on
130 // or zero if a shape not found
131 //=======================================================================
133 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
135 SMESHDS_Mesh * aMesh = GetMeshDS();
136 if ( aMesh->ShapeToMesh().IsNull() )
139 if ( theElem->GetType() == SMDSAbs_Node )
141 const SMDS_PositionPtr& aPosition =
142 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
143 if ( aPosition.get() )
144 return aPosition->GetShapeId();
149 TopoDS_Shape aShape; // the shape a node is on
150 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
151 while ( nodeIt->more() )
153 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
154 const SMDS_PositionPtr& aPosition = node->GetPosition();
155 if ( aPosition.get() ) {
156 int aShapeID = aPosition->GetShapeId();
157 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
160 if ( sm->Contains( theElem ))
162 if ( aShape.IsNull() )
163 aShape = aMesh->IndexToShape( aShapeID );
167 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
172 // None of nodes is on a proper shape,
173 // find the shape among ancestors of aShape on which a node is
174 if ( aShape.IsNull() ) {
175 //MESSAGE ("::FindShape() - NONE node is on shape")
178 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
179 for ( ; ancIt.More(); ancIt.Next() )
181 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
182 if ( sm && sm->Contains( theElem ))
183 return aMesh->ShapeToIndex( ancIt.Value() );
186 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
190 //=======================================================================
191 //function : InverseDiag
192 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
193 // but having other common link.
194 // Return False if args are improper
195 //=======================================================================
197 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
198 const SMDS_MeshElement * theTria2 )
200 if (!theTria1 || !theTria2)
202 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
203 if (!F1) return false;
204 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
205 if (!F2) return false;
207 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
208 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
212 // put nodes in array and find out indices of the same ones
213 const SMDS_MeshNode* aNodes [6];
214 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
216 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
219 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
221 if ( i > 2 ) // theTria2
222 // find same node of theTria1
223 for ( int j = 0; j < 3; j++ )
224 if ( aNodes[ i ] == aNodes[ j ]) {
233 return false; // theTria1 is not a triangle
234 it = theTria2->nodesIterator();
236 if ( i == 6 && it->more() )
237 return false; // theTria2 is not a triangle
240 // find indices of 1,2 and of A,B in theTria1
241 int iA = 0, iB = 0, i1 = 0, i2 = 0;
242 for ( i = 0; i < 6; i++ )
244 if ( sameInd [ i ] == 0 )
251 // nodes 1 and 2 should not be the same
252 if ( aNodes[ i1 ] == aNodes[ i2 ] )
257 aNodes[ iA ] = aNodes[ i2 ];
259 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
261 //MESSAGE( theTria1 << theTria2 );
263 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
264 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
266 //MESSAGE( theTria1 << theTria2 );
271 //=======================================================================
272 //function : findTriangles
273 //purpose : find triangles sharing theNode1-theNode2 link
274 //=======================================================================
276 static bool findTriangles(const SMDS_MeshNode * theNode1,
277 const SMDS_MeshNode * theNode2,
278 const SMDS_MeshElement*& theTria1,
279 const SMDS_MeshElement*& theTria2)
281 if ( !theNode1 || !theNode2 ) return false;
283 theTria1 = theTria2 = 0;
285 set< const SMDS_MeshElement* > emap;
286 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
288 const SMDS_MeshElement* elem = it->next();
289 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
292 it = theNode2->GetInverseElementIterator();
294 const SMDS_MeshElement* elem = it->next();
295 if ( elem->GetType() == SMDSAbs_Face &&
296 emap.find( elem ) != emap.end() )
304 return ( theTria1 && theTria2 );
307 //=======================================================================
308 //function : InverseDiag
309 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
310 // with ones built on the same 4 nodes but having other common link.
311 // Return false if proper faces not found
312 //=======================================================================
314 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
315 const SMDS_MeshNode * theNode2)
317 MESSAGE( "::InverseDiag()" );
319 const SMDS_MeshElement *tr1, *tr2;
320 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
323 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
324 if (!F1) return false;
325 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
326 if (!F2) return false;
328 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
329 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
333 // put nodes in array
334 // and find indices of 1,2 and of A in tr1 and of B in tr2
335 int i, iA1 = 0, i1 = 0;
336 const SMDS_MeshNode* aNodes1 [3];
337 SMDS_ElemIteratorPtr it;
338 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
339 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
340 if ( aNodes1[ i ] == theNode1 )
341 iA1 = i; // node A in tr1
342 else if ( aNodes1[ i ] != theNode2 )
346 const SMDS_MeshNode* aNodes2 [3];
347 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
348 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
349 if ( aNodes2[ i ] == theNode2 )
350 iB2 = i; // node B in tr2
351 else if ( aNodes2[ i ] != theNode1 )
355 // nodes 1 and 2 should not be the same
356 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
360 aNodes1[ iA1 ] = aNodes2[ i2 ];
362 aNodes2[ iB2 ] = aNodes1[ i1 ];
364 //MESSAGE( tr1 << tr2 );
366 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
367 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
369 //MESSAGE( tr1 << tr2 );
375 //=======================================================================
376 //function : getQuadrangleNodes
377 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
378 // fusion of triangles tr1 and tr2 having shared link on
379 // theNode1 and theNode2
380 //=======================================================================
382 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
383 const SMDS_MeshNode * theNode1,
384 const SMDS_MeshNode * theNode2,
385 const SMDS_MeshElement * tr1,
386 const SMDS_MeshElement * tr2 )
388 // find the 4-th node to insert into tr1
389 const SMDS_MeshNode* n4 = 0;
390 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
391 while ( !n4 && it->more() )
393 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
394 bool isDiag = ( n == theNode1 || n == theNode2 );
398 // Make an array of nodes to be in a quadrangle
399 int iNode = 0, iFirstDiag = -1;
400 it = tr1->nodesIterator();
403 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
404 bool isDiag = ( n == theNode1 || n == theNode2 );
407 if ( iFirstDiag < 0 )
409 else if ( iNode - iFirstDiag == 1 )
410 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
414 return false; // tr1 and tr2 should not have all the same nodes
416 theQuadNodes[ iNode++ ] = n;
418 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
419 theQuadNodes[ iNode ] = n4;
424 //=======================================================================
425 //function : DeleteDiag
426 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
427 // with a quadrangle built on the same 4 nodes.
428 // Return false if proper faces not found
429 //=======================================================================
431 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
432 const SMDS_MeshNode * theNode2)
434 MESSAGE( "::DeleteDiag()" );
436 const SMDS_MeshElement *tr1, *tr2;
437 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
440 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
441 if (!F1) return false;
442 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
443 if (!F2) return false;
445 const SMDS_MeshNode* aNodes [ 4 ];
446 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
449 //MESSAGE( endl << tr1 << tr2 );
451 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
452 GetMeshDS()->RemoveElement( tr2 );
454 //MESSAGE( endl << tr1 );
459 //=======================================================================
460 //function : Reorient
461 //purpose : Reverse the normal of theFace
462 // Return false if theFace is null
463 //=======================================================================
465 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theFace)
467 if (!theFace) return false;
468 const SMDS_FaceOfNodes* F = dynamic_cast<const SMDS_FaceOfNodes*>( theFace );
469 if (!F) return false;
471 const SMDS_MeshNode* aNodes [4], *tmpNode;
473 SMDS_ElemIteratorPtr it = theFace->nodesIterator();
475 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( it->next() );
477 // exchange nodes with indeces 0 and 2
478 tmpNode = aNodes[ 0 ];
479 aNodes[ 0 ] = aNodes[ 2 ];
480 aNodes[ 2 ] = tmpNode;
482 //MESSAGE( theFace );
484 GetMeshDS()->ChangeElementNodes( theFace, aNodes, theFace->NbNodes() );
486 //MESSAGE( theFace );
491 //=======================================================================
492 //function : getBadRate
494 //=======================================================================
496 static double getBadRate (const SMDS_MeshElement* theElem,
497 SMESH::Controls::NumericalFunctorPtr& theCrit)
499 SMESH::Controls::TSequenceOfXYZ P;
500 if ( !theElem || !theCrit->GetPoints( theElem, P ))
502 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
505 //=======================================================================
506 //function : QuadToTri
507 //purpose : Cut quadrangles into triangles.
508 // theCrit is used to select a diagonal to cut
509 //=======================================================================
511 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
512 SMESH::Controls::NumericalFunctorPtr theCrit)
514 MESSAGE( "::QuadToTri()" );
516 if ( !theCrit.get() )
519 SMESHDS_Mesh * aMesh = GetMeshDS();
521 set< const SMDS_MeshElement * >::iterator itElem;
522 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
524 const SMDS_MeshElement* elem = (*itElem);
525 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
528 // retrieve element nodes
529 const SMDS_MeshNode* aNodes [4];
530 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
532 while ( itN->more() )
533 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
535 // compare two sets of possible triangles
536 double aBadRate1, aBadRate2; // to what extent a set is bad
537 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
538 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
539 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
541 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
542 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
543 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
545 int aShapeId = FindShape( elem );
546 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
547 // << " ShapeID = " << aShapeId << endl << elem );
549 if ( aBadRate1 <= aBadRate2 ) {
550 // tr1 + tr2 is better
551 aMesh->ChangeElementNodes( elem, aNodes, 3 );
552 //MESSAGE( endl << elem );
554 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
557 // tr3 + tr4 is better
558 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
559 //MESSAGE( endl << elem );
561 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
563 //MESSAGE( endl << elem );
565 // put a new triangle on the same shape
567 aMesh->SetMeshElementOnShape( elem, aShapeId );
573 //=======================================================================
574 //function : AddToSameGroups
575 //purpose : add elemToAdd to the groups the elemInGroups belongs to
576 //=======================================================================
578 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
579 const SMDS_MeshElement* elemInGroups,
580 SMESHDS_Mesh * aMesh)
582 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
583 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
584 for ( ; grIt != groups.end(); grIt++ ) {
585 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
586 if ( group && group->SMDSGroup().Contains( elemInGroups ))
587 group->SMDSGroup().Add( elemToAdd );
591 //=======================================================================
592 //function : QuadToTri
593 //purpose : Cut quadrangles into triangles.
594 // theCrit is used to select a diagonal to cut
595 //=======================================================================
597 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
598 const bool the13Diag)
600 MESSAGE( "::QuadToTri()" );
602 SMESHDS_Mesh * aMesh = GetMeshDS();
604 set< const SMDS_MeshElement * >::iterator itElem;
605 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
607 const SMDS_MeshElement* elem = (*itElem);
608 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
611 // retrieve element nodes
612 const SMDS_MeshNode* aNodes [4];
613 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
615 while ( itN->more() )
616 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
618 int aShapeId = FindShape( elem );
619 const SMDS_MeshElement* newElem = 0;
622 aMesh->ChangeElementNodes( elem, aNodes, 3 );
623 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
627 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
628 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
631 // put a new triangle on the same shape and add to the same groups
634 aMesh->SetMeshElementOnShape( newElem, aShapeId );
636 AddToSameGroups( newElem, elem, aMesh );
642 //=======================================================================
643 //function : getAngle
645 //=======================================================================
647 double getAngle(const SMDS_MeshElement * tr1,
648 const SMDS_MeshElement * tr2,
649 const SMDS_MeshNode * n1,
650 const SMDS_MeshNode * n2)
652 double angle = 2*PI; // bad angle
655 SMESH::Controls::TSequenceOfXYZ P1, P2;
656 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
657 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
659 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
660 if ( N1.SquareMagnitude() <= gp::Resolution() )
662 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
663 if ( N2.SquareMagnitude() <= gp::Resolution() )
666 // find the first diagonal node n1 in the triangles:
667 // take in account a diagonal link orientation
668 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
669 for ( int t = 0; t < 2; t++ )
671 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
672 int i = 0, iDiag = -1;
673 while ( it->more()) {
674 const SMDS_MeshElement *n = it->next();
675 if ( n == n1 || n == n2 )
679 if ( i - iDiag == 1 )
680 nFirst[ t ] = ( n == n1 ? n2 : n1 );
688 if ( nFirst[ 0 ] == nFirst[ 1 ] )
691 angle = N1.Angle( N2 );
696 // =================================================
697 // class generating a unique ID for a pair of nodes
698 // and able to return nodes by that ID
699 // =================================================
704 LinkID_Gen( const SMESHDS_Mesh* theMesh )
705 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
708 long GetLinkID (const SMDS_MeshNode * n1,
709 const SMDS_MeshNode * n2) const
711 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
714 bool GetNodes (const long theLinkID,
715 const SMDS_MeshNode* & theNode1,
716 const SMDS_MeshNode* & theNode2) const
718 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
719 if ( !theNode1 ) return false;
720 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
721 if ( !theNode2 ) return false;
727 const SMESHDS_Mesh* myMesh;
731 //=======================================================================
732 //function : TriToQuad
733 //purpose : Fuse neighbour triangles into quadrangles.
734 // theCrit is used to select a neighbour to fuse with.
735 // theMaxAngle is a max angle between element normals at which
736 // fusion is still performed.
737 //=======================================================================
739 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
740 SMESH::Controls::NumericalFunctorPtr theCrit,
741 const double theMaxAngle)
743 MESSAGE( "::TriToQuad()" );
745 if ( !theCrit.get() )
748 SMESHDS_Mesh * aMesh = GetMeshDS();
749 LinkID_Gen aLinkID_Gen( aMesh );
752 // Prepare data for algo: build
753 // 1. map of elements with their linkIDs
754 // 2. map of linkIDs with their elements
756 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
757 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
758 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
759 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
761 set<const SMDS_MeshElement*>::iterator itElem;
762 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
764 const SMDS_MeshElement* elem = (*itElem);
765 if ( !elem || elem->NbNodes() != 3 )
768 // retrieve element nodes
769 const SMDS_MeshNode* aNodes [4];
770 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
772 while ( itN->more() )
773 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
775 aNodes[ 3 ] = aNodes[ 0 ];
778 for ( i = 0; i < 3; i++ )
780 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
781 // check if elements sharing a link can be fused
782 itLE = mapLi_listEl.find( linkID );
783 if ( itLE != mapLi_listEl.end() )
785 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
787 const SMDS_MeshElement* elem2 = (*itLE).second.front();
788 // if ( FindShape( elem ) != FindShape( elem2 ))
789 // continue; // do not fuse triangles laying on different shapes
790 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
791 continue; // avoid making badly shaped quads
792 (*itLE).second.push_back( elem );
795 mapLi_listEl[ linkID ].push_back( elem );
796 mapEl_setLi [ elem ].insert( linkID );
799 // Clean the maps from the links shared by a sole element, ie
800 // links to which only one element is bound in mapLi_listEl
802 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
804 int nbElems = (*itLE).second.size();
806 const SMDS_MeshElement* elem = (*itLE).second.front();
807 long link = (*itLE).first;
808 mapEl_setLi[ elem ].erase( link );
809 if ( mapEl_setLi[ elem ].empty() )
810 mapEl_setLi.erase( elem );
814 // Algo: fuse triangles into quadrangles
816 while ( ! mapEl_setLi.empty() )
818 // Look for the start element:
819 // the element having the least nb of shared links
821 const SMDS_MeshElement* startElem = 0;
823 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
825 int nbLinks = (*itEL).second.size();
826 if ( nbLinks < minNbLinks )
828 startElem = (*itEL).first;
829 minNbLinks = nbLinks;
830 if ( minNbLinks == 1 )
835 // search elements to fuse starting from startElem or links of elements
836 // fused earlyer - startLinks
837 list< long > startLinks;
838 while ( startElem || !startLinks.empty() )
840 while ( !startElem && !startLinks.empty() )
842 // Get an element to start, by a link
843 long linkId = startLinks.front();
844 startLinks.pop_front();
845 itLE = mapLi_listEl.find( linkId );
846 if ( itLE != mapLi_listEl.end() )
848 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
849 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
850 for ( ; itE != listElem.end() ; itE++ )
851 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
853 mapLi_listEl.erase( itLE );
859 // Get candidates to be fused
861 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
864 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
865 set< long >& setLi = mapEl_setLi[ tr1 ];
866 ASSERT( !setLi.empty() );
867 set< long >::iterator itLi;
868 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
870 long linkID = (*itLi);
871 itLE = mapLi_listEl.find( linkID );
872 if ( itLE == mapLi_listEl.end() )
874 const SMDS_MeshElement* elem = (*itLE).second.front();
876 elem = (*itLE).second.back();
877 mapLi_listEl.erase( itLE );
878 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
891 // add other links of elem to list of links to re-start from
892 set< long >& links = mapEl_setLi[ elem ];
893 set< long >::iterator it;
894 for ( it = links.begin(); it != links.end(); it++ )
896 long linkID2 = (*it);
897 if ( linkID2 != linkID )
898 startLinks.push_back( linkID2 );
902 // Get nodes of possible quadrangles
904 const SMDS_MeshNode *n12 [4], *n13 [4];
905 bool Ok12 = false, Ok13 = false;
906 const SMDS_MeshNode *linkNode1, *linkNode2;
908 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
909 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
912 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
913 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
916 // Choose a pair to fuse
920 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
921 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
922 double aBadRate12 = getBadRate( &quad12, theCrit );
923 double aBadRate13 = getBadRate( &quad13, theCrit );
924 if ( aBadRate13 < aBadRate12 )
932 // and remove fused elems and removed links from the maps
934 mapEl_setLi.erase( tr1 );
937 mapEl_setLi.erase( tr2 );
938 mapLi_listEl.erase( link12 );
939 aMesh->ChangeElementNodes( tr1, n12, 4 );
940 aMesh->RemoveElement( tr2 );
944 mapEl_setLi.erase( tr3 );
945 mapLi_listEl.erase( link13 );
946 aMesh->ChangeElementNodes( tr1, n13, 4 );
947 aMesh->RemoveElement( tr3 );
950 // Next element to fuse: the rejected one
952 startElem = Ok12 ? tr3 : tr2;
954 } // if ( startElem )
955 } // while ( startElem || !startLinks.empty() )
956 } // while ( ! mapEl_setLi.empty() )
962 #define DUMPSO(txt) \
963 // cout << txt << endl;
964 //=============================================================================
968 //=============================================================================
969 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
973 int tmp = idNodes[ i1 ];
974 idNodes[ i1 ] = idNodes[ i2 ];
976 gp_Pnt Ptmp = P[ i1 ];
979 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
982 //=======================================================================
983 //function : SortQuadNodes
984 //purpose : Set 4 nodes of a quadrangle face in a good order.
985 // Swap 1<->2 or 2<->3 nodes and correspondingly return
987 //=======================================================================
989 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
994 for ( i = 0; i < 4; i++ ) {
995 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
997 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1000 gp_Vec V1(P[0], P[1]);
1001 gp_Vec V2(P[0], P[2]);
1002 gp_Vec V3(P[0], P[3]);
1004 gp_Vec Cross1 = V1 ^ V2;
1005 gp_Vec Cross2 = V2 ^ V3;
1008 if (Cross1.Dot(Cross2) < 0)
1013 if (Cross1.Dot(Cross2) < 0)
1017 swap ( i, i + 1, idNodes, P );
1019 // for ( int ii = 0; ii < 4; ii++ ) {
1020 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1021 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1027 //=======================================================================
1028 //function : SortHexaNodes
1029 //purpose : Set 8 nodes of a hexahedron in a good order.
1030 // Return success status
1031 //=======================================================================
1033 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1038 DUMPSO( "INPUT: ========================================");
1039 for ( i = 0; i < 8; i++ ) {
1040 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1041 if ( !n ) return false;
1042 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1043 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1045 DUMPSO( "========================================");
1048 set<int> faceNodes; // ids of bottom face nodes, to be found
1049 set<int> checkedId1; // ids of tried 2-nd nodes
1050 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1051 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1052 int iMin, iLoop1 = 0;
1054 // Loop to try the 2-nd nodes
1056 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1058 // Find not checked 2-nd node
1059 for ( i = 1; i < 8; i++ )
1060 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1061 int id1 = idNodes[i];
1062 swap ( 1, i, idNodes, P );
1063 checkedId1.insert ( id1 );
1067 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1068 // ie that all but meybe one (id3 which is on the same face) nodes
1069 // lay on the same side from the triangle plane.
1071 bool manyInPlane = false; // more than 4 nodes lay in plane
1073 while ( ++iLoop2 < 6 ) {
1075 // get 1-2-3 plane coeffs
1076 Standard_Real A, B, C, D;
1077 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1078 if ( N.SquareMagnitude() > gp::Resolution() )
1080 gp_Pln pln ( P[0], N );
1081 pln.Coefficients( A, B, C, D );
1083 // find the node (iMin) closest to pln
1084 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1086 for ( i = 3; i < 8; i++ ) {
1087 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1088 if ( fabs( dist[i] ) < minDist ) {
1089 minDist = fabs( dist[i] );
1092 if ( fabs( dist[i] ) <= tol )
1093 idInPln.insert( idNodes[i] );
1096 // there should not be more than 4 nodes in bottom plane
1097 if ( idInPln.size() > 1 )
1099 DUMPSO( "### idInPln.size() = " << idInPln.size());
1100 // idInPlane does not contain the first 3 nodes
1101 if ( manyInPlane || idInPln.size() == 5)
1102 return false; // all nodes in one plane
1105 // set the 1-st node to be not in plane
1106 for ( i = 3; i < 8; i++ ) {
1107 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1108 DUMPSO( "### Reset 0-th node");
1109 swap( 0, i, idNodes, P );
1114 // reset to re-check second nodes
1115 leastDist = DBL_MAX;
1119 break; // from iLoop2;
1122 // check that the other 4 nodes are on the same side
1123 bool sameSide = true;
1124 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1125 for ( i = 3; sameSide && i < 8; i++ ) {
1127 sameSide = ( isNeg == dist[i] <= 0.);
1130 // keep best solution
1131 if ( sameSide && minDist < leastDist ) {
1132 leastDist = minDist;
1134 faceNodes.insert( idNodes[ 1 ] );
1135 faceNodes.insert( idNodes[ 2 ] );
1136 faceNodes.insert( idNodes[ iMin ] );
1137 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1138 << " leastDist = " << leastDist);
1139 if ( leastDist <= DBL_MIN )
1144 // set next 3-d node to check
1145 int iNext = 2 + iLoop2;
1147 DUMPSO( "Try 2-nd");
1148 swap ( 2, iNext, idNodes, P );
1150 } // while ( iLoop2 < 6 )
1153 if ( faceNodes.empty() ) return false;
1155 // Put the faceNodes in proper places
1156 for ( i = 4; i < 8; i++ ) {
1157 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1158 // find a place to put
1160 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1162 DUMPSO( "Set faceNodes");
1163 swap ( iTo, i, idNodes, P );
1168 // Set nodes of the found bottom face in good order
1169 DUMPSO( " Found bottom face: ");
1170 i = SortQuadNodes( theMesh, idNodes );
1172 gp_Pnt Ptmp = P[ i ];
1177 // for ( int ii = 0; ii < 4; ii++ ) {
1178 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1179 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1182 // Gravity center of the top and bottom faces
1183 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1184 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1186 // Get direction from the bottom to the top face
1187 gp_Vec upDir ( aGCb, aGCt );
1188 Standard_Real upDirSize = upDir.Magnitude();
1189 if ( upDirSize <= gp::Resolution() ) return false;
1192 // Assure that the bottom face normal points up
1193 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1194 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1195 if ( Nb.Dot( upDir ) < 0 ) {
1196 DUMPSO( "Reverse bottom face");
1197 swap( 1, 3, idNodes, P );
1200 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1201 Standard_Real minDist = DBL_MAX;
1202 for ( i = 4; i < 8; i++ ) {
1203 // projection of P[i] to the plane defined by P[0] and upDir
1204 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1205 Standard_Real sqDist = P[0].SquareDistance( Pp );
1206 if ( sqDist < minDist ) {
1211 DUMPSO( "Set 4-th");
1212 swap ( 4, iMin, idNodes, P );
1214 // Set nodes of the top face in good order
1215 DUMPSO( "Sort top face");
1216 i = SortQuadNodes( theMesh, &idNodes[4] );
1219 gp_Pnt Ptmp = P[ i ];
1224 // Assure that direction of the top face normal is from the bottom face
1225 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1226 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1227 if ( Nt.Dot( upDir ) < 0 ) {
1228 DUMPSO( "Reverse top face");
1229 swap( 5, 7, idNodes, P );
1232 // DUMPSO( "OUTPUT: ========================================");
1233 // for ( i = 0; i < 8; i++ ) {
1234 // float *p = ugrid->GetPoint(idNodes[i]);
1235 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1241 //=======================================================================
1242 //function : laplacianSmooth
1243 //purpose : pulls theNode toward the center of surrounding nodes directly
1244 // connected to that node along an element edge
1245 //=======================================================================
1247 void laplacianSmooth(SMESHDS_Mesh * theMesh,
1248 const SMDS_MeshNode* theNode,
1249 const set<const SMDS_MeshElement*> & theElems,
1250 const set<const SMDS_MeshNode*> & theFixedNodes)
1252 // find surrounding nodes
1253 set< const SMDS_MeshNode* > nodeSet;
1254 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1255 while ( elemIt->more() )
1257 const SMDS_MeshElement* elem = elemIt->next();
1258 if ( theElems.find( elem ) == theElems.end() )
1261 int i = 0, iNode = 0;
1262 const SMDS_MeshNode* aNodes [4];
1263 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1264 while ( itN->more() )
1266 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1267 if ( aNodes[ i ] == theNode )
1270 nodeSet.insert( aNodes[ i ] );
1273 if ( elem->NbNodes() == 4 ) { // remove an opposite node
1274 iNode += ( iNode < 2 ) ? 2 : -2;
1275 nodeSet.erase( aNodes[ iNode ]);
1279 // compute new coodrs
1280 double coord[] = { 0., 0., 0. };
1281 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1282 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1283 const SMDS_MeshNode* node = (*nodeSetIt);
1284 coord[0] += node->X();
1285 coord[1] += node->Y();
1286 coord[2] += node->Z();
1288 double nbNodes = nodeSet.size();
1289 theMesh->MoveNode (theNode,
1295 //=======================================================================
1296 //function : centroidalSmooth
1297 //purpose : pulls theNode toward the element-area-weighted centroid of the
1298 // surrounding elements
1299 //=======================================================================
1301 void centroidalSmooth(SMESHDS_Mesh * theMesh,
1302 const SMDS_MeshNode* theNode,
1303 const set<const SMDS_MeshElement*> & theElems,
1304 const set<const SMDS_MeshNode*> & theFixedNodes)
1306 gp_XYZ aNewXYZ(0.,0.,0.);
1307 SMESH::Controls::Area anAreaFunc;
1308 double totalArea = 0.;
1311 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1312 while ( elemIt->more() )
1314 const SMDS_MeshElement* elem = elemIt->next();
1315 if ( theElems.find( elem ) == theElems.end() )
1320 gp_XYZ elemCenter(0.,0.,0.);
1321 SMESH::Controls::TSequenceOfXYZ aNodePoints;
1322 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1323 while ( itN->more() )
1325 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1326 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1327 aNodePoints.push_back( aP );
1330 double elemArea = anAreaFunc.GetValue( aNodePoints );
1331 totalArea += elemArea;
1332 elemCenter /= elem->NbNodes();
1333 aNewXYZ += elemCenter * elemArea;
1335 aNewXYZ /= totalArea;
1336 theMesh->MoveNode (theNode,
1342 //=======================================================================
1344 //purpose : Smooth theElements during theNbIterations or until a worst
1345 // element has aspect ratio <= theTgtAspectRatio.
1346 // Aspect Ratio varies in range [1.0, inf].
1347 // If theElements is empty, the whole mesh is smoothed.
1348 // theFixedNodes contains additionally fixed nodes. Nodes built
1349 // on edges and boundary nodes are always fixed.
1350 //=======================================================================
1352 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1353 set<const SMDS_MeshNode*> & theFixedNodes,
1354 const SmoothMethod theSmoothMethod,
1355 const int theNbIterations,
1356 double theTgtAspectRatio)
1358 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1360 SMESHDS_Mesh* aMesh = GetMeshDS();
1361 if ( theElems.empty() ) {
1363 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1364 while ( fIt->more() )
1365 theElems.insert( fIt->next() );
1368 set<const SMDS_MeshNode*> setMovableNodes;
1370 // Fill setMovableNodes
1372 map< const SMDS_MeshNode*, int > mapNodeNbFaces;
1373 set< const SMDS_MeshElement* >::iterator itElem;
1374 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1376 const SMDS_MeshElement* elem = (*itElem);
1377 if ( !elem || elem->GetType() != SMDSAbs_Face )
1380 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1381 while ( itN->more() ) {
1382 const SMDS_MeshNode* node =
1383 static_cast<const SMDS_MeshNode*>( itN->next() );
1385 if ( theFixedNodes.find( node ) != theFixedNodes.end() )
1388 // if node is on edge => it is fixed
1389 SMDS_PositionPtr aPositionPtr = node->GetPosition();
1390 if ( aPositionPtr.get() &&
1391 (aPositionPtr->GetTypeOfPosition() == SMDS_TOP_EDGE ||
1392 aPositionPtr->GetTypeOfPosition() == SMDS_TOP_VERTEX)) {
1393 theFixedNodes.insert( node );
1396 // fill mapNodeNbFaces in order to detect fixed boundary nodes
1397 map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1398 mapNodeNbFaces.find ( node );
1399 if ( nodeNbFacesIt == mapNodeNbFaces.end() )
1400 mapNodeNbFaces.insert( map<const SMDS_MeshNode*,int>::value_type( node, 1 ));
1402 (*nodeNbFacesIt).second++;
1405 // put not fixed nodes in setMovableNodes
1406 map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1407 mapNodeNbFaces.begin();
1408 for ( ; nodeNbFacesIt != mapNodeNbFaces.end(); nodeNbFacesIt++ ) {
1409 const SMDS_MeshNode* node = (*nodeNbFacesIt).first;
1410 // a node is on free boundary if it is shared by 1-2 faces
1411 if ( (*nodeNbFacesIt).second > 2 )
1412 setMovableNodes.insert( node );
1414 theFixedNodes.insert( node );
1419 if ( theTgtAspectRatio < 1.0 )
1420 theTgtAspectRatio = 1.0;
1422 SMESH::Controls::AspectRatio aQualityFunc;
1424 for ( int it = 0; it < theNbIterations; it++ )
1426 Standard_Real maxDisplacement = 0.;
1427 set<const SMDS_MeshNode*>::iterator movableNodesIt
1428 = setMovableNodes.begin();
1429 for ( ; movableNodesIt != setMovableNodes.end(); movableNodesIt++ )
1431 const SMDS_MeshNode* node = (*movableNodesIt);
1432 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1435 if ( theSmoothMethod == LAPLACIAN )
1436 laplacianSmooth( aMesh, node, theElems, theFixedNodes );
1438 centroidalSmooth( aMesh, node, theElems, theFixedNodes );
1441 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1442 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1443 if ( aDispl > maxDisplacement )
1444 maxDisplacement = aDispl;
1446 // no node movement => exit
1447 if ( maxDisplacement < 1.e-16 ) {
1448 MESSAGE("-- no node movement -- maxDisplacement: " << maxDisplacement << " it "<< it);
1452 // check elements quality
1453 double maxRatio = 0;
1454 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1456 const SMDS_MeshElement* elem = (*itElem);
1457 if ( !elem || elem->GetType() != SMDSAbs_Face )
1459 SMESH::Controls::TSequenceOfXYZ aPoints;
1460 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1461 double aValue = aQualityFunc.GetValue( aPoints );
1462 if ( aValue > maxRatio )
1466 if ( maxRatio <= theTgtAspectRatio ) {
1467 MESSAGE("-- quality achived -- maxRatio " << maxRatio << " it "<< it);
1470 if (it+1 == theNbIterations) {
1471 MESSAGE("-- Iteration limit exceeded --");
1476 //=======================================================================
1477 //function : isReverse
1478 //purpose : Return true if normal of prevNodes is not co-directied with
1479 // gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1480 // iNotSame is where prevNodes and nextNodes are different
1481 //=======================================================================
1483 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1484 const SMDS_MeshNode* nextNodes[],
1488 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1489 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1491 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1492 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1493 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1494 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1496 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1497 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1498 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1499 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1501 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1503 return (vA ^ vB) * vN < 0.0;
1506 //=======================================================================
1507 //function : sweepElement
1509 //=======================================================================
1511 static void sweepElement(SMESHDS_Mesh* aMesh,
1512 const SMDS_MeshElement* elem,
1513 const vector<TNodeOfNodeListMapItr> & newNodesItVec,
1514 list<const SMDS_MeshElement*>& newElems)
1516 // Loop on elem nodes:
1517 // find new nodes and detect same nodes indices
1518 int nbNodes = elem->NbNodes();
1519 list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
1520 const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
1521 int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
1523 for ( iNode = 0; iNode < nbNodes; iNode++ )
1525 TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
1526 const SMDS_MeshNode* node = nnIt->first;
1527 const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
1528 if ( listNewNodes.empty() )
1531 itNN[ iNode ] = listNewNodes.begin();
1532 prevNod[ iNode ] = node;
1533 nextNod[ iNode ] = listNewNodes.front();
1534 if ( prevNod[ iNode ] != nextNod [ iNode ])
1535 iNotSameNode = iNode;
1541 if ( nbSame == nbNodes || nbSame > 2) {
1542 MESSAGE( " Too many same nodes of element " << elem->GetID() );
1546 int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
1548 iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
1549 iAfterSame = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
1550 iOpposSame = ( iSameNode - 2 < 0 ? iSameNode + 2 : iSameNode - 2 );
1553 // check element orientation
1555 if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
1556 //MESSAGE("Reversed elem " << elem );
1560 int iAB = iAfterSame + iBeforeSame;
1561 iBeforeSame = iAB - iBeforeSame;
1562 iAfterSame = iAB - iAfterSame;
1566 // make new elements
1567 int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
1568 for (iStep = 0; iStep < nbSteps; iStep++ )
1571 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
1572 nextNod[ iNode ] = *itNN[ iNode ];
1575 SMDS_MeshElement* aNewElem = 0;
1580 aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
1586 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
1587 nextNod[ 1 ], nextNod[ 0 ] );
1589 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
1590 nextNod[ iNotSameNode ] );
1593 case 3: { // TRIANGLE
1595 if ( nbSame == 0 ) // --- pentahedron
1596 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1597 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
1599 else if ( nbSame == 1 ) // --- pyramid
1600 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iBeforeSame ],
1601 nextNod[ iBeforeSame ], nextNod[ iAfterSame ],
1602 nextNod[ iSameNode ]);
1604 else // 2 same nodes: --- tetrahedron
1605 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1606 nextNod[ iNotSameNode ]);
1609 case 4: { // QUADRANGLE
1611 if ( nbSame == 0 ) // --- hexahedron
1612 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
1613 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
1615 else if ( nbSame == 1 ) // --- pyramid + pentahedron
1617 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iBeforeSame ],
1618 nextNod[ iBeforeSame ], nextNod[ iAfterSame ],
1619 nextNod[ iSameNode ]);
1620 newElems.push_back( aNewElem );
1621 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
1622 prevNod[ iAfterSame ], nextNod[ iBeforeSame ],
1623 nextNod[ iOpposSame ], nextNod[ iAfterSame ] );
1625 else if ( nbSame == 2 ) // pentahedron
1627 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
1628 // iBeforeSame is same too
1629 aNewElem = aMesh->AddVolume (prevNod[ iOpposSame ], prevNod[ iBeforeSame ],
1630 nextNod[ iOpposSame ], prevNod[ iAfterSame ],
1631 prevNod[ iSameNode ], nextNod[ iAfterSame ]);
1633 // iAfterSame is same too
1634 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iSameNode ],
1635 nextNod[ iBeforeSame ], prevNod[ iOpposSame ],
1636 prevNod[ iAfterSame ], nextNod[ iOpposSame ]);
1644 newElems.push_back( aNewElem );
1646 // set new prev nodes
1647 for ( iNode = 0; iNode < nbNodes; iNode++ )
1648 prevNod[ iNode ] = nextNod[ iNode ];
1653 //=======================================================================
1654 //function : makeWalls
1655 //purpose : create 1D and 2D elements around swept elements
1656 //=======================================================================
1658 static void makeWalls (SMESHDS_Mesh* aMesh,
1659 TNodeOfNodeListMap& mapNewNodes,
1660 TElemOfElemListMap& newElemsMap,
1661 TElemOfVecOfNnlmiMap& elemNewNodesMap,
1662 set<const SMDS_MeshElement*>& elemSet)
1664 ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
1666 // Find nodes belonging to only one initial element - sweep them to get edges.
1668 TNodeOfNodeListMapItr nList = mapNewNodes.begin();
1669 for ( ; nList != mapNewNodes.end(); nList++ )
1671 const SMDS_MeshNode* node =
1672 static_cast<const SMDS_MeshNode*>( nList->first );
1673 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1674 int nbInitElems = 0;
1675 while ( eIt->more() && nbInitElems < 2 )
1676 if ( elemSet.find( eIt->next() ) != elemSet.end() )
1678 if ( nbInitElems < 2 ) {
1679 vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
1680 list<const SMDS_MeshElement*> newEdges;
1681 sweepElement( aMesh, node, newNodesItVec, newEdges );
1685 // Make a ceiling for each element ie an equal element of last new nodes.
1686 // Find free links of faces - make edges and sweep them into faces.
1688 TElemOfElemListMap::iterator itElem = newElemsMap.begin();
1689 TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
1690 for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
1692 const SMDS_MeshElement* elem = itElem->first;
1693 vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
1694 bool hasFreeLinks = false;
1696 set<const SMDS_MeshElement*> avoidSet;
1697 avoidSet.insert( elem );
1699 // loop on element nodes
1700 int iNode, nbNodes = vecNewNodes.size();
1701 vector<const SMDS_MeshNode*> lastNewNode( nbNodes ); // to make ceiling
1702 for ( iNode = 0; iNode < nbNodes; iNode++ )
1704 lastNewNode[ iNode ] = vecNewNodes[ iNode ]->second.back();
1706 // look for free links of a face
1708 if ( elem->GetType() == SMDSAbs_Face )
1711 int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1712 const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
1713 const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
1714 // check if a link is free
1715 if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
1717 hasFreeLinks = true;
1718 // make an edge and a ceiling for a new edge
1719 if ( !aMesh->FindEdge( n1, n2 ))
1720 aMesh->AddEdge( n1, n2 );
1721 n1 = vecNewNodes[ iNode ]->second.back();
1722 n2 = vecNewNodes[ iNext ]->second.back();
1723 if ( !aMesh->FindEdge( n1, n2 ))
1724 aMesh->AddEdge( n1, n2 );
1728 // sweep free links into faces
1732 list<const SMDS_MeshElement*> & newVolumes = itElem->second;
1733 int iStep, nbSteps = vecNewNodes[0]->second.size();
1734 int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
1736 set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
1737 for ( iNode = 0; iNode < nbNodes; iNode++ )
1738 initNodeSet.insert( vecNewNodes[ iNode ]->first );
1740 for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
1742 list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
1744 while ( iVol++ < volNb ) v++;
1745 // find indices of free faces of a volume
1747 SMDS_VolumeTool vTool( *v );
1748 int iF, nbF = vTool.NbFaces();
1749 for ( iF = 0; iF < nbF; iF ++ )
1750 if (vTool.IsFreeFace( iF ) &&
1751 vTool.GetFaceNodes( iF, faceNodeSet ) &&
1752 initNodeSet != faceNodeSet) // except an initial face
1753 fInd.push_back( iF );
1757 // create faces for all steps
1758 for ( iStep = 0; iStep < nbSteps; iStep++ )
1761 vTool.SetExternalNormal();
1762 list< int >::iterator ind = fInd.begin();
1763 for ( ; ind != fInd.end(); ind++ )
1765 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
1766 switch ( vTool.NbFaceNodes( *ind ) ) {
1768 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
1770 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
1773 // go to the next volume
1775 while ( iVol++ < nbVolumesByStep ) v++;
1778 } // sweep free links into faces
1780 // create a ceiling element, faces will be reversed
1782 switch ( nbNodes ) {
1784 aMesh->AddEdge(lastNewNode[ 0 ], lastNewNode[ 1 ]);
1787 if (!hasFreeLinks ||
1788 !aMesh->FindFace( lastNewNode[ 0 ], lastNewNode[ 2 ], lastNewNode[ 1 ]))
1789 aMesh->AddFace (lastNewNode[ 0 ], lastNewNode[ 2 ], lastNewNode[ 1 ]);
1792 if (!hasFreeLinks ||
1793 !aMesh->FindFace (lastNewNode[ 0 ], lastNewNode[ 3 ],
1794 lastNewNode[ 2 ], lastNewNode[ 1 ]))
1795 aMesh->AddFace (lastNewNode[ 0 ], lastNewNode[ 3 ],
1796 lastNewNode[ 2 ], lastNewNode[ 1 ]);
1800 } // loop on elements
1803 //=======================================================================
1804 //function : RotationSweep
1806 //=======================================================================
1808 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
1809 const gp_Ax1& theAxis,
1810 const double theAngle,
1811 const int theNbSteps,
1812 const double theTol)
1814 MESSAGE( "RotationSweep()");
1816 aTrsf.SetRotation( theAxis, theAngle );
1818 gp_Lin aLine( theAxis );
1819 double aSqTol = theTol * theTol;
1821 SMESHDS_Mesh* aMesh = GetMeshDS();
1823 TNodeOfNodeListMap mapNewNodes;
1824 TElemOfVecOfNnlmiMap mapElemNewNodes;
1825 TElemOfElemListMap newElemsMap;
1828 set< const SMDS_MeshElement* >::iterator itElem;
1829 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1831 const SMDS_MeshElement* elem = (*itElem);
1834 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
1835 newNodesItVec.reserve( elem->NbNodes() );
1837 // loop on elem nodes
1838 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1839 while ( itN->more() ) {
1841 // check if a node has been already sweeped
1842 const SMDS_MeshNode* node =
1843 static_cast<const SMDS_MeshNode*>( itN->next() );
1844 TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
1845 if ( nIt == mapNewNodes.end() )
1847 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
1848 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
1851 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
1853 aXYZ.Coord( coord[0], coord[1], coord[2] );
1854 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
1855 const SMDS_MeshNode * newNode = node;
1856 for ( int i = 0; i < theNbSteps; i++ ) {
1858 aTrsf.Transforms( coord[0], coord[1], coord[2] );
1859 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1861 listNewNodes.push_back( newNode );
1864 newNodesItVec.push_back( nIt );
1866 // make new elements
1867 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
1870 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
1873 //=======================================================================
1874 //function : ExtrusionSweep
1876 //=======================================================================
1878 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
1879 const gp_Vec& theStep,
1880 const int theNbSteps)
1883 aTrsf.SetTranslation( theStep );
1885 SMESHDS_Mesh* aMesh = GetMeshDS();
1887 TNodeOfNodeListMap mapNewNodes;
1888 TElemOfVecOfNnlmiMap mapElemNewNodes;
1889 TElemOfElemListMap newElemsMap;
1892 set< const SMDS_MeshElement* >::iterator itElem;
1893 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1895 // check element type
1896 const SMDS_MeshElement* elem = (*itElem);
1900 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
1901 newNodesItVec.reserve( elem->NbNodes() );
1903 // loop on elem nodes
1904 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1905 while ( itN->more() ) {
1907 // check if a node has been already sweeped
1908 const SMDS_MeshNode* node =
1909 static_cast<const SMDS_MeshNode*>( itN->next() );
1910 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
1911 if ( nIt == mapNewNodes.end() )
1913 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
1914 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
1917 double coord[] = { node->X(), node->Y(), node->Z() };
1918 for ( int i = 0; i < theNbSteps; i++ ) {
1919 aTrsf.Transforms( coord[0], coord[1], coord[2] );
1920 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1921 listNewNodes.push_back( newNode );
1924 newNodesItVec.push_back( nIt );
1926 // make new elements
1927 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
1930 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
1934 //=======================================================================
1935 //function : Transform
1937 //=======================================================================
1939 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
1940 const gp_Trsf& theTrsf,
1944 switch ( theTrsf.Form() ) {
1950 needReverse = false;
1953 SMESHDS_Mesh* aMesh = GetMeshDS();
1955 // map old node to new one
1956 TNodeNodeMap nodeMap;
1958 // elements sharing moved nodes; those of them which have all
1959 // nodes mirrored but are not in theElems are to be reversed
1960 set<const SMDS_MeshElement*> inverseElemSet;
1963 set< const SMDS_MeshElement* >::iterator itElem;
1964 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1966 const SMDS_MeshElement* elem = (*itElem);
1970 // loop on elem nodes
1971 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1972 while ( itN->more() ) {
1974 // check if a node has been already transormed
1975 const SMDS_MeshNode* node =
1976 static_cast<const SMDS_MeshNode*>( itN->next() );
1977 if (nodeMap.find( node ) != nodeMap.end() )
1981 coord[0] = node->X();
1982 coord[1] = node->Y();
1983 coord[2] = node->Z();
1984 theTrsf.Transforms( coord[0], coord[1], coord[2] );
1985 const SMDS_MeshNode * newNode = node;
1987 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1989 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
1990 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
1992 // keep inverse elements
1993 if ( !theCopy && needReverse ) {
1994 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
1995 while ( invElemIt->more() )
1996 inverseElemSet.insert( invElemIt->next() );
2001 // either new elements are to be created
2002 // or a mirrored element are to be reversed
2003 if ( !theCopy && !needReverse)
2006 if ( !inverseElemSet.empty()) {
2007 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2008 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2009 theElems.insert( *invElemIt );
2012 // replicate or reverse elements
2015 REV_TETRA = 0, // = nbNodes - 4
2016 REV_PYRAMID = 1, // = nbNodes - 4
2017 REV_PENTA = 2, // = nbNodes - 4
2019 REV_HEXA = 4, // = nbNodes - 4
2023 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
2024 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
2025 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
2026 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
2027 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
2028 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
2031 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2033 const SMDS_MeshElement* elem = (*itElem);
2034 if ( !elem || elem->GetType() == SMDSAbs_Node )
2037 int nbNodes = elem->NbNodes();
2038 int elemType = elem->GetType();
2040 int* i = index[ FORWARD ];
2041 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2042 if ( elemType == SMDSAbs_Face )
2043 i = index[ REV_FACE ];
2045 i = index[ nbNodes - 4 ];
2047 // find transformed nodes
2048 const SMDS_MeshNode* nodes[8];
2050 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2051 while ( itN->more() )
2053 const SMDS_MeshNode* node =
2054 static_cast<const SMDS_MeshNode*>( itN->next() );
2055 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
2056 if ( nodeMapIt == nodeMap.end() )
2057 break; // not all nodes transformed
2058 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
2060 if ( iNode != nbNodes )
2061 continue; // not all nodes transformed
2065 // add a new element
2066 switch ( elemType ) {
2068 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
2072 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2074 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
2076 case SMDSAbs_Volume:
2078 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
2079 else if ( nbNodes == 8 )
2080 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2081 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
2082 else if ( nbNodes == 6 )
2083 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2084 nodes[ 4 ], nodes[ 5 ]);
2085 else if ( nbNodes == 5 )
2086 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2094 // reverse element as it was reversed by transformation
2096 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
2101 //=======================================================================
2102 //function : FindCoincidentNodes
2103 //purpose : Return list of group of nodes close to each other within theTolerance
2104 // Search among theNodes or in the whole mesh if theNodes is empty.
2105 //=======================================================================
2107 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
2108 const double theTolerance,
2109 TListOfListOfNodes & theGroupsOfNodes)
2111 double tol2 = theTolerance * theTolerance;
2113 list<const SMDS_MeshNode*> nodes;
2114 if ( theNodes.empty() )
2115 { // get all nodes in the mesh
2116 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
2117 while ( nIt->more() )
2118 nodes.push_back( nIt->next() );
2122 nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
2125 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
2126 for ( ; it1 != nodes.end(); it1++ )
2128 const SMDS_MeshNode* n1 = *it1;
2129 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
2131 list<const SMDS_MeshNode*> * groupPtr = 0;
2133 for ( it2++; it2 != nodes.end(); it2++ )
2135 const SMDS_MeshNode* n2 = *it2;
2136 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
2137 if ( p1.SquareDistance( p2 ) <= tol2 )
2140 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
2141 groupPtr = & theGroupsOfNodes.back();
2142 groupPtr->push_back( n1 );
2144 groupPtr->push_back( n2 );
2145 it2 = nodes.erase( it2 );
2152 //=======================================================================
2153 //function : MergeNodes
2154 //purpose : In each group, the cdr of nodes are substituted by the first one
2156 //=======================================================================
2158 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
2160 SMESHDS_Mesh* aMesh = GetMeshDS();
2162 TNodeNodeMap nodeNodeMap; // node to replace - new node
2163 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
2164 list< int > rmElemIds, rmNodeIds;
2166 // Fill nodeNodeMap and elems
2168 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
2169 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
2171 list<const SMDS_MeshNode*>& nodes = *grIt;
2172 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
2173 const SMDS_MeshNode* nToKeep = *nIt;
2174 for ( ; nIt != nodes.end(); nIt++ )
2176 const SMDS_MeshNode* nToRemove = *nIt;
2177 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
2178 if ( nToRemove != nToKeep ) {
2179 rmNodeIds.push_back( nToRemove->GetID() );
2180 AddToSameGroups( nToKeep, nToRemove, aMesh );
2183 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
2184 while ( invElemIt->more() )
2185 elems.insert( invElemIt->next() );
2188 // Change element nodes or remove an element
2190 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
2191 for ( ; eIt != elems.end(); eIt++ )
2193 const SMDS_MeshElement* elem = *eIt;
2194 int nbNodes = elem->NbNodes();
2195 int aShapeId = FindShape( elem );
2197 set<const SMDS_MeshNode*> nodeSet;
2198 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
2199 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
2201 // get new seq of nodes
2202 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2203 while ( itN->more() )
2205 const SMDS_MeshNode* n =
2206 static_cast<const SMDS_MeshNode*>( itN->next() );
2208 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
2209 if ( nnIt != nodeNodeMap.end() ) { // n sticks
2211 iRepl[ nbRepl++ ] = iCur;
2213 curNodes[ iCur ] = n;
2214 bool isUnique = nodeSet.insert( n ).second;
2216 uniqueNodes[ iUnique++ ] = n;
2220 // Analyse element topology after replacement
2223 int nbUniqueNodes = nodeSet.size();
2224 if ( nbNodes != nbUniqueNodes ) // some nodes stick
2226 switch ( nbNodes ) {
2227 case 2: ///////////////////////////////////// EDGE
2228 isOk = false; break;
2229 case 3: ///////////////////////////////////// TRIANGLE
2230 isOk = false; break;
2232 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
2234 else { //////////////////////////////////// QUADRANGLE
2235 if ( nbUniqueNodes < 3 )
2237 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
2238 isOk = false; // opposite nodes stick
2241 case 6: ///////////////////////////////////// PENTAHEDRON
2242 if ( nbUniqueNodes == 4 ) {
2243 // ---------------------------------> tetrahedron
2245 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
2246 // all top nodes stick: reverse a bottom
2247 uniqueNodes[ 0 ] = curNodes [ 1 ];
2248 uniqueNodes[ 1 ] = curNodes [ 0 ];
2250 else if (nbRepl == 3 &&
2251 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
2252 // all bottom nodes stick: set a top before
2253 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
2254 uniqueNodes[ 0 ] = curNodes [ 3 ];
2255 uniqueNodes[ 1 ] = curNodes [ 4 ];
2256 uniqueNodes[ 2 ] = curNodes [ 5 ];
2258 else if (nbRepl == 4 &&
2259 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
2260 // a lateral face turns into a line: reverse a bottom
2261 uniqueNodes[ 0 ] = curNodes [ 1 ];
2262 uniqueNodes[ 1 ] = curNodes [ 0 ];
2267 else if ( nbUniqueNodes == 5 ) {
2268 // PENTAHEDRON --------------------> 2 tetrahedrons
2269 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
2270 // a bottom node sticks with a linked top one
2272 SMDS_MeshElement* newElem =
2273 aMesh->AddVolume(curNodes[ 3 ],
2276 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
2278 aMesh->SetMeshElementOnShape( newElem, aShapeId );
2279 // 2. : reverse a bottom
2280 uniqueNodes[ 0 ] = curNodes [ 1 ];
2281 uniqueNodes[ 1 ] = curNodes [ 0 ];
2290 case 8: { //////////////////////////////////// HEXAHEDRON
2292 SMDS_VolumeTool hexa (elem);
2293 hexa.SetExternalNormal();
2294 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
2295 //////////////////////// ---> tetrahedron
2296 for ( int iFace = 0; iFace < 6; iFace++ ) {
2297 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2298 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2299 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2300 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2301 // one face turns into a point ...
2302 int iOppFace = hexa.GetOppFaceIndex( iFace );
2303 ind = hexa.GetFaceNodesIndices( iOppFace );
2305 iUnique = 2; // reverse a tetrahedron bottom
2306 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
2307 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2309 else if ( iUnique >= 0 )
2310 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2312 if ( nbStick == 1 ) {
2313 // ... and the opposite one - into a triangle.
2315 ind = hexa.GetFaceNodesIndices( iFace );
2316 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
2323 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
2324 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
2325 for ( int iFace = 0; iFace < 6; iFace++ ) {
2326 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2327 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2328 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2329 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2330 // one face turns into a point ...
2331 int iOppFace = hexa.GetOppFaceIndex( iFace );
2332 ind = hexa.GetFaceNodesIndices( iOppFace );
2334 iUnique = 2; // reverse a tetrahedron 1 bottom
2335 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
2336 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2338 else if ( iUnique >= 0 )
2339 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2341 if ( nbStick == 0 ) {
2342 // ... and the opposite one is a quadrangle
2344 const int* indTop = hexa.GetFaceNodesIndices( iFace );
2345 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
2348 SMDS_MeshElement* newElem =
2349 aMesh->AddVolume(curNodes[ind[ 0 ]],
2352 curNodes[indTop[ 0 ]]);
2354 aMesh->SetMeshElementOnShape( newElem, aShapeId );
2361 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
2362 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
2363 // find indices of quad and tri faces
2364 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
2365 for ( iFace = 0; iFace < 6; iFace++ ) {
2366 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2368 for ( iCur = 0; iCur < 4; iCur++ )
2369 nodeSet.insert( curNodes[ind[ iCur ]] );
2370 nbUniqueNodes = nodeSet.size();
2371 if ( nbUniqueNodes == 3 )
2372 iTriFace[ nbTri++ ] = iFace;
2373 else if ( nbUniqueNodes == 4 )
2374 iQuadFace[ nbQuad++ ] = iFace;
2376 if (nbQuad == 2 && nbTri == 4 &&
2377 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
2378 // 2 opposite quadrangles stuck with a diagonal;
2379 // sample groups of merged indices: (0-4)(2-6)
2380 // --------------------------------------------> 2 tetrahedrons
2381 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
2382 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
2383 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
2384 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
2385 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
2386 // stuck with 0-2 diagonal
2394 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
2395 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
2396 // stuck with 1-3 diagonal
2408 uniqueNodes[ 0 ] = curNodes [ i0 ];
2409 uniqueNodes[ 1 ] = curNodes [ i1d ];
2410 uniqueNodes[ 2 ] = curNodes [ i3d ];
2411 uniqueNodes[ 3 ] = curNodes [ i0t ];
2414 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
2419 aMesh->SetMeshElementOnShape( newElem, aShapeId );
2422 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
2423 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
2424 // --------------------------------------------> prism
2425 // find 2 opposite triangles
2427 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
2428 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
2429 // find indices of kept and replaced nodes
2430 // and fill unique nodes of 2 opposite triangles
2431 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
2432 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
2433 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
2434 // fill unique nodes
2437 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
2438 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
2439 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
2441 // iCur of a linked node of the opposite face (make normals co-directed):
2442 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
2443 // check that correspondent corners of triangles are linked
2444 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
2447 uniqueNodes[ iUnique ] = n;
2448 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
2457 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
2463 } // switch ( nbNodes )
2465 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
2468 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
2470 rmElemIds.push_back( elem->GetID() );
2472 } // loop on elements
2474 // Remove equal nodes and bad elements
2476 Remove( rmNodeIds, true );
2477 Remove( rmElemIds, false );
2481 //=======================================================================
2482 //function : MergeEqualElements
2483 //purpose : Remove all but one of elements built on the same nodes.
2484 //=======================================================================
2486 void SMESH_MeshEditor::MergeEqualElements()
2488 SMESHDS_Mesh* aMesh = GetMeshDS();
2490 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
2491 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
2492 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
2494 list< int > rmElemIds; // IDs of elems to remove
2496 for ( int iDim = 1; iDim <= 3; iDim++ ) {
2498 set< set <const SMDS_MeshElement*> > setOfNodeSet;
2502 const SMDS_MeshElement* elem = 0;
2504 if ( eIt->more() ) elem = eIt->next();
2505 } else if ( iDim == 2 ) {
2506 if ( fIt->more() ) elem = fIt->next();
2508 if ( vIt->more() ) elem = vIt->next();
2513 set <const SMDS_MeshElement*> nodeSet;
2514 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
2515 while ( nodeIt->more() )
2516 nodeSet.insert( nodeIt->next() );
2519 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
2521 rmElemIds.push_back( elem->GetID() );
2525 Remove( rmElemIds, false );
2528 //=======================================================================
2529 //function : FindFaceInSet
2530 //purpose : Return a face having linked nodes n1 and n2 and which is
2531 // - not in avoidSet,
2532 // - in elemSet provided that !elemSet.empty()
2533 //=======================================================================
2535 const SMDS_MeshElement*
2536 SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode* n1,
2537 const SMDS_MeshNode* n2,
2538 const set<const SMDS_MeshElement*>& elemSet,
2539 const set<const SMDS_MeshElement*>& avoidSet)
2542 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
2543 while ( invElemIt->more() ) { // loop on inverse elements of n1
2544 const SMDS_MeshElement* elem = invElemIt->next();
2545 if (elem->GetType() != SMDSAbs_Face ||
2546 avoidSet.find( elem ) != avoidSet.end() )
2548 if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
2550 // get face nodes and find index of n1
2551 int i1, nbN = elem->NbNodes(), iNode = 0;
2552 const SMDS_MeshNode* faceNodes[ nbN ], *n;
2553 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2554 while ( nIt->more() ) {
2555 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2556 if ( faceNodes[ iNode++ ] == n1 )
2559 // find a n2 linked to n1
2560 for ( iNode = 0; iNode < 2; iNode++ ) {
2561 if ( iNode ) // node before n1
2562 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
2563 else // node after n1
2564 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
2572 //=======================================================================
2573 //function : findAdjacentFace
2575 //=======================================================================
2577 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
2578 const SMDS_MeshNode* n2,
2579 const SMDS_MeshElement* elem)
2581 set<const SMDS_MeshElement*> elemSet, avoidSet;
2583 avoidSet.insert ( elem );
2584 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
2587 //=======================================================================
2588 //function : findFreeBorder
2590 //=======================================================================
2592 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
2594 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
2595 const SMDS_MeshNode* theSecondNode,
2596 const SMDS_MeshNode* theLastNode,
2597 list< const SMDS_MeshNode* > & theNodes,
2598 list< const SMDS_MeshElement* > & theFaces)
2600 if ( !theFirstNode || !theSecondNode )
2602 // find border face between theFirstNode and theSecondNode
2603 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
2607 theFaces.push_back( curElem );
2608 theNodes.push_back( theFirstNode );
2609 theNodes.push_back( theSecondNode );
2611 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
2612 set < const SMDS_MeshElement* > foundElems;
2613 bool needTheLast = ( theLastNode != 0 );
2615 while ( nStart != theLastNode )
2617 if ( nStart == theFirstNode )
2618 return !needTheLast;
2620 // find all free border faces sharing form nStart
2622 list< const SMDS_MeshElement* > curElemList;
2623 list< const SMDS_MeshNode* > nStartList;
2624 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
2625 while ( invElemIt->more() ) {
2626 const SMDS_MeshElement* e = invElemIt->next();
2627 if ( e == curElem || foundElems.insert( e ).second )
2630 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2631 int iNode = 0, nbNodes = e->NbNodes();
2632 while ( nIt->more() )
2633 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2634 nodes[ iNode ] = nodes[ 0 ];
2636 for ( iNode = 0; iNode < nbNodes; iNode++ )
2637 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
2638 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
2639 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
2641 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
2642 curElemList.push_back( e );
2646 // analyse the found
2648 int nbNewBorders = curElemList.size();
2649 if ( nbNewBorders == 0 ) {
2650 // no free border furthermore
2651 return !needTheLast;
2653 else if ( nbNewBorders == 1 ) {
2654 // one more element found
2656 nStart = nStartList.front();
2657 curElem = curElemList.front();
2658 theFaces.push_back( curElem );
2659 theNodes.push_back( nStart );
2662 // several continuations found
2663 list< const SMDS_MeshElement* >::iterator curElemIt;
2664 list< const SMDS_MeshNode* >::iterator nStartIt;
2665 // check if one of them reached the last node
2666 if ( needTheLast ) {
2667 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
2668 curElemIt!= curElemList.end();
2669 curElemIt++, nStartIt++ )
2670 if ( *nStartIt == theLastNode ) {
2671 theFaces.push_back( *curElemIt );
2672 theNodes.push_back( *nStartIt );
2676 // find the best free border by the continuations
2677 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
2678 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
2679 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
2680 curElemIt!= curElemList.end();
2681 curElemIt++, nStartIt++ )
2683 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
2684 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
2685 // find one more free border
2686 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
2690 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
2691 // choice: clear a worse one
2692 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
2693 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
2694 contNodes[ iWorse ].clear();
2695 contFaces[ iWorse ].clear();
2698 if ( contNodes[0].empty() && contNodes[1].empty() )
2701 // append the best free border
2702 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
2703 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
2704 theNodes.pop_back(); // remove nIgnore
2705 theNodes.pop_back(); // remove nStart
2706 theFaces.pop_back(); // remove curElem
2707 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
2708 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
2709 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
2710 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
2713 } // several continuations found
2714 } // while ( nStart != theLastNode )
2719 //=======================================================================
2720 //function : CheckFreeBorderNodes
2721 //purpose : Return true if the tree nodes are on a free border
2722 //=======================================================================
2724 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
2725 const SMDS_MeshNode* theNode2,
2726 const SMDS_MeshNode* theNode3)
2728 list< const SMDS_MeshNode* > nodes;
2729 list< const SMDS_MeshElement* > faces;
2730 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
2733 //=======================================================================
2734 //function : SewFreeBorder
2736 //=======================================================================
2738 SMESH_MeshEditor::Sew_Error
2739 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
2740 const SMDS_MeshNode* theBordSecondNode,
2741 const SMDS_MeshNode* theBordLastNode,
2742 const SMDS_MeshNode* theSideFirstNode,
2743 const SMDS_MeshNode* theSideSecondNode,
2744 const SMDS_MeshNode* theSideThirdNode,
2745 bool theSideIsFreeBorder)
2747 MESSAGE("::SewFreeBorder()");
2748 Sew_Error aResult = SEW_OK;
2750 // ====================================
2751 // find side nodes and elements
2752 // ====================================
2754 list< const SMDS_MeshNode* > nSide[ 2 ];
2755 list< const SMDS_MeshElement* > eSide[ 2 ];
2756 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
2757 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
2761 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
2762 nSide[0], eSide[0])) {
2763 MESSAGE(" Free Border 1 not found " );
2764 aResult = SEW_BORDER1_NOT_FOUND;
2766 if (theSideIsFreeBorder)
2770 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
2771 nSide[1], eSide[1])) {
2772 MESSAGE(" Free Border 2 not found " );
2773 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
2776 if ( aResult != SEW_OK )
2779 if (!theSideIsFreeBorder)
2784 // -------------------------------------------------------------------------
2786 // 1. If nodes to merge are not coincident, move nodes of the free border
2787 // from the coord sys defined by the direction from the first to last
2788 // nodes of the border to the correspondent sys of the side 2
2789 // 2. On the side 2, find the links most co-directed with the correspondent
2790 // links of the free border
2791 // -------------------------------------------------------------------------
2793 // 1. Since sewing may brake if there are volumes to split on the side 2,
2794 // we wont move nodes but just compute new coordinates for them
2795 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
2796 TNodeXYZMap nBordXYZ;
2797 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
2798 list< const SMDS_MeshNode* >::iterator nBordIt;
2800 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
2801 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
2802 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
2803 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
2804 double tol2 = 1.e-8;
2805 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
2806 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
2808 // Need node movement.
2810 // find X and Z axes to create trsf
2811 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
2813 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
2815 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
2818 gp_Ax3 toBordAx( Pb1, Zb, X );
2819 gp_Ax3 fromSideAx( Ps1, Zs, X );
2820 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
2822 gp_Trsf toBordSys, fromSide2Sys;
2823 toBordSys.SetTransformation( toBordAx );
2824 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
2825 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
2828 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
2829 const SMDS_MeshNode* n = *nBordIt;
2830 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
2831 toBordSys.Transforms( xyz );
2832 fromSide2Sys.Transforms( xyz );
2833 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
2838 // just insert nodes XYZ in the nBordXYZ map
2839 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
2840 const SMDS_MeshNode* n = *nBordIt;
2841 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
2845 // 2. On the side 2, find the links most co-directed with the correspondent
2846 // links of the free border
2848 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
2849 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
2850 sideNodes.push_back( theSideFirstNode );
2852 bool hasVolumes = false;
2853 LinkID_Gen aLinkID_Gen( GetMeshDS() );
2854 set<long> foundSideLinkIDs, checkedLinkIDs;
2855 SMDS_VolumeTool volume;
2856 const SMDS_MeshNode* faceNodes[ 4 ];
2858 const SMDS_MeshNode* sideNode;
2859 const SMDS_MeshElement* sideElem;
2860 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
2861 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
2862 nBordIt = bordNodes.begin();
2864 // border node position and border link direction to compare with
2865 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
2866 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
2867 // choose next side node by link direction or by closeness to
2868 // the current border node:
2869 bool searchByDir = ( *nBordIt != theBordLastNode );
2871 // find the next node on the Side 2
2873 double maxDot = -DBL_MAX, minDist = DBL_MAX;
2875 checkedLinkIDs.clear();
2876 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
2878 SMDS_ElemIteratorPtr invElemIt
2879 = prevSideNode->GetInverseElementIterator();
2880 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
2881 const SMDS_MeshElement* elem = invElemIt->next();
2882 // prepare data for a loop on links, of a face or a volume
2883 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
2884 bool isVolume = volume.Set( elem );
2885 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
2886 if ( isVolume ) // --volume
2888 else if ( nbNodes > 2 ) { // --face
2889 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
2890 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2891 while ( nIt->more() ) {
2892 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2893 if ( nodes[ iNode++ ] == prevSideNode )
2894 iPrevNode = iNode - 1;
2896 // there are 2 links to check
2901 // loop on links, to be precise, on the second node of links
2902 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2903 const SMDS_MeshNode* n = nodes[ iNode ];
2905 if ( !volume.IsLinked( n, prevSideNode ))
2908 if ( iNode ) // a node before prevSideNode
2909 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
2910 else // a node after prevSideNode
2911 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
2913 // check if this link was already used
2914 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
2915 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
2916 if (!isJustChecked &&
2917 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
2918 // test a link geometrically
2919 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
2920 bool linkIsBetter = false;
2922 if ( searchByDir ) { // choose most co-directed link
2923 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
2924 linkIsBetter = ( dot > maxDot );
2926 else { // choose link with the node closest to bordPos
2927 dist = ( nextXYZ - bordPos ).SquareModulus();
2928 linkIsBetter = ( dist < minDist );
2930 if ( linkIsBetter ) {
2939 } // loop on inverse elements of prevSideNode
2942 MESSAGE(" Cant find path by links of the Side 2 ");
2943 return SEW_BAD_SIDE_NODES;
2945 sideNodes.push_back( sideNode );
2946 sideElems.push_back( sideElem );
2947 foundSideLinkIDs.insert ( linkID );
2948 prevSideNode = sideNode;
2950 if ( *nBordIt == theBordLastNode )
2951 searchByDir = false;
2953 // find the next border link to compare with
2954 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
2955 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
2956 while ( *nBordIt != theBordLastNode && !searchByDir ) {
2957 prevBordNode = *nBordIt;
2959 bordPos = nBordXYZ[ *nBordIt ];
2960 bordDir = bordPos - nBordXYZ[ prevBordNode ];
2961 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
2965 while ( sideNode != theSideSecondNode );
2967 if ( hasVolumes && sideNodes.size () != bordNodes.size() ) {
2968 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
2969 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
2971 } // end nodes search on the side 2
2973 // ============================
2974 // sew the border to the side 2
2975 // ============================
2977 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
2978 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
2980 TListOfListOfNodes nodeGroupsToMerge;
2981 if ( nbNodes[0] == nbNodes[1] ||
2982 ( theSideIsFreeBorder && !theSideThirdNode)) {
2984 // all nodes are to be merged
2986 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
2987 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
2988 nIt[0]++, nIt[1]++ )
2990 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
2991 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
2992 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
2997 // insert new nodes into the border and the side to get equal nb of segments
2999 // get normalized parameters of nodes on the borders
3000 double param[ 2 ][ maxNbNodes ];
3002 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
3003 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
3004 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
3005 const SMDS_MeshNode* nPrev = *nIt;
3006 double bordLength = 0;
3007 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
3008 const SMDS_MeshNode* nCur = *nIt;
3009 gp_XYZ segment (nCur->X() - nPrev->X(),
3010 nCur->Y() - nPrev->Y(),
3011 nCur->Z() - nPrev->Z());
3012 double segmentLen = segment.Modulus();
3013 bordLength += segmentLen;
3014 param[ iBord ][ iNode ] = bordLength;
3017 // normalize within [0,1]
3018 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
3019 param[ iBord ][ iNode ] /= bordLength;
3023 // loop on border segments
3024 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
3025 int i[ 2 ] = { 0, 0 };
3026 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
3027 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
3029 TElemOfNodeListMap insertMap;
3030 TElemOfNodeListMap::iterator insertMapIt;
3032 // key: elem to insert nodes into
3033 // value: 2 nodes to insert between + nodes to be inserted
3035 bool next[ 2 ] = { false, false };
3037 // find min adjacent segment length after sewing
3038 double nextParam = 10., prevParam = 0;
3039 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
3040 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
3041 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
3042 if ( i[ iBord ] > 0 )
3043 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
3045 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
3046 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
3047 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
3049 // choose to insert or to merge nodes
3050 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
3051 if ( Abs( du ) <= minSegLen * 0.2 ) {
3054 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
3055 const SMDS_MeshNode* n0 = *nIt[0];
3056 const SMDS_MeshNode* n1 = *nIt[1];
3057 nodeGroupsToMerge.back().push_back( n1 );
3058 nodeGroupsToMerge.back().push_back( n0 );
3059 // position of node of the border changes due to merge
3060 param[ 0 ][ i[0] ] += du;
3061 // move n1 for the sake of elem shape evaluation during insertion.
3062 // n1 will be removed by MergeNodes() anyway
3063 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
3064 next[0] = next[1] = true;
3069 int intoBord = ( du < 0 ) ? 0 : 1;
3070 const SMDS_MeshElement* elem = *eIt[ intoBord ];
3071 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
3072 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
3073 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
3074 if ( intoBord == 1 ) {
3075 // move node of the border to be on a link of elem of the side
3076 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
3077 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
3078 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
3079 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
3080 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
3082 insertMapIt = insertMap.find( elem );
3083 bool notFound = ( insertMapIt == insertMap.end() );
3084 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
3086 // insert into another link of the same element:
3087 // 1. perform insertion into the other link of the elem
3088 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
3089 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
3090 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
3091 InsertNodesIntoLink( elem, n12, n22, nodeList );
3092 // 2. perform insertion into the link of adjacent faces
3094 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
3096 InsertNodesIntoLink( adjElem, n12, n22, nodeList );
3100 // 3. find an element appeared on n1 and n2 after the insertion
3101 insertMap.erase( elem );
3102 elem = findAdjacentFace( n1, n2, 0 );
3104 if ( notFound || otherLink ) {
3105 // add element and nodes of the side into the insertMap
3106 insertMapIt = insertMap.insert
3107 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
3108 (*insertMapIt).second.push_back( n1 );
3109 (*insertMapIt).second.push_back( n2 );
3111 // add node to be inserted into elem
3112 (*insertMapIt).second.push_back( nIns );
3113 next[ 1 - intoBord ] = true;
3116 // go to the next segment
3117 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
3118 if ( next[ iBord ] ) {
3119 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
3121 nPrev[ iBord ] = *nIt[ iBord ];
3122 nIt[ iBord ]++; i[ iBord ]++;
3126 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
3128 // perform insertion of nodes into elements
3130 for (insertMapIt = insertMap.begin();
3131 insertMapIt != insertMap.end();
3134 const SMDS_MeshElement* elem = (*insertMapIt).first;
3135 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
3136 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
3137 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
3139 InsertNodesIntoLink( elem, n1, n2, nodeList );
3141 if ( !theSideIsFreeBorder ) {
3142 // look for and insert nodes into the faces adjacent to elem
3144 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
3146 InsertNodesIntoLink( adjElem, n1, n2, nodeList );
3153 } // end: insert new nodes
3155 MergeNodes ( nodeGroupsToMerge );
3160 //=======================================================================
3161 //function : InsertNodesIntoLink
3162 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
3163 // and theBetweenNode2 and split theElement
3164 //=======================================================================
3166 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
3167 const SMDS_MeshNode* theBetweenNode1,
3168 const SMDS_MeshNode* theBetweenNode2,
3169 list<const SMDS_MeshNode*>& theNodesToInsert)
3171 if ( theFace->GetType() != SMDSAbs_Face ) return;
3173 // find indices of 2 link nodes and of the rest nodes
3174 int iNode = 0, il1, il2, i3, i4;
3175 il1 = il2 = i3 = i4 = -1;
3176 const SMDS_MeshNode* nodes[ 8 ];
3177 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
3178 while ( nodeIt->more() ) {
3179 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3180 if ( n == theBetweenNode1 )
3182 else if ( n == theBetweenNode2 )
3188 nodes[ iNode++ ] = n;
3190 if ( il1 < 0 || il2 < 0 || i3 < 0 )
3193 // arrange link nodes to go one after another regarding the face orientation
3194 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
3199 theNodesToInsert.reverse();
3201 // check that not link nodes of a quadrangles are in good order
3202 int nbFaceNodes = theFace->NbNodes();
3203 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
3209 // put theNodesToInsert between theBetweenNode1 and theBetweenNode2
3210 int nbLinkNodes = 2 + theNodesToInsert.size();
3211 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
3212 linkNodes[ 0 ] = nodes[ il1 ];
3213 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
3214 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
3215 for ( iNode = 1; nIt != theNodesToInsert.end(); nIt++ ) {
3216 linkNodes[ iNode++ ] = *nIt;
3218 // decide how to split a quadrangle: compare possible variants
3219 // and choose which of splits to be a quadrangle
3220 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
3221 if ( nbFaceNodes == 3 )
3223 iBestQuad = nbSplits;
3226 else if ( nbFaceNodes == 4 )
3228 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
3229 double aBestRate = DBL_MAX;
3230 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
3232 double aBadRate = 0;
3233 // evaluate elements quality
3234 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
3235 if ( iSplit == iQuad ) {
3236 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
3240 aBadRate += getBadRate( &quad, aCrit );
3243 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
3245 nodes[ iSplit < iQuad ? i4 : i3 ]);
3246 aBadRate += getBadRate( &tria, aCrit );
3250 if ( aBadRate < aBestRate ) {
3252 aBestRate = aBadRate;
3257 // create new elements
3258 SMESHDS_Mesh *aMesh = GetMeshDS();
3259 int aShapeId = FindShape( theFace );
3262 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
3263 SMDS_MeshElement* newElem = 0;
3264 if ( iSplit == iBestQuad )
3265 newElem = aMesh->AddFace (linkNodes[ i1++ ],
3270 newElem = aMesh->AddFace (linkNodes[ i1++ ],
3272 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
3273 if ( aShapeId && newElem )
3274 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3277 // change nodes of theFace
3278 const SMDS_MeshNode* newNodes[ 4 ];
3279 newNodes[ 0 ] = linkNodes[ i1 ];
3280 newNodes[ 1 ] = linkNodes[ i2 ];
3281 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
3282 newNodes[ 3 ] = nodes[ i4 ];
3283 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
3286 //=======================================================================
3287 //function : SewSideElements
3289 //=======================================================================
3291 SMESH_MeshEditor::Sew_Error
3292 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
3293 set<const SMDS_MeshElement*>& theSide2,
3294 const SMDS_MeshNode* theFirstNode1,
3295 const SMDS_MeshNode* theFirstNode2,
3296 const SMDS_MeshNode* theSecondNode1,
3297 const SMDS_MeshNode* theSecondNode2)
3299 MESSAGE ("::::SewSideElements()");
3300 if ( theSide1.size() != theSide2.size() )
3301 return SEW_DIFF_NB_OF_ELEMENTS;
3303 Sew_Error aResult = SEW_OK;
3305 // 1. Build set of faces representing each side
3306 // 2. Find which nodes of the side 1 to merge with ones on the side 2
3307 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
3309 // =======================================================================
3310 // 1. Build set of faces representing each side:
3311 // =======================================================================
3312 // a. build set of nodes belonging to faces
3313 // b. complete set of faces: find missing fices whose nodes are in set of nodes
3314 // c. create temporary faces representing side of volumes if correspondent
3315 // face does not exist
3317 SMESHDS_Mesh* aMesh = GetMeshDS();
3318 SMDS_Mesh aTmpFacesMesh;
3319 set<const SMDS_MeshElement*> faceSet1, faceSet2;
3320 set<const SMDS_MeshElement*> volSet1, volSet2;
3321 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
3322 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
3323 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
3324 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
3325 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
3326 int iSide, iFace, iNode;
3328 for ( iSide = 0; iSide < 2; iSide++ ) {
3329 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
3330 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
3331 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3332 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
3333 set<const SMDS_MeshElement*>::iterator vIt, eIt;
3334 set<const SMDS_MeshNode*>::iterator nIt;
3336 // -----------------------------------------------------------
3337 // 1a. Collect nodes of existing faces
3338 // and build set of face nodes in order to detect missing
3339 // faces corresponing to sides of volumes
3340 // -----------------------------------------------------------
3342 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
3344 // loop on the given element of a side
3345 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
3346 const SMDS_MeshElement* elem = *eIt;
3347 if ( elem->GetType() == SMDSAbs_Face ) {
3348 faceSet->insert( elem );
3349 set <const SMDS_MeshNode*> faceNodeSet;
3350 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3351 while ( nodeIt->more() ) {
3352 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3353 nodeSet->insert( n );
3354 faceNodeSet.insert( n );
3356 setOfFaceNodeSet.insert( faceNodeSet );
3358 else if ( elem->GetType() == SMDSAbs_Volume )
3359 volSet->insert( elem );
3361 // ------------------------------------------------------------------------------
3362 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
3363 // ------------------------------------------------------------------------------
3365 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3366 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3367 while ( fIt->more() ) { // loop on faces sharing a node
3368 const SMDS_MeshElement* f = fIt->next();
3369 if ( faceSet->find( f ) == faceSet->end() ) {
3370 // check if all nodes are in nodeSet and
3371 // complete setOfFaceNodeSet if they are
3372 set <const SMDS_MeshNode*> faceNodeSet;
3373 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3374 bool allInSet = true;
3375 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3376 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3377 if ( nodeSet->find( n ) == nodeSet->end() )
3380 faceNodeSet.insert( n );
3383 faceSet->insert( f );
3384 setOfFaceNodeSet.insert( faceNodeSet );
3390 // -------------------------------------------------------------------------
3391 // 1c. Create temporary faces representing sides of volumes if correspondent
3392 // face does not exist
3393 // -------------------------------------------------------------------------
3395 if ( !volSet->empty() )
3397 //int nodeSetSize = nodeSet->size();
3399 // loop on given volumes
3400 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
3401 SMDS_VolumeTool vol (*vIt);
3402 // loop on volume faces: find free faces
3403 // --------------------------------------
3404 list<const SMDS_MeshElement* > freeFaceList;
3405 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
3406 if ( !vol.IsFreeFace( iFace ))
3408 // check if there is already a face with same nodes in a face set
3409 const SMDS_MeshElement* aFreeFace = 0;
3410 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
3411 int nbNodes = vol.NbFaceNodes( iFace );
3412 set <const SMDS_MeshNode*> faceNodeSet;
3413 vol.GetFaceNodes( iFace, faceNodeSet );
3414 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
3416 // no such a face is given but it still can exist, check it
3418 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
3420 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3423 // create a temporary face
3425 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
3427 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3430 freeFaceList.push_back( aFreeFace );
3432 } // loop on faces of a volume
3434 // choose one of several free faces
3435 // --------------------------------------
3436 if ( freeFaceList.size() > 1 ) {
3437 // choose a face having max nb of nodes shared by other elems of a side
3438 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
3439 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
3440 while ( fIt != freeFaceList.end() ) { // loop on free faces
3441 int nbSharedNodes = 0;
3442 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3443 while ( nodeIt->more() ) { // loop on free face nodes
3444 const SMDS_MeshNode* n =
3445 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3446 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
3447 while ( invElemIt->more() ) {
3448 const SMDS_MeshElement* e = invElemIt->next();
3449 if ( faceSet->find( e ) != faceSet->end() )
3451 if ( elemSet->find( e ) != elemSet->end() )
3455 if ( nbSharedNodes >= maxNbNodes ) {
3456 maxNbNodes = nbSharedNodes;
3460 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
3462 if ( freeFaceList.size() > 1 )
3464 // could not choose one face, use another way
3465 // choose a face most close to the bary center of the opposite side
3466 gp_XYZ aBC( 0., 0., 0. );
3467 set <const SMDS_MeshNode*> addedNodes;
3468 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
3469 eIt = elemSet2->begin();
3470 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
3471 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
3472 while ( nodeIt->more() ) { // loop on free face nodes
3473 const SMDS_MeshNode* n =
3474 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3475 if ( addedNodes.insert( n ).second )
3476 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
3479 aBC /= addedNodes.size();
3480 double minDist = DBL_MAX;
3481 fIt = freeFaceList.begin();
3482 while ( fIt != freeFaceList.end() ) { // loop on free faces
3484 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3485 while ( nodeIt->more() ) { // loop on free face nodes
3486 const SMDS_MeshNode* n =
3487 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3488 gp_XYZ p( n->X(),n->Y(),n->Z() );
3489 dist += ( aBC - p ).SquareModulus();
3491 if ( dist < minDist ) {
3493 freeFaceList.erase( freeFaceList.begin(), fIt++ );
3496 fIt = freeFaceList.erase( fIt++ );
3499 } // choose one of several free faces of a volume
3501 if ( freeFaceList.size() == 1 ) {
3502 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
3503 faceSet->insert( aFreeFace );
3504 // complete a node set with nodes of a found free face
3505 // for ( iNode = 0; iNode < ; iNode++ )
3506 // nodeSet->insert( fNodes[ iNode ] );
3509 } // loop on volumes of a side
3511 // // complete a set of faces if new nodes in a nodeSet appeared
3512 // // ----------------------------------------------------------
3513 // if ( nodeSetSize != nodeSet->size() ) {
3514 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3515 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3516 // while ( fIt->more() ) { // loop on faces sharing a node
3517 // const SMDS_MeshElement* f = fIt->next();
3518 // if ( faceSet->find( f ) == faceSet->end() ) {
3519 // // check if all nodes are in nodeSet and
3520 // // complete setOfFaceNodeSet if they are
3521 // set <const SMDS_MeshNode*> faceNodeSet;
3522 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3523 // bool allInSet = true;
3524 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3525 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3526 // if ( nodeSet->find( n ) == nodeSet->end() )
3527 // allInSet = false;
3529 // faceNodeSet.insert( n );
3531 // if ( allInSet ) {
3532 // faceSet->insert( f );
3533 // setOfFaceNodeSet.insert( faceNodeSet );
3539 } // Create temporary faces, if there are volumes given
3542 if ( faceSet1.size() != faceSet2.size() ) {
3543 // delete temporary faces: they are in reverseElements of actual nodes
3544 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
3545 while ( tmpFaceIt->more() )
3546 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
3547 MESSAGE("Diff nb of faces");
3548 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3551 // ============================================================
3552 // 2. Find nodes to merge:
3553 // bind a node to remove to a node to put instead
3554 // ============================================================
3556 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
3557 if ( theFirstNode1 != theFirstNode2 )
3558 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
3559 if ( theSecondNode1 != theSecondNode2 )
3560 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
3562 LinkID_Gen aLinkID_Gen( GetMeshDS() );
3563 set< long > linkIdSet; // links to process
3564 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
3566 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
3567 list< TPairOfNodes > linkList[2];
3568 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
3569 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
3570 // loop on links in linkList; find faces by links and append links
3571 // of the found faces to linkList
3572 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
3573 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
3575 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
3576 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
3577 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
3580 // by links, find faces in the face sets,
3581 // and find indices of link nodes in the found faces;
3582 // in a face set, there is only one or no face sharing a link
3583 // ---------------------------------------------------------------
3585 const SMDS_MeshElement* face[] = { 0, 0 };
3586 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
3587 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
3588 int iLinkNode[2][2];
3589 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
3590 const SMDS_MeshNode* n1 = link[iSide].first;
3591 const SMDS_MeshNode* n2 = link[iSide].second;
3592 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3593 set< const SMDS_MeshElement* > fMap;
3594 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
3595 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
3596 SMDS_ElemIteratorPtr fIt = n->facesIterator();
3597 while ( fIt->more() ) { // loop on faces sharing a node
3598 const SMDS_MeshElement* f = fIt->next();
3599 if (faceSet->find( f ) != faceSet->end() && // f is in face set
3600 ! fMap.insert( f ).second ) // f encounters twice
3602 if ( face[ iSide ] ) {
3603 MESSAGE( "2 faces per link " );
3604 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
3608 faceSet->erase( f );
3609 // get face nodes and find ones of a link
3611 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3612 while ( nIt->more() ) {
3613 const SMDS_MeshNode* n =
3614 static_cast<const SMDS_MeshNode*>( nIt->next() );
3616 iLinkNode[ iSide ][ 0 ] = iNode;
3618 iLinkNode[ iSide ][ 1 ] = iNode;
3619 else if ( notLinkNodes[ iSide ][ 0 ] )
3620 notLinkNodes[ iSide ][ 1 ] = n;
3622 notLinkNodes[ iSide ][ 0 ] = n;
3623 faceNodes[ iSide ][ iNode++ ] = n;
3625 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
3630 // check similarity of elements of the sides
3631 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
3632 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
3633 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
3634 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
3636 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3637 break; // do not return because it s necessary to remove tmp faces
3640 // set nodes to merge
3641 // -------------------
3643 if ( face[0] && face[1] )
3645 int nbNodes = face[0]->NbNodes();
3646 if ( nbNodes != face[1]->NbNodes() ) {
3647 MESSAGE("Diff nb of face nodes");
3648 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3649 break; // do not return because it s necessary to remove tmp faces
3651 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
3653 nReplaceMap.insert( TNodeNodeMap::value_type
3654 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
3656 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
3657 // analyse link orientation in faces
3658 int i1 = iLinkNode[ iSide ][ 0 ];
3659 int i2 = iLinkNode[ iSide ][ 1 ];
3660 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
3661 // if notLinkNodes are the first and the last ones, then
3662 // their order does not correspond to the link orientation
3663 if (( i1 == 1 && i2 == 2 ) ||
3664 ( i1 == 2 && i2 == 1 ))
3665 reverse[ iSide ] = !reverse[ iSide ];
3667 if ( reverse[0] == reverse[1] ) {
3668 nReplaceMap.insert( TNodeNodeMap::value_type
3669 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
3670 nReplaceMap.insert( TNodeNodeMap::value_type
3671 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
3674 nReplaceMap.insert( TNodeNodeMap::value_type
3675 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
3676 nReplaceMap.insert( TNodeNodeMap::value_type
3677 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
3681 // add other links of the faces to linkList
3682 // -----------------------------------------
3684 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
3685 for ( iNode = 0; iNode < nbNodes; iNode++ )
3687 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
3688 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
3689 if ( !iter_isnew.second ) { // already in a set: no need to process
3690 linkIdSet.erase( iter_isnew.first );
3692 else // new in set == encountered for the first time: add
3694 const SMDS_MeshNode* n1 = nodes[ iNode ];
3695 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
3696 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
3697 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
3701 } // loop on link lists
3703 if ( aResult == SEW_OK &&
3704 ( linkIt[0] != linkList[0].end() ||
3705 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
3706 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
3707 " " << (faceSetPtr[1]->empty()));
3708 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3711 // ====================================================================
3712 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
3713 // ====================================================================
3715 // delete temporary faces: they are in reverseElements of actual nodes
3716 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
3717 while ( tmpFaceIt->more() )
3718 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
3720 if ( aResult != SEW_OK)
3723 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
3724 // loop on nodes replacement map
3725 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
3726 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
3727 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
3729 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
3730 nodeIDsToRemove.push_back( nToRemove->GetID() );
3731 // loop on elements sharing nToRemove
3732 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3733 while ( invElemIt->more() ) {
3734 const SMDS_MeshElement* e = invElemIt->next();
3735 // get a new suite of nodes: make replacement
3736 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
3737 const SMDS_MeshNode* nodes[ 8 ];
3738 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3739 while ( nIt->more() ) {
3740 const SMDS_MeshNode* n =
3741 static_cast<const SMDS_MeshNode*>( nIt->next() );
3742 nnIt = nReplaceMap.find( n );
3743 if ( nnIt != nReplaceMap.end() ) {
3749 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
3750 // elemIDsToRemove.push_back( e->GetID() );
3753 aMesh->ChangeElementNodes( e, nodes, nbNodes );
3757 Remove( nodeIDsToRemove, true );