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 "SMESH_ControlsDef.hxx"
33 #include "SMDS_FaceOfNodes.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESH_subMesh.hxx"
39 #include <TopTools_ListIteratorOfListOfShape.hxx>
40 #include <TopTools_ListOfShape.hxx>
43 #include <gp_Trsf.hxx>
50 #include "utilities.h"
53 using namespace SMESH::Controls;
55 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
56 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
57 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
59 //=======================================================================
60 //function : SMESH_MeshEditor
62 //=======================================================================
64 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
69 //=======================================================================
71 //purpose : Remove a node or an element.
72 // Modify a compute state of sub-meshes which become empty
73 //=======================================================================
75 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
79 SMESHDS_Mesh* aMesh = GetMeshDS();
80 set< SMESH_subMesh *> smmap;
82 list<int>::const_iterator it = theIDs.begin();
83 for ( ; it != theIDs.end(); it++ )
85 const SMDS_MeshElement * elem;
87 elem = aMesh->FindNode( *it );
89 elem = aMesh->FindElement( *it );
93 // Find sub-meshes to notify about modification
94 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
95 while ( nodeIt->more() )
97 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
98 const SMDS_PositionPtr& aPosition = node->GetPosition();
99 if ( aPosition.get() ) {
100 int aShapeID = aPosition->GetShapeId();
102 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
103 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
112 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
114 aMesh->RemoveElement( elem );
117 // Notify sub-meshes about modification
118 if ( !smmap.empty() ) {
119 set< SMESH_subMesh *>::iterator smIt;
120 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
121 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
126 //=======================================================================
127 //function : FindShape
128 //purpose : Return an index of the shape theElem is on
129 // or zero if a shape not found
130 //=======================================================================
132 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
134 SMESHDS_Mesh * aMesh = GetMeshDS();
135 if ( aMesh->ShapeToMesh().IsNull() )
138 if ( theElem->GetType() == SMDSAbs_Node )
140 const SMDS_PositionPtr& aPosition =
141 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
142 if ( aPosition.get() )
143 return aPosition->GetShapeId();
148 TopoDS_Shape aShape; // the shape a node is on
149 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
150 while ( nodeIt->more() )
152 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
153 const SMDS_PositionPtr& aPosition = node->GetPosition();
154 if ( aPosition.get() ) {
155 int aShapeID = aPosition->GetShapeId();
156 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
159 if ( sm->Contains( theElem ))
161 if ( aShape.IsNull() )
162 aShape = aMesh->IndexToShape( aShapeID );
166 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
171 // None of nodes is on a proper shape,
172 // find the shape among ancestors of aShape on which a node is
173 if ( aShape.IsNull() ) {
174 //MESSAGE ("::FindShape() - NONE node is on shape")
177 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
178 for ( ; ancIt.More(); ancIt.Next() )
180 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
181 if ( sm && sm->Contains( theElem ))
182 return aMesh->ShapeToIndex( ancIt.Value() );
185 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
189 //=======================================================================
190 //function : InverseDiag
191 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
192 // but having other common link.
193 // Return False if args are improper
194 //=======================================================================
196 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
197 const SMDS_MeshElement * theTria2 )
199 if (!theTria1 || !theTria2)
201 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
202 if (!F1) return false;
203 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
204 if (!F2) return false;
206 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
207 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
211 // put nodes in array and find out indices of the same ones
212 const SMDS_MeshNode* aNodes [6];
213 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
215 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
218 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
220 if ( i > 2 ) // theTria2
221 // find same node of theTria1
222 for ( int j = 0; j < 3; j++ )
223 if ( aNodes[ i ] == aNodes[ j ]) {
232 return false; // theTria1 is not a triangle
233 it = theTria2->nodesIterator();
235 if ( i == 6 && it->more() )
236 return false; // theTria2 is not a triangle
239 // find indices of 1,2 and of A,B in theTria1
240 int iA = 0, iB = 0, i1 = 0, i2 = 0;
241 for ( i = 0; i < 6; i++ )
243 if ( sameInd [ i ] == 0 )
250 // nodes 1 and 2 should not be the same
251 if ( aNodes[ i1 ] == aNodes[ i2 ] )
256 aNodes[ iA ] = aNodes[ i2 ];
258 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
260 //MESSAGE( theTria1 << theTria2 );
262 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
263 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
265 //MESSAGE( theTria1 << theTria2 );
270 //=======================================================================
271 //function : findTriangles
272 //purpose : find triangles sharing theNode1-theNode2 link
273 //=======================================================================
275 static bool findTriangles(const SMDS_MeshNode * theNode1,
276 const SMDS_MeshNode * theNode2,
277 const SMDS_MeshElement*& theTria1,
278 const SMDS_MeshElement*& theTria2)
280 if ( !theNode1 || !theNode2 ) return false;
282 theTria1 = theTria2 = 0;
284 set< const SMDS_MeshElement* > emap;
285 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
287 const SMDS_MeshElement* elem = it->next();
288 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
291 it = theNode2->GetInverseElementIterator();
293 const SMDS_MeshElement* elem = it->next();
294 if ( elem->GetType() == SMDSAbs_Face &&
295 emap.find( elem ) != emap.end() )
303 return ( theTria1 && theTria2 );
306 //=======================================================================
307 //function : InverseDiag
308 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
309 // with ones built on the same 4 nodes but having other common link.
310 // Return false if proper faces not found
311 //=======================================================================
313 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
314 const SMDS_MeshNode * theNode2)
316 MESSAGE( "::InverseDiag()" );
318 const SMDS_MeshElement *tr1, *tr2;
319 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
322 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
323 if (!F1) return false;
324 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
325 if (!F2) return false;
327 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
328 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
332 // put nodes in array
333 // and find indices of 1,2 and of A in tr1 and of B in tr2
334 int i, iA1 = 0, i1 = 0;
335 const SMDS_MeshNode* aNodes1 [3];
336 SMDS_ElemIteratorPtr it;
337 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
338 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
339 if ( aNodes1[ i ] == theNode1 )
340 iA1 = i; // node A in tr1
341 else if ( aNodes1[ i ] != theNode2 )
345 const SMDS_MeshNode* aNodes2 [3];
346 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
347 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
348 if ( aNodes2[ i ] == theNode2 )
349 iB2 = i; // node B in tr2
350 else if ( aNodes2[ i ] != theNode1 )
354 // nodes 1 and 2 should not be the same
355 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
359 aNodes1[ iA1 ] = aNodes2[ i2 ];
361 aNodes2[ iB2 ] = aNodes1[ i1 ];
363 //MESSAGE( tr1 << tr2 );
365 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
366 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
368 //MESSAGE( tr1 << tr2 );
374 //=======================================================================
375 //function : getQuadrangleNodes
376 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
377 // fusion of triangles tr1 and tr2 having shared link on
378 // theNode1 and theNode2
379 //=======================================================================
381 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
382 const SMDS_MeshNode * theNode1,
383 const SMDS_MeshNode * theNode2,
384 const SMDS_MeshElement * tr1,
385 const SMDS_MeshElement * tr2 )
387 // find the 4-th node to insert into tr1
388 const SMDS_MeshNode* n4 = 0;
389 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
390 while ( !n4 && it->more() )
392 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
393 bool isDiag = ( n == theNode1 || n == theNode2 );
397 // Make an array of nodes to be in a quadrangle
398 int iNode = 0, iFirstDiag = -1;
399 it = tr1->nodesIterator();
402 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
403 bool isDiag = ( n == theNode1 || n == theNode2 );
406 if ( iFirstDiag < 0 )
408 else if ( iNode - iFirstDiag == 1 )
409 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
413 return false; // tr1 and tr2 should not have all the same nodes
415 theQuadNodes[ iNode++ ] = n;
417 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
418 theQuadNodes[ iNode ] = n4;
423 //=======================================================================
424 //function : DeleteDiag
425 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
426 // with a quadrangle built on the same 4 nodes.
427 // Return false if proper faces not found
428 //=======================================================================
430 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
431 const SMDS_MeshNode * theNode2)
433 MESSAGE( "::DeleteDiag()" );
435 const SMDS_MeshElement *tr1, *tr2;
436 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
439 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
440 if (!F1) return false;
441 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
442 if (!F2) return false;
444 const SMDS_MeshNode* aNodes [ 4 ];
445 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
448 //MESSAGE( endl << tr1 << tr2 );
450 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
451 GetMeshDS()->RemoveElement( tr2 );
453 //MESSAGE( endl << tr1 );
458 //=======================================================================
459 //function : Reorient
460 //purpose : Reverse the normal of theFace
461 // Return false if theFace is null
462 //=======================================================================
464 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theFace)
466 if (!theFace) return false;
467 const SMDS_FaceOfNodes* F = dynamic_cast<const SMDS_FaceOfNodes*>( theFace );
468 if (!F) return false;
470 const SMDS_MeshNode* aNodes [4], *tmpNode;
472 SMDS_ElemIteratorPtr it = theFace->nodesIterator();
474 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( it->next() );
476 // exchange nodes with indeces 0 and 2
477 tmpNode = aNodes[ 0 ];
478 aNodes[ 0 ] = aNodes[ 2 ];
479 aNodes[ 2 ] = tmpNode;
481 //MESSAGE( theFace );
483 GetMeshDS()->ChangeElementNodes( theFace, aNodes, theFace->NbNodes() );
485 //MESSAGE( theFace );
490 //=======================================================================
491 //function : getBadRate
493 //=======================================================================
495 static double getBadRate (const SMDS_MeshElement* theElem,
496 SMESH::Controls::NumericalFunctorPtr& theCrit)
499 if ( !theElem || !theCrit->GetPoints( theElem, P ))
501 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
504 //=======================================================================
505 //function : QuadToTri
506 //purpose : Cut quadrangles into triangles.
507 // theCrit is used to select a diagonal to cut
508 //=======================================================================
510 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
511 SMESH::Controls::NumericalFunctorPtr theCrit)
513 MESSAGE( "::QuadToTri()" );
515 if ( !theCrit.get() )
518 SMESHDS_Mesh * aMesh = GetMeshDS();
520 set< const SMDS_MeshElement * >::iterator itElem;
521 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
523 const SMDS_MeshElement* elem = (*itElem);
524 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
527 // retrieve element nodes
528 const SMDS_MeshNode* aNodes [4];
529 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
531 while ( itN->more() )
532 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
534 // compare two sets of possible triangles
535 double aBadRate1, aBadRate2; // to what extent a set is bad
536 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
537 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
538 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
540 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
541 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
542 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
544 int aShapeId = FindShape( elem );
545 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
546 // << " ShapeID = " << aShapeId << endl << elem );
548 if ( aBadRate1 <= aBadRate2 ) {
549 // tr1 + tr2 is better
550 aMesh->ChangeElementNodes( elem, aNodes, 3 );
551 //MESSAGE( endl << elem );
553 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
556 // tr3 + tr4 is better
557 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
558 //MESSAGE( endl << elem );
560 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
562 //MESSAGE( endl << elem );
564 // put a new triangle on the same shape
566 aMesh->SetMeshElementOnShape( elem, aShapeId );
572 //=======================================================================
573 //function : addToSameGroups
574 //purpose : add elemToAdd to the groups the elemInGroups belongs to
575 //=======================================================================
577 static void addToSameGroups (const SMDS_MeshElement* elemToAdd,
578 const SMDS_MeshElement* elemInGroups,
579 SMESHDS_Mesh * aMesh)
581 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
582 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
583 for ( ; grIt != groups.end(); grIt++ ) {
584 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
585 if ( group && group->SMDSGroup().Contains( elemInGroups ))
586 group->SMDSGroup().Add( elemToAdd );
590 //=======================================================================
591 //function : QuadToTri
592 //purpose : Cut quadrangles into triangles.
593 // theCrit is used to select a diagonal to cut
594 //=======================================================================
596 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
597 const bool the13Diag)
599 MESSAGE( "::QuadToTri()" );
601 SMESHDS_Mesh * aMesh = GetMeshDS();
603 set< const SMDS_MeshElement * >::iterator itElem;
604 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
606 const SMDS_MeshElement* elem = (*itElem);
607 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
610 // retrieve element nodes
611 const SMDS_MeshNode* aNodes [4];
612 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
614 while ( itN->more() )
615 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
617 int aShapeId = FindShape( elem );
618 const SMDS_MeshElement* newElem = 0;
621 aMesh->ChangeElementNodes( elem, aNodes, 3 );
622 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
626 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
627 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
630 // put a new triangle on the same shape and add to the same groups
633 aMesh->SetMeshElementOnShape( newElem, aShapeId );
635 addToSameGroups( newElem, elem, aMesh );
641 //=======================================================================
642 //function : getAngle
644 //=======================================================================
646 double getAngle(const SMDS_MeshElement * tr1,
647 const SMDS_MeshElement * tr2,
648 const SMDS_MeshNode * n1,
649 const SMDS_MeshNode * n2)
651 double angle = 2*PI; // bad angle
654 TSequenceOfXYZ P1, P2;
655 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
656 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
658 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
659 if ( N1.SquareMagnitude() <= gp::Resolution() )
661 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
662 if ( N2.SquareMagnitude() <= gp::Resolution() )
665 // find the first diagonal node n1 in the triangles:
666 // take in account a diagonal link orientation
667 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
668 for ( int t = 0; t < 2; t++ )
670 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
671 int i = 0, iDiag = -1;
672 while ( it->more()) {
673 const SMDS_MeshElement *n = it->next();
674 if ( n == n1 || n == n2 )
678 if ( i - iDiag == 1 )
679 nFirst[ t ] = ( n == n1 ? n2 : n1 );
687 if ( nFirst[ 0 ] == nFirst[ 1 ] )
690 angle = N1.Angle( N2 );
695 // =================================================
696 // class generating a unique ID for a pair of nodes
697 // and able to return nodes by that ID
698 // =================================================
703 LinkID_Gen( const SMESHDS_Mesh* theMesh )
704 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
707 long GetLinkID (const SMDS_MeshNode * n1,
708 const SMDS_MeshNode * n2) const
710 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
713 bool GetNodes (const long theLinkID,
714 const SMDS_MeshNode* & theNode1,
715 const SMDS_MeshNode* & theNode2) const
717 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
718 if ( !theNode1 ) return false;
719 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
720 if ( !theNode2 ) return false;
726 const SMESHDS_Mesh* myMesh;
730 //=======================================================================
731 //function : TriToQuad
732 //purpose : Fuse neighbour triangles into quadrangles.
733 // theCrit is used to select a neighbour to fuse with.
734 // theMaxAngle is a max angle between element normals at which
735 // fusion is still performed.
736 //=======================================================================
738 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
739 SMESH::Controls::NumericalFunctorPtr theCrit,
740 const double theMaxAngle)
742 MESSAGE( "::TriToQuad()" );
744 if ( !theCrit.get() )
747 SMESHDS_Mesh * aMesh = GetMeshDS();
748 LinkID_Gen aLinkID_Gen( aMesh );
751 // Prepare data for algo: build
752 // 1. map of elements with their linkIDs
753 // 2. map of linkIDs with their elements
755 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
756 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
757 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
758 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
760 set<const SMDS_MeshElement*>::iterator itElem;
761 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
763 const SMDS_MeshElement* elem = (*itElem);
764 if ( !elem || elem->NbNodes() != 3 )
767 // retrieve element nodes
768 const SMDS_MeshNode* aNodes [4];
769 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
771 while ( itN->more() )
772 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
774 aNodes[ 3 ] = aNodes[ 0 ];
777 for ( i = 0; i < 3; i++ )
779 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
780 // check if elements sharing a link can be fused
781 itLE = mapLi_listEl.find( linkID );
782 if ( itLE != mapLi_listEl.end() )
784 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
786 const SMDS_MeshElement* elem2 = (*itLE).second.front();
787 // if ( FindShape( elem ) != FindShape( elem2 ))
788 // continue; // do not fuse triangles laying on different shapes
789 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
790 continue; // avoid making badly shaped quads
791 (*itLE).second.push_back( elem );
794 mapLi_listEl[ linkID ].push_back( elem );
795 mapEl_setLi [ elem ].insert( linkID );
798 // Clean the maps from the links shared by a sole element, ie
799 // links to which only one element is bound in mapLi_listEl
801 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
803 int nbElems = (*itLE).second.size();
805 const SMDS_MeshElement* elem = (*itLE).second.front();
806 long link = (*itLE).first;
807 mapEl_setLi[ elem ].erase( link );
808 if ( mapEl_setLi[ elem ].empty() )
809 mapEl_setLi.erase( elem );
813 // Algo: fuse triangles into quadrangles
815 while ( ! mapEl_setLi.empty() )
817 // Look for the start element:
818 // the element having the least nb of shared links
820 const SMDS_MeshElement* startElem = 0;
822 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
824 int nbLinks = (*itEL).second.size();
825 if ( nbLinks < minNbLinks )
827 startElem = (*itEL).first;
828 minNbLinks = nbLinks;
829 if ( minNbLinks == 1 )
834 // search elements to fuse starting from startElem or links of elements
835 // fused earlyer - startLinks
836 list< long > startLinks;
837 while ( startElem || !startLinks.empty() )
839 while ( !startElem && !startLinks.empty() )
841 // Get an element to start, by a link
842 long linkId = startLinks.front();
843 startLinks.pop_front();
844 itLE = mapLi_listEl.find( linkId );
845 if ( itLE != mapLi_listEl.end() )
847 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
848 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
849 for ( ; itE != listElem.end() ; itE++ )
850 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
852 mapLi_listEl.erase( itLE );
858 // Get candidates to be fused
860 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
863 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
864 set< long >& setLi = mapEl_setLi[ tr1 ];
865 ASSERT( !setLi.empty() );
866 set< long >::iterator itLi;
867 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
869 long linkID = (*itLi);
870 itLE = mapLi_listEl.find( linkID );
871 if ( itLE == mapLi_listEl.end() )
873 const SMDS_MeshElement* elem = (*itLE).second.front();
875 elem = (*itLE).second.back();
876 mapLi_listEl.erase( itLE );
877 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
890 // add other links of elem to list of links to re-start from
891 set< long >& links = mapEl_setLi[ elem ];
892 set< long >::iterator it;
893 for ( it = links.begin(); it != links.end(); it++ )
895 long linkID2 = (*it);
896 if ( linkID2 != linkID )
897 startLinks.push_back( linkID2 );
901 // Get nodes of possible quadrangles
903 const SMDS_MeshNode *n12 [4], *n13 [4];
904 bool Ok12 = false, Ok13 = false;
905 const SMDS_MeshNode *linkNode1, *linkNode2;
907 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
908 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
911 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
912 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
915 // Choose a pair to fuse
919 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
920 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
921 double aBadRate12 = getBadRate( &quad12, theCrit );
922 double aBadRate13 = getBadRate( &quad13, theCrit );
923 if ( aBadRate13 < aBadRate12 )
931 // and remove fused elems and removed links from the maps
933 mapEl_setLi.erase( tr1 );
936 mapEl_setLi.erase( tr2 );
937 mapLi_listEl.erase( link12 );
938 aMesh->ChangeElementNodes( tr1, n12, 4 );
939 aMesh->RemoveElement( tr2 );
943 mapEl_setLi.erase( tr3 );
944 mapLi_listEl.erase( link13 );
945 aMesh->ChangeElementNodes( tr1, n13, 4 );
946 aMesh->RemoveElement( tr3 );
949 // Next element to fuse: the rejected one
951 startElem = Ok12 ? tr3 : tr2;
953 } // if ( startElem )
954 } // while ( startElem || !startLinks.empty() )
955 } // while ( ! mapEl_setLi.empty() )
961 #define DUMPSO(txt) \
962 // cout << txt << endl;
963 //=============================================================================
967 //=============================================================================
968 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
972 int tmp = idNodes[ i1 ];
973 idNodes[ i1 ] = idNodes[ i2 ];
975 gp_Pnt Ptmp = P[ i1 ];
978 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
981 //=======================================================================
982 //function : SortQuadNodes
983 //purpose : Set 4 nodes of a quadrangle face in a good order.
984 // Swap 1<->2 or 2<->3 nodes and correspondingly return
986 //=======================================================================
988 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
993 for ( i = 0; i < 4; i++ ) {
994 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
996 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
999 gp_Vec V1(P[0], P[1]);
1000 gp_Vec V2(P[0], P[2]);
1001 gp_Vec V3(P[0], P[3]);
1003 gp_Vec Cross1 = V1 ^ V2;
1004 gp_Vec Cross2 = V2 ^ V3;
1007 if (Cross1.Dot(Cross2) < 0)
1012 if (Cross1.Dot(Cross2) < 0)
1016 swap ( i, i + 1, idNodes, P );
1018 // for ( int ii = 0; ii < 4; ii++ ) {
1019 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1020 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1026 //=======================================================================
1027 //function : SortHexaNodes
1028 //purpose : Set 8 nodes of a hexahedron in a good order.
1029 // Return success status
1030 //=======================================================================
1032 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1037 DUMPSO( "INPUT: ========================================");
1038 for ( i = 0; i < 8; i++ ) {
1039 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1040 if ( !n ) return false;
1041 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1042 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1044 DUMPSO( "========================================");
1047 set<int> faceNodes; // ids of bottom face nodes, to be found
1048 set<int> checkedId1; // ids of tried 2-nd nodes
1049 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1050 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1051 int iMin, iLoop1 = 0;
1053 // Loop to try the 2-nd nodes
1055 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1057 // Find not checked 2-nd node
1058 for ( i = 1; i < 8; i++ )
1059 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1060 int id1 = idNodes[i];
1061 swap ( 1, i, idNodes, P );
1062 checkedId1.insert ( id1 );
1066 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1067 // ie that all but meybe one (id3 which is on the same face) nodes
1068 // lay on the same side from the triangle plane.
1070 bool manyInPlane = false; // more than 4 nodes lay in plane
1072 while ( ++iLoop2 < 6 ) {
1074 // get 1-2-3 plane coeffs
1075 Standard_Real A, B, C, D;
1076 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1077 if ( N.SquareMagnitude() > gp::Resolution() )
1079 gp_Pln pln ( P[0], N );
1080 pln.Coefficients( A, B, C, D );
1082 // find the node (iMin) closest to pln
1083 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1085 for ( i = 3; i < 8; i++ ) {
1086 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1087 if ( fabs( dist[i] ) < minDist ) {
1088 minDist = fabs( dist[i] );
1091 if ( fabs( dist[i] ) <= tol )
1092 idInPln.insert( idNodes[i] );
1095 // there should not be more than 4 nodes in bottom plane
1096 if ( idInPln.size() > 1 )
1098 DUMPSO( "### idInPln.size() = " << idInPln.size());
1099 // idInPlane does not contain the first 3 nodes
1100 if ( manyInPlane || idInPln.size() == 5)
1101 return false; // all nodes in one plane
1104 // set the 1-st node to be not in plane
1105 for ( i = 3; i < 8; i++ ) {
1106 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1107 DUMPSO( "### Reset 0-th node");
1108 swap( 0, i, idNodes, P );
1113 // reset to re-check second nodes
1114 leastDist = DBL_MAX;
1118 break; // from iLoop2;
1121 // check that the other 4 nodes are on the same side
1122 bool sameSide = true;
1123 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1124 for ( i = 3; sameSide && i < 8; i++ ) {
1126 sameSide = ( isNeg == dist[i] <= 0.);
1129 // keep best solution
1130 if ( sameSide && minDist < leastDist ) {
1131 leastDist = minDist;
1133 faceNodes.insert( idNodes[ 1 ] );
1134 faceNodes.insert( idNodes[ 2 ] );
1135 faceNodes.insert( idNodes[ iMin ] );
1136 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1137 << " leastDist = " << leastDist);
1138 if ( leastDist <= DBL_MIN )
1143 // set next 3-d node to check
1144 int iNext = 2 + iLoop2;
1146 DUMPSO( "Try 2-nd");
1147 swap ( 2, iNext, idNodes, P );
1149 } // while ( iLoop2 < 6 )
1152 if ( faceNodes.empty() ) return false;
1154 // Put the faceNodes in proper places
1155 for ( i = 4; i < 8; i++ ) {
1156 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1157 // find a place to put
1159 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1161 DUMPSO( "Set faceNodes");
1162 swap ( iTo, i, idNodes, P );
1167 // Set nodes of the found bottom face in good order
1168 DUMPSO( " Found bottom face: ");
1169 i = SortQuadNodes( theMesh, idNodes );
1171 gp_Pnt Ptmp = P[ i ];
1176 // for ( int ii = 0; ii < 4; ii++ ) {
1177 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1178 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1181 // Gravity center of the top and bottom faces
1182 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1183 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1185 // Get direction from the bottom to the top face
1186 gp_Vec upDir ( aGCb, aGCt );
1187 Standard_Real upDirSize = upDir.Magnitude();
1188 if ( upDirSize <= gp::Resolution() ) return false;
1191 // Assure that the bottom face normal points up
1192 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1193 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1194 if ( Nb.Dot( upDir ) < 0 ) {
1195 DUMPSO( "Reverse bottom face");
1196 swap( 1, 3, idNodes, P );
1199 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1200 Standard_Real minDist = DBL_MAX;
1201 for ( i = 4; i < 8; i++ ) {
1202 // projection of P[i] to the plane defined by P[0] and upDir
1203 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1204 Standard_Real sqDist = P[0].SquareDistance( Pp );
1205 if ( sqDist < minDist ) {
1210 DUMPSO( "Set 4-th");
1211 swap ( 4, iMin, idNodes, P );
1213 // Set nodes of the top face in good order
1214 DUMPSO( "Sort top face");
1215 i = SortQuadNodes( theMesh, &idNodes[4] );
1218 gp_Pnt Ptmp = P[ i ];
1223 // Assure that direction of the top face normal is from the bottom face
1224 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1225 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1226 if ( Nt.Dot( upDir ) < 0 ) {
1227 DUMPSO( "Reverse top face");
1228 swap( 5, 7, idNodes, P );
1231 // DUMPSO( "OUTPUT: ========================================");
1232 // for ( i = 0; i < 8; i++ ) {
1233 // float *p = ugrid->GetPoint(idNodes[i]);
1234 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1240 //=======================================================================
1241 //function : laplacianSmooth
1242 //purpose : pulls theNode toward the center of surrounding nodes directly
1243 // connected to that node along an element edge
1244 //=======================================================================
1246 void laplacianSmooth(SMESHDS_Mesh * theMesh,
1247 const SMDS_MeshNode* theNode,
1248 const set<const SMDS_MeshElement*> & theElems,
1249 const set<const SMDS_MeshNode*> & theFixedNodes)
1251 // find surrounding nodes
1252 set< const SMDS_MeshNode* > nodeSet;
1253 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1254 while ( elemIt->more() )
1256 const SMDS_MeshElement* elem = elemIt->next();
1257 if ( theElems.find( elem ) == theElems.end() )
1260 int i = 0, iNode = 0;
1261 const SMDS_MeshNode* aNodes [4];
1262 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1263 while ( itN->more() )
1265 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1266 if ( aNodes[ i ] == theNode )
1269 nodeSet.insert( aNodes[ i ] );
1272 if ( elem->NbNodes() == 4 ) { // remove an opposite node
1273 iNode += ( iNode < 2 ) ? 2 : -2;
1274 nodeSet.erase( aNodes[ iNode ]);
1278 // compute new coodrs
1279 double coord[] = { 0., 0., 0. };
1280 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1281 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1282 const SMDS_MeshNode* node = (*nodeSetIt);
1283 coord[0] += node->X();
1284 coord[1] += node->Y();
1285 coord[2] += node->Z();
1287 double nbNodes = nodeSet.size();
1288 theMesh->MoveNode (theNode,
1294 //=======================================================================
1295 //function : centroidalSmooth
1296 //purpose : pulls theNode toward the element-area-weighted centroid of the
1297 // surrounding elements
1298 //=======================================================================
1300 void centroidalSmooth(SMESHDS_Mesh * theMesh,
1301 const SMDS_MeshNode* theNode,
1302 const set<const SMDS_MeshElement*> & theElems,
1303 const set<const SMDS_MeshNode*> & theFixedNodes)
1305 gp_XYZ aNewXYZ(0.,0.,0.);
1306 SMESH::Controls::Area anAreaFunc;
1307 double totalArea = 0.;
1310 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1311 while ( elemIt->more() )
1313 const SMDS_MeshElement* elem = elemIt->next();
1314 if ( theElems.find( elem ) == theElems.end() )
1319 gp_XYZ elemCenter(0.,0.,0.);
1320 TSequenceOfXYZ aNodePoints;
1321 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1322 while ( itN->more() )
1324 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1325 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1326 aNodePoints.push_back( aP );
1329 double elemArea = anAreaFunc.GetValue( aNodePoints );
1330 totalArea += elemArea;
1331 elemCenter /= elem->NbNodes();
1332 aNewXYZ += elemCenter * elemArea;
1334 aNewXYZ /= totalArea;
1335 theMesh->MoveNode (theNode,
1341 //=======================================================================
1343 //purpose : Smooth theElements during theNbIterations or until a worst
1344 // element has aspect ratio <= theTgtAspectRatio.
1345 // Aspect Ratio varies in range [1.0, inf].
1346 // If theElements is empty, the whole mesh is smoothed.
1347 // theFixedNodes contains additionally fixed nodes. Nodes built
1348 // on edges and boundary nodes are always fixed.
1349 //=======================================================================
1351 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1352 set<const SMDS_MeshNode*> & theFixedNodes,
1353 const SmoothMethod theSmoothMethod,
1354 const int theNbIterations,
1355 double theTgtAspectRatio)
1357 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1359 SMESHDS_Mesh* aMesh = GetMeshDS();
1360 if ( theElems.empty() ) {
1362 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1363 while ( fIt->more() )
1364 theElems.insert( fIt->next() );
1367 set<const SMDS_MeshNode*> setMovableNodes;
1369 // Fill setMovableNodes
1371 map< const SMDS_MeshNode*, int > mapNodeNbFaces;
1372 set< const SMDS_MeshElement* >::iterator itElem;
1373 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1375 const SMDS_MeshElement* elem = (*itElem);
1376 if ( !elem || elem->GetType() != SMDSAbs_Face )
1379 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1380 while ( itN->more() ) {
1381 const SMDS_MeshNode* node =
1382 static_cast<const SMDS_MeshNode*>( itN->next() );
1384 if ( theFixedNodes.find( node ) != theFixedNodes.end() )
1387 // if node is on edge => it is fixed
1388 SMDS_PositionPtr aPositionPtr = node->GetPosition();
1389 if ( aPositionPtr.get() &&
1390 (aPositionPtr->GetTypeOfPosition() == SMDS_TOP_EDGE ||
1391 aPositionPtr->GetTypeOfPosition() == SMDS_TOP_VERTEX)) {
1392 theFixedNodes.insert( node );
1395 // fill mapNodeNbFaces in order to detect fixed boundary nodes
1396 map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1397 mapNodeNbFaces.find ( node );
1398 if ( nodeNbFacesIt == mapNodeNbFaces.end() )
1399 mapNodeNbFaces.insert( map<const SMDS_MeshNode*,int>::value_type( node, 1 ));
1401 (*nodeNbFacesIt).second++;
1404 // put not fixed nodes in setMovableNodes
1405 map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1406 mapNodeNbFaces.begin();
1407 for ( ; nodeNbFacesIt != mapNodeNbFaces.end(); nodeNbFacesIt++ ) {
1408 const SMDS_MeshNode* node = (*nodeNbFacesIt).first;
1409 // a node is on free boundary if it is shared by 1-2 faces
1410 if ( (*nodeNbFacesIt).second > 2 )
1411 setMovableNodes.insert( node );
1413 theFixedNodes.insert( node );
1418 if ( theTgtAspectRatio < 1.0 )
1419 theTgtAspectRatio = 1.0;
1421 SMESH::Controls::AspectRatio aQualityFunc;
1423 for ( int it = 0; it < theNbIterations; it++ )
1425 Standard_Real maxDisplacement = 0.;
1426 set<const SMDS_MeshNode*>::iterator movableNodesIt
1427 = setMovableNodes.begin();
1428 for ( ; movableNodesIt != setMovableNodes.end(); movableNodesIt++ )
1430 const SMDS_MeshNode* node = (*movableNodesIt);
1431 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1434 if ( theSmoothMethod == LAPLACIAN )
1435 laplacianSmooth( aMesh, node, theElems, theFixedNodes );
1437 centroidalSmooth( aMesh, node, theElems, theFixedNodes );
1440 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1441 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1442 if ( aDispl > maxDisplacement )
1443 maxDisplacement = aDispl;
1445 // no node movement => exit
1446 if ( maxDisplacement < 1.e-16 ) {
1447 MESSAGE("-- no node movement -- maxDisplacement: " << maxDisplacement << " it "<< it);
1451 // check elements quality
1452 double maxRatio = 0;
1453 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1455 const SMDS_MeshElement* elem = (*itElem);
1456 if ( !elem || elem->GetType() != SMDSAbs_Face )
1458 TSequenceOfXYZ aPoints;
1459 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1460 double aValue = aQualityFunc.GetValue( aPoints );
1461 if ( aValue > maxRatio )
1465 if ( maxRatio <= theTgtAspectRatio ) {
1466 MESSAGE("-- quality achived -- maxRatio " << maxRatio << " it "<< it);
1469 if (it+1 == theNbIterations) {
1470 MESSAGE("-- Iteration limit exceeded --");
1475 //=======================================================================
1476 //function : isReverse
1478 //=======================================================================
1480 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1481 const SMDS_MeshNode* nextNodes[],
1485 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1486 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1488 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1489 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1490 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1491 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1493 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1494 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1495 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1496 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1498 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1500 return (vA ^ vB) * vN < 0.0;
1503 //=======================================================================
1504 //function : sweepElement
1506 //=======================================================================
1508 static void sweepElement(SMESHDS_Mesh* aMesh,
1509 const SMDS_MeshElement* elem,
1510 const TNodeOfNodeListMap& mapNewNodes )
1512 // Loop on elem nodes:
1513 // find new nodes and detect same nodes indices
1514 list<const SMDS_MeshNode*>::const_iterator itNN[ 4 ];
1515 const SMDS_MeshNode* prevNod[ 4 ], *nextNod[ 4 ];
1516 int nbSame = 0, iNotSameNode = 0, iSameNode = 0;
1518 TNodeOfNodeListMap::const_iterator mapIt;
1520 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1521 while ( itN->more() )
1523 const SMDS_MeshNode* node =
1524 static_cast<const SMDS_MeshNode*>( itN->next() );
1525 mapIt = mapNewNodes.find( node );
1526 if ( mapIt == mapNewNodes.end() )
1527 return; // not duplicated node
1529 itNN[ iNode ] = (*mapIt).second.begin();
1530 prevNod[ iNode ] = node;
1531 nextNod[ iNode ] = (*mapIt).second.front();
1532 if ( prevNod[ iNode ] != nextNod [ iNode ])
1533 iNotSameNode = iNode;
1540 int nbNodes = 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->GetID() );
1560 int iAB = iAfterSame + iBeforeSame;
1561 iBeforeSame = iAB - iBeforeSame;
1562 iAfterSame = iAB - iAfterSame;
1566 // make new elements
1567 int iStep, nbSteps = (*mapIt).second.size();
1568 for (iStep = 0; iStep < nbSteps; iStep++ )
1571 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
1572 nextNod[ iNode ] = *itNN[ iNode ];
1580 aMesh->AddFace( prevNod[ 0 ], prevNod[ 1 ], nextNod[ 1 ], nextNod[ 0 ] );
1582 aMesh->AddFace( prevNod[ 0 ], prevNod[ 1 ], nextNod[ iNotSameNode ] );
1585 case 3: { // TRIANGLE
1587 if ( nbSame == 0 ) // --- 1 pentahedron
1589 aMesh->AddVolume (prevNod[ i2 ], prevNod[ 1 ], prevNod[ i0 ],
1590 nextNod[ i2 ], nextNod[ 1 ], nextNod[ i0 ] );
1592 else if ( nbSame == 1 ) // --- 2 tetrahedrons
1594 aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1595 nextNod[ iBeforeSame ]);
1596 aMesh->AddVolume (nextNod[ i2 ], nextNod[ 1 ], nextNod[ i0 ],
1597 prevNod[ iAfterSame ]);
1599 else // 2 same nodes: --- 1 tetrahedron
1601 aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1602 nextNod[ iNotSameNode ]);
1606 case 4: { // QUADRANGLE
1608 if ( nbSame == 0 ) // --- 1 hexahedron
1610 aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
1611 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
1613 else if ( nbSame == 1 ) // --- 2 tetrahedrons + 1 pentahedron
1615 aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iSameNode ],
1616 prevNod[ iAfterSame ], nextNod[ iBeforeSame ]);
1617 aMesh->AddVolume (nextNod[ iAfterSame ], nextNod[ iSameNode ],
1618 nextNod[ iBeforeSame ], prevNod[ iAfterSame ]);
1619 aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ], prevNod[ iAfterSame ],
1620 nextNod[ iBeforeSame ], nextNod[ iOpposSame ], nextNod[ iAfterSame ] );
1622 else if ( nbSame == 2 ) // 1 pentahedron
1624 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
1625 // iBeforeSame is same too
1626 aMesh->AddVolume (prevNod[ iOpposSame ], prevNod[ iBeforeSame ], nextNod[ iOpposSame ],
1627 prevNod[ iAfterSame ], prevNod[ iSameNode ], nextNod[ iAfterSame ]);
1629 // iAfterSame is same too
1630 aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iSameNode ], nextNod[ iBeforeSame ],
1631 prevNod[ iOpposSame ], prevNod[ iAfterSame ], nextNod[ iOpposSame ]);
1639 // set new prev nodes
1640 for ( iNode = 0; iNode < nbNodes; iNode++ )
1641 prevNod[ iNode ] = nextNod[ iNode ];
1646 //=======================================================================
1647 //function : RotationSweep
1649 //=======================================================================
1651 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
1652 const gp_Ax1& theAxis,
1653 const double theAngle,
1654 const int theNbSteps,
1655 const double theTol)
1658 aTrsf.SetRotation( theAxis, theAngle );
1660 gp_Lin aLine( theAxis );
1661 double aSqTol = theTol * theTol;
1663 SMESHDS_Mesh* aMesh = GetMeshDS();
1665 TNodeOfNodeListMap mapNewNodes;
1668 set< const SMDS_MeshElement* >::iterator itElem;
1669 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1671 // check element type
1672 const SMDS_MeshElement* elem = (*itElem);
1674 (elem->GetType() != SMDSAbs_Face &&
1675 elem->GetType() != SMDSAbs_Edge ))
1678 // loop on elem nodes
1679 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1680 while ( itN->more() ) {
1682 // check if a node has been already sweeped
1683 const SMDS_MeshNode* node =
1684 static_cast<const SMDS_MeshNode*>( itN->next() );
1685 if (mapNewNodes.find( node ) != mapNewNodes.end() )
1688 list<const SMDS_MeshNode*>& listNewNodes = mapNewNodes[ node ];
1691 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
1693 aXYZ.Coord( coord[0], coord[1], coord[2] );
1694 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
1695 const SMDS_MeshNode * newNode = node;
1696 for ( int i = 0; i < theNbSteps; i++ ) {
1698 aTrsf.Transforms( coord[0], coord[1], coord[2] );
1699 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1701 listNewNodes.push_back( newNode );
1704 // make new elements
1705 sweepElement( aMesh, elem, mapNewNodes );
1708 //=======================================================================
1709 //function : ExtrusionSweep
1711 //=======================================================================
1713 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
1714 const gp_Vec& theStep,
1715 const int theNbSteps)
1718 aTrsf.SetTranslation( theStep );
1720 SMESHDS_Mesh* aMesh = GetMeshDS();
1722 TNodeOfNodeListMap mapNewNodes;
1725 set< const SMDS_MeshElement* >::iterator itElem;
1726 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1728 // check element type
1729 const SMDS_MeshElement* elem = (*itElem);
1731 (elem->GetType() != SMDSAbs_Face &&
1732 elem->GetType() != SMDSAbs_Edge))
1735 // loop on elem nodes
1736 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1737 while ( itN->more() ) {
1739 // check if a node has been already sweeped
1740 const SMDS_MeshNode* node =
1741 static_cast<const SMDS_MeshNode*>( itN->next() );
1742 if (mapNewNodes.find( node ) != mapNewNodes.end() )
1745 list<const SMDS_MeshNode*>& listNewNodes = mapNewNodes[ node ];
1749 coord[0] = node->X();
1750 coord[1] = node->Y();
1751 coord[2] = node->Z();
1752 for ( int i = 0; i < theNbSteps; i++ ) {
1753 aTrsf.Transforms( coord[0], coord[1], coord[2] );
1754 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1755 listNewNodes.push_back( newNode );
1758 // make new elements
1759 sweepElement( aMesh, elem, mapNewNodes );
1763 //=======================================================================
1764 //function : Transform
1766 //=======================================================================
1768 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
1769 const gp_Trsf& theTrsf,
1773 switch ( theTrsf.Form() ) {
1779 needReverse = false;
1782 SMESHDS_Mesh* aMesh = GetMeshDS();
1784 // map old node to new one
1785 TNodeNodeMap nodeMap;
1787 // elements sharing moved nodes; those of them which have all
1788 // nodes mirrored but are not in theElems are to be reversed
1789 set<const SMDS_MeshElement*> inverseElemSet;
1792 set< const SMDS_MeshElement* >::iterator itElem;
1793 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1795 const SMDS_MeshElement* elem = (*itElem);
1799 // loop on elem nodes
1800 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1801 while ( itN->more() ) {
1803 // check if a node has been already transormed
1804 const SMDS_MeshNode* node =
1805 static_cast<const SMDS_MeshNode*>( itN->next() );
1806 if (nodeMap.find( node ) != nodeMap.end() )
1810 coord[0] = node->X();
1811 coord[1] = node->Y();
1812 coord[2] = node->Z();
1813 theTrsf.Transforms( coord[0], coord[1], coord[2] );
1814 const SMDS_MeshNode * newNode = node;
1816 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1818 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
1819 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
1821 // keep inverse elements
1822 if ( !theCopy && needReverse ) {
1823 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
1824 while ( invElemIt->more() )
1825 inverseElemSet.insert( invElemIt->next() );
1830 // either new elements are to be created
1831 // or a mirrored element are to be reversed
1832 if ( !theCopy && !needReverse)
1835 if ( !inverseElemSet.empty()) {
1836 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
1837 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
1838 theElems.insert( *invElemIt );
1841 // replicate or reverse elements
1844 REV_TETRA = 0, // = nbNodes - 4
1845 REV_PYRAMID = 1, // = nbNodes - 4
1846 REV_PENTA = 2, // = nbNodes - 4
1848 REV_HEXA = 4, // = nbNodes - 4
1852 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
1853 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
1854 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
1855 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
1856 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
1857 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
1860 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1862 const SMDS_MeshElement* elem = (*itElem);
1863 if ( !elem || elem->GetType() == SMDSAbs_Node )
1866 int nbNodes = elem->NbNodes();
1867 int elemType = elem->GetType();
1869 int* i = index[ FORWARD ];
1870 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
1871 if ( elemType == SMDSAbs_Face )
1872 i = index[ REV_FACE ];
1874 i = index[ nbNodes - 4 ];
1876 // find transformed nodes
1877 const SMDS_MeshNode* nodes[8];
1879 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1880 while ( itN->more() )
1882 const SMDS_MeshNode* node =
1883 static_cast<const SMDS_MeshNode*>( itN->next() );
1884 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
1885 if ( nodeMapIt == nodeMap.end() )
1886 break; // not all nodes transformed
1887 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
1889 if ( iNode != nbNodes )
1890 continue; // not all nodes transformed
1894 // add a new element
1895 switch ( elemType ) {
1897 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
1901 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
1903 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
1905 case SMDSAbs_Volume:
1907 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
1908 else if ( nbNodes == 8 )
1909 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
1910 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
1911 else if ( nbNodes == 6 )
1912 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
1913 nodes[ 4 ], nodes[ 5 ]);
1914 else if ( nbNodes == 5 )
1915 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
1923 // reverse element as it was reversed by transformation
1925 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
1930 //=======================================================================
1931 //function : FindCoincidentNodes
1932 //purpose : Return list of group of nodes close to each other within theTolerance
1933 //=======================================================================
1935 void SMESH_MeshEditor::FindCoincidentNodes (const double theTolerance,
1936 TListOfListOfNodes & theGroupsOfNodes)
1938 double tol2 = theTolerance * theTolerance;
1940 list<const SMDS_MeshNode*> nodes;
1941 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
1942 while ( nIt->more() )
1943 nodes.push_back( nIt->next() );
1945 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
1946 for ( ; it1 != nodes.end(); it1++ )
1948 const SMDS_MeshNode* n1 = *it1;
1949 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
1951 list<const SMDS_MeshNode*> * groupPtr = 0;
1953 for ( it2++; it2 != nodes.end(); it2++ )
1955 const SMDS_MeshNode* n2 = *it2;
1956 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
1957 if ( p1.SquareDistance( p2 ) <= tol2 )
1960 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
1961 groupPtr = & theGroupsOfNodes.back();
1962 groupPtr->push_back( n1 );
1964 groupPtr->push_back( n2 );
1965 it2 = nodes.erase( it2 );
1972 //=======================================================================
1973 //function : MergeNodes
1974 //purpose : In each group, the cdr of nodes are substituted by the first one
1976 //=======================================================================
1978 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
1980 SMESHDS_Mesh* aMesh = GetMeshDS();
1982 TNodeNodeMap nodeNodeMap; // node to replace - new node
1983 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
1984 list< int > rmElemIds, rmNodeIds;
1986 // Fill nodeNodeMap and elems
1988 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
1989 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
1991 list<const SMDS_MeshNode*>& nodes = *grIt;
1992 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
1993 const SMDS_MeshNode* nToKeep = *nIt;
1994 for ( ; nIt != nodes.end(); nIt++ )
1996 const SMDS_MeshNode* nToRemove = *nIt;
1997 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
1998 if ( nToRemove != nToKeep ) {
1999 rmNodeIds.push_back( nToRemove->GetID() );
2000 addToSameGroups( nToKeep, nToRemove, aMesh );
2003 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
2004 while ( invElemIt->more() )
2005 elems.insert( invElemIt->next() );
2008 // Change element nodes or remove an element
2010 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
2011 for ( ; eIt != elems.end(); eIt++ )
2013 const SMDS_MeshElement* elem = *eIt;
2014 int nbNodes = elem->NbNodes();
2015 int aShapeId = FindShape( elem );
2017 set<const SMDS_MeshNode*> nodeSet;
2018 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
2019 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
2021 // get new seq of nodes
2022 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2023 while ( itN->more() )
2025 const SMDS_MeshNode* n =
2026 static_cast<const SMDS_MeshNode*>( itN->next() );
2028 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
2029 if ( nnIt != nodeNodeMap.end() ) { // n sticks
2031 iRepl[ nbRepl++ ] = iCur;
2033 curNodes[ iCur ] = n;
2034 bool isUnique = nodeSet.insert( n ).second;
2036 uniqueNodes[ iUnique++ ] = n;
2040 // Analyse element topology after replacement
2043 int nbUniqueNodes = nodeSet.size();
2044 if ( nbNodes != nbUniqueNodes ) // some nodes stick
2046 switch ( nbNodes ) {
2047 case 2: ///////////////////////////////////// EDGE
2048 isOk = false; break;
2049 case 3: ///////////////////////////////////// TRIANGLE
2050 isOk = false; break;
2052 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
2054 else { //////////////////////////////////// QUADRANGLE
2055 if ( nbUniqueNodes < 3 )
2057 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
2058 isOk = false; // opposite nodes stick
2061 case 6: ///////////////////////////////////// PENTAHEDRON
2062 if ( nbUniqueNodes == 4 ) {
2063 // ---------------------------------> tetrahedron
2065 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
2066 // all top nodes stick: reverse a bottom
2067 uniqueNodes[ 0 ] = curNodes [ 1 ];
2068 uniqueNodes[ 1 ] = curNodes [ 0 ];
2070 else if (nbRepl == 3 &&
2071 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
2072 // all bottom nodes stick: set a top before
2073 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
2074 uniqueNodes[ 0 ] = curNodes [ 3 ];
2075 uniqueNodes[ 1 ] = curNodes [ 4 ];
2076 uniqueNodes[ 2 ] = curNodes [ 5 ];
2078 else if (nbRepl == 4 &&
2079 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
2080 // a lateral face turns into a line: reverse a bottom
2081 uniqueNodes[ 0 ] = curNodes [ 1 ];
2082 uniqueNodes[ 1 ] = curNodes [ 0 ];
2087 else if ( nbUniqueNodes == 5 ) {
2088 // PENTAHEDRON --------------------> 2 tetrahedrons
2089 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
2090 // a bottom node sticks with a linked top one
2092 SMDS_MeshElement* newElem =
2093 aMesh->AddVolume(curNodes[ 3 ],
2096 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
2098 aMesh->SetMeshElementOnShape( newElem, aShapeId );
2099 // 2. : reverse a bottom
2100 uniqueNodes[ 0 ] = curNodes [ 1 ];
2101 uniqueNodes[ 1 ] = curNodes [ 0 ];
2110 case 8: { //////////////////////////////////// HEXAHEDRON
2112 SMDS_VolumeTool hexa (elem);
2113 hexa.SetExternalNormal();
2114 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
2115 //////////////////////// ---> tetrahedron
2116 for ( int iFace = 0; iFace < 6; iFace++ ) {
2117 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2118 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2119 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2120 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2121 // one face turns into a point ...
2122 int iOppFace = hexa.GetOppFaceIndex( iFace );
2123 ind = hexa.GetFaceNodesIndices( iOppFace );
2125 iUnique = 2; // reverse a tetrahedron bottom
2126 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
2127 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2129 else if ( iUnique >= 0 )
2130 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2132 if ( nbStick == 1 ) {
2133 // ... and the opposite one - into a triangle.
2135 ind = hexa.GetFaceNodesIndices( iFace );
2136 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
2143 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
2144 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
2145 for ( int iFace = 0; iFace < 6; iFace++ ) {
2146 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2147 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2148 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2149 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2150 // one face turns into a point ...
2151 int iOppFace = hexa.GetOppFaceIndex( iFace );
2152 ind = hexa.GetFaceNodesIndices( iOppFace );
2154 iUnique = 2; // reverse a tetrahedron 1 bottom
2155 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
2156 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2158 else if ( iUnique >= 0 )
2159 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2161 if ( nbStick == 0 ) {
2162 // ... and the opposite one is a quadrangle
2164 const int* indTop = hexa.GetFaceNodesIndices( iFace );
2165 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
2168 SMDS_MeshElement* newElem =
2169 aMesh->AddVolume(curNodes[ind[ 0 ]],
2172 curNodes[indTop[ 0 ]]);
2174 aMesh->SetMeshElementOnShape( newElem, aShapeId );
2181 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
2182 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
2183 // find indices of quad and tri faces
2184 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
2185 for ( iFace = 0; iFace < 6; iFace++ ) {
2186 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2188 for ( iCur = 0; iCur < 4; iCur++ )
2189 nodeSet.insert( curNodes[ind[ iCur ]] );
2190 nbUniqueNodes = nodeSet.size();
2191 if ( nbUniqueNodes == 3 )
2192 iTriFace[ nbTri++ ] = iFace;
2193 else if ( nbUniqueNodes == 4 )
2194 iQuadFace[ nbQuad++ ] = iFace;
2196 if (nbQuad == 2 && nbTri == 4 &&
2197 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
2198 // 2 opposite quadrangles stuck with a diagonal;
2199 // sample groups of merged indices: (0-4)(2-6)
2200 // --------------------------------------------> 2 tetrahedrons
2201 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
2202 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
2203 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
2204 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
2205 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
2206 // stuck with 0-2 diagonal
2214 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
2215 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
2216 // stuck with 1-3 diagonal
2228 uniqueNodes[ 0 ] = curNodes [ i0 ];
2229 uniqueNodes[ 1 ] = curNodes [ i1d ];
2230 uniqueNodes[ 2 ] = curNodes [ i3d ];
2231 uniqueNodes[ 3 ] = curNodes [ i0t ];
2234 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
2239 aMesh->SetMeshElementOnShape( newElem, aShapeId );
2242 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
2243 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
2244 // --------------------------------------------> prism
2245 // find 2 opposite triangles
2247 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
2248 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
2249 // find indices of kept and replaced nodes
2250 // and fill unique nodes of 2 opposite triangles
2251 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
2252 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
2253 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
2254 // fill unique nodes
2257 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
2258 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
2259 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
2261 // iCur of a linked node of the opposite face (make normals co-directed):
2262 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
2263 // check that correspondent corners of triangles are linked
2264 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
2267 uniqueNodes[ iUnique ] = n;
2268 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
2277 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
2283 } // switch ( nbNodes )
2285 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
2288 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
2290 rmElemIds.push_back( elem->GetID() );
2292 } // loop on elements
2294 // Remove equal nodes and bad elements
2296 Remove( rmNodeIds, true );
2297 Remove( rmElemIds, false );
2301 //=======================================================================
2302 //function : MergeEqualElements
2303 //purpose : Remove all but one of elements built on the same nodes.
2304 //=======================================================================
2306 void SMESH_MeshEditor::MergeEqualElements()
2308 SMESHDS_Mesh* aMesh = GetMeshDS();
2310 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
2311 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
2312 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
2314 list< int > rmElemIds; // IDs of elems to remove
2316 for ( int iDim = 1; iDim <= 3; iDim++ ) {
2318 set< set <const SMDS_MeshElement*> > setOfNodeSet;
2322 const SMDS_MeshElement* elem = 0;
2324 if ( eIt->more() ) elem = eIt->next();
2325 } else if ( iDim == 2 ) {
2326 if ( fIt->more() ) elem = fIt->next();
2328 if ( vIt->more() ) elem = vIt->next();
2333 set <const SMDS_MeshElement*> nodeSet;
2334 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
2335 while ( nodeIt->more() )
2336 nodeSet.insert( nodeIt->next() );
2339 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
2341 rmElemIds.push_back( elem->GetID() );
2345 Remove( rmElemIds, false );
2348 //=======================================================================
2349 //function : findAdjacentFace
2351 //=======================================================================
2352 #define CHECKIND(max,val) {if ( (val) >= (max) ) \
2354 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
2355 const SMDS_MeshNode* n2,
2356 const SMDS_MeshElement* elem)
2358 SMDS_ElemIteratorPtr invElemIt = n1->facesIterator();
2359 while ( invElemIt->more() ) { // loop on inverse elements of n1
2360 const SMDS_MeshElement* adjElem = invElemIt->next();
2361 if ( elem != adjElem ) {
2362 // get face nodes and find index of n1
2363 int i1, nbN = adjElem->NbNodes(), iNode = 0;
2364 const SMDS_MeshNode* faceNodes[ nbN ], *n;
2365 SMDS_ElemIteratorPtr nIt = adjElem->nodesIterator();
2366 while ( nIt->more() ) {
2367 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2368 if ( faceNodes[ iNode++ ] == n1 )
2371 // find a n2 linked to n1
2372 for ( iNode = 0; iNode < 2; iNode++ ) {
2373 if ( iNode ) // node before n1
2374 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
2375 else // node after n1
2376 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
2385 //=======================================================================
2386 //function : findFreeBorder
2388 //=======================================================================
2390 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
2392 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
2393 const SMDS_MeshNode* theSecondNode,
2394 const SMDS_MeshNode* theLastNode,
2395 list< const SMDS_MeshNode* > & theNodes,
2396 list< const SMDS_MeshElement* > & theFaces)
2398 if ( !theFirstNode || !theSecondNode )
2400 // find border face between theFirstNode and theSecondNode
2401 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
2405 theFaces.push_back( curElem );
2406 theNodes.push_back( theFirstNode );
2407 theNodes.push_back( theSecondNode );
2409 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
2410 set < const SMDS_MeshElement* > foundElems;
2411 bool needTheLast = ( theLastNode != 0 );
2413 while ( nStart != theLastNode )
2415 if ( nStart == theFirstNode )
2416 return !needTheLast;
2418 // find all free border faces sharing form nStart
2420 list< const SMDS_MeshElement* > curElemList;
2421 list< const SMDS_MeshNode* > nStartList;
2422 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
2423 while ( invElemIt->more() ) {
2424 const SMDS_MeshElement* e = invElemIt->next();
2425 if ( e == curElem || foundElems.insert( e ).second )
2428 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2429 int iNode = 0, nbNodes = e->NbNodes();
2430 while ( nIt->more() )
2431 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2432 nodes[ iNode ] = nodes[ 0 ];
2434 for ( iNode = 0; iNode < nbNodes; iNode++ )
2435 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
2436 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
2437 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
2439 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
2440 curElemList.push_back( e );
2444 // analyse the found
2446 int nbNewBorders = curElemList.size();
2447 if ( nbNewBorders == 0 ) {
2448 // no free border furthermore
2449 return !needTheLast;
2451 else if ( nbNewBorders == 1 ) {
2452 // one more element found
2454 nStart = nStartList.front();
2455 curElem = curElemList.front();
2456 theFaces.push_back( curElem );
2457 theNodes.push_back( nStart );
2460 // several continuations found
2461 list< const SMDS_MeshElement* >::iterator curElemIt;
2462 list< const SMDS_MeshNode* >::iterator nStartIt;
2463 // check if one of them reached the last node
2464 if ( needTheLast ) {
2465 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
2466 curElemIt!= curElemList.end();
2467 curElemIt++, nStartIt++ )
2468 if ( *nStartIt == theLastNode ) {
2469 theFaces.push_back( *curElemIt );
2470 theNodes.push_back( *nStartIt );
2474 // find the best free border by the continuations
2475 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
2476 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
2477 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
2478 curElemIt!= curElemList.end();
2479 curElemIt++, nStartIt++ )
2481 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
2482 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
2483 // find one more free border
2484 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
2488 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
2489 // choice: clear a worse one
2490 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
2491 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
2492 contNodes[ iWorse ].clear();
2493 contFaces[ iWorse ].clear();
2496 if ( contNodes[0].empty() && contNodes[1].empty() )
2499 // append the best free border
2500 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
2501 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
2502 theNodes.pop_back(); // remove nIgnore
2503 theNodes.pop_back(); // remove nStart
2504 theFaces.pop_back(); // remove curElem
2505 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
2506 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
2507 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
2508 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
2511 } // several continuations found
2512 } // while ( nStart != theLastNode )
2517 //=======================================================================
2518 //function : CheckFreeBorderNodes
2519 //purpose : Return true if the tree nodes are on a free border
2520 //=======================================================================
2522 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
2523 const SMDS_MeshNode* theNode2,
2524 const SMDS_MeshNode* theNode3)
2526 list< const SMDS_MeshNode* > nodes;
2527 list< const SMDS_MeshElement* > faces;
2528 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
2531 //=======================================================================
2532 //function : SewFreeBorder
2534 //=======================================================================
2536 SMESH_MeshEditor::Sew_Error
2537 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
2538 const SMDS_MeshNode* theBordSecondNode,
2539 const SMDS_MeshNode* theBordLastNode,
2540 const SMDS_MeshNode* theSideFirstNode,
2541 const SMDS_MeshNode* theSideSecondNode,
2542 const SMDS_MeshNode* theSideThirdNode,
2543 bool theSideIsFreeBorder)
2545 MESSAGE("::SewFreeBorder()");
2546 Sew_Error aResult = SEW_OK;
2548 // ====================================
2549 // find side nodes and elements
2550 // ====================================
2552 list< const SMDS_MeshNode* > nSide[ 2 ];
2553 list< const SMDS_MeshElement* > eSide[ 2 ];
2554 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
2555 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
2559 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
2560 nSide[0], eSide[0])) {
2561 MESSAGE(" Free Border 1 not found " );
2562 aResult = SEW_BORDER1_NOT_FOUND;
2564 if (theSideIsFreeBorder)
2568 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
2569 nSide[1], eSide[1])) {
2570 MESSAGE(" Free Border 2 not found " );
2571 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
2574 if ( aResult != SEW_OK )
2577 if (!theSideIsFreeBorder)
2582 // -------------------------------------------------------------------------
2584 // 1. If nodes to merge are not coincident, move nodes of the free border
2585 // from the coord sys defined by the direction from the first to last
2586 // nodes of the border to the correspondent sys of the side 2
2587 // 2. On the side 2, find the links most co-directed with the correspondent
2588 // links of the free border
2589 // -------------------------------------------------------------------------
2591 // 1. Since sewing may brake if there are volumes to split on the side 2,
2592 // we wont move nodes but just compute new coordinates for them
2593 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
2594 TNodeXYZMap nBordXYZ;
2595 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
2596 list< const SMDS_MeshNode* >::iterator nBordIt;
2598 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
2599 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
2600 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
2601 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
2602 double tol2 = 1.e-8;
2603 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
2604 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
2606 // Need node movement.
2608 // find X and Z axes to create trsf
2609 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
2611 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
2613 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
2616 gp_Ax3 toBordAx( Pb1, Zb, X );
2617 gp_Ax3 fromSideAx( Ps1, Zs, X );
2618 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
2620 gp_Trsf toBordSys, fromSide2Sys;
2621 toBordSys.SetTransformation( toBordAx );
2622 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
2623 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
2626 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
2627 const SMDS_MeshNode* n = *nBordIt;
2628 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
2629 toBordSys.Transforms( xyz );
2630 fromSide2Sys.Transforms( xyz );
2631 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
2636 // just insert nodes XYZ in the nBordXYZ map
2637 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
2638 const SMDS_MeshNode* n = *nBordIt;
2639 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
2643 // 2. On the side 2, find the links most co-directed with the correspondent
2644 // links of the free border
2646 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
2647 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
2648 sideNodes.push_back( theSideFirstNode );
2650 bool hasVolumes = false;
2651 LinkID_Gen aLinkID_Gen( GetMeshDS() );
2652 set<long> foundSideLinkIDs, checkedLinkIDs;
2653 SMDS_VolumeTool volume;
2654 const SMDS_MeshNode* faceNodes[ 4 ];
2656 const SMDS_MeshNode* sideNode;
2657 const SMDS_MeshElement* sideElem;
2658 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
2659 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
2660 nBordIt = bordNodes.begin();
2662 // border node position and border link direction to compare with
2663 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
2664 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
2665 // choose next side node by link direction or by closeness to
2666 // the current border node:
2667 bool searchByDir = ( *nBordIt != theBordLastNode );
2669 // find the next node on the Side 2
2671 double maxDot = -DBL_MAX, minDist = DBL_MAX;
2673 checkedLinkIDs.clear();
2674 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
2676 SMDS_ElemIteratorPtr invElemIt
2677 = prevSideNode->GetInverseElementIterator();
2678 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
2679 const SMDS_MeshElement* elem = invElemIt->next();
2680 // prepare data for a loop on links, of a face or a volume
2681 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
2682 bool isVolume = volume.Set( elem );
2683 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
2684 if ( isVolume ) // --volume
2686 else if ( nbNodes > 2 ) { // --face
2687 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
2688 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2689 while ( nIt->more() ) {
2690 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2691 if ( nodes[ iNode++ ] == prevSideNode )
2692 iPrevNode = iNode - 1;
2694 // there are 2 links to check
2699 // loop on links, to be precise, on the second node of links
2700 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2701 const SMDS_MeshNode* n = nodes[ iNode ];
2703 if ( !volume.IsLinked( n, prevSideNode ))
2706 if ( iNode ) // a node before prevSideNode
2707 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
2708 else // a node after prevSideNode
2709 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
2711 // check if this link was already used
2712 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
2713 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
2714 if (!isJustChecked &&
2715 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
2716 // test a link geometrically
2717 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
2718 bool linkIsBetter = false;
2720 if ( searchByDir ) { // choose most co-directed link
2721 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
2722 linkIsBetter = ( dot > maxDot );
2724 else { // choose link with the node closest to bordPos
2725 dist = ( nextXYZ - bordPos ).SquareModulus();
2726 linkIsBetter = ( dist < minDist );
2728 if ( linkIsBetter ) {
2737 } // loop on inverse elements of prevSideNode
2740 MESSAGE(" Cant find path by links of the Side 2 ");
2741 return SEW_BAD_SIDE_NODES;
2743 sideNodes.push_back( sideNode );
2744 sideElems.push_back( sideElem );
2745 foundSideLinkIDs.insert ( linkID );
2746 prevSideNode = sideNode;
2748 if ( *nBordIt == theBordLastNode )
2749 searchByDir = false;
2751 // find the next border link to compare with
2752 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
2753 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
2754 while ( *nBordIt != theBordLastNode && !searchByDir ) {
2755 prevBordNode = *nBordIt;
2757 bordPos = nBordXYZ[ *nBordIt ];
2758 bordDir = bordPos - nBordXYZ[ prevBordNode ];
2759 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
2763 while ( sideNode != theSideSecondNode );
2765 if ( hasVolumes && sideNodes.size () != bordNodes.size() ) {
2766 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
2767 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
2769 } // end nodes search on the side 2
2771 // ============================
2772 // sew the border to the side 2
2773 // ============================
2775 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
2776 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
2778 TListOfListOfNodes nodeGroupsToMerge;
2779 if ( nbNodes[0] == nbNodes[1] ||
2780 ( theSideIsFreeBorder && !theSideThirdNode)) {
2782 // all nodes are to be merged
2784 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
2785 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
2786 nIt[0]++, nIt[1]++ )
2788 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
2789 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
2790 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
2795 // insert new nodes into the border and the side to get equal nb of segments
2797 // get normalized parameters of nodes on the borders
2798 double param[ 2 ][ maxNbNodes ];
2800 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
2801 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
2802 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
2803 const SMDS_MeshNode* nPrev = *nIt;
2804 double bordLength = 0;
2805 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
2806 const SMDS_MeshNode* nCur = *nIt;
2807 gp_XYZ segment (nCur->X() - nPrev->X(),
2808 nCur->Y() - nPrev->Y(),
2809 nCur->Z() - nPrev->Z());
2810 double segmentLen = segment.Modulus();
2811 bordLength += segmentLen;
2812 param[ iBord ][ iNode ] = bordLength;
2815 // normalize within [0,1]
2816 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
2817 param[ iBord ][ iNode ] /= bordLength;
2821 // loop on border segments
2822 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
2823 int i[ 2 ] = { 0, 0 };
2824 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
2825 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
2827 TElemOfNodeListMap insertMap;
2828 TElemOfNodeListMap::iterator insertMapIt;
2830 // key: elem to insert nodes into
2831 // value: 2 nodes to insert between + nodes to be inserted
2833 bool next[ 2 ] = { false, false };
2835 // find min adjacent segment length after sewing
2836 double nextParam = 10., prevParam = 0;
2837 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
2838 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
2839 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
2840 if ( i[ iBord ] > 0 )
2841 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
2843 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
2844 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
2845 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
2847 // choose to insert or to merge nodes
2848 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
2849 if ( Abs( du ) <= minSegLen * 0.2 ) {
2852 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
2853 const SMDS_MeshNode* n0 = *nIt[0];
2854 const SMDS_MeshNode* n1 = *nIt[1];
2855 nodeGroupsToMerge.back().push_back( n1 );
2856 nodeGroupsToMerge.back().push_back( n0 );
2857 // position of node of the border changes due to merge
2858 param[ 0 ][ i[0] ] += du;
2859 // move n1 for the sake of elem shape evaluation during insertion.
2860 // n1 will be removed by MergeNodes() anyway
2861 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
2862 next[0] = next[1] = true;
2867 int intoBord = ( du < 0 ) ? 0 : 1;
2868 const SMDS_MeshElement* elem = *eIt[ intoBord ];
2869 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
2870 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
2871 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
2872 if ( intoBord == 1 ) {
2873 // move node of the border to be on a link of elem of the side
2874 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
2875 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
2876 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
2877 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
2878 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
2880 insertMapIt = insertMap.find( elem );
2881 bool notFound = ( insertMapIt == insertMap.end() );
2882 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
2884 // insert into another link of the same element:
2885 // 1. perform insertion into the other link of the elem
2886 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
2887 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
2888 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
2889 InsertNodesIntoLink( elem, n12, n22, nodeList );
2890 // 2. perform insertion into the link of adjacent faces
2892 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
2894 InsertNodesIntoLink( adjElem, n12, n22, nodeList );
2898 // 3. find an element appeared on n1 and n2 after the insertion
2899 insertMap.erase( elem );
2900 elem = findAdjacentFace( n1, n2, 0 );
2902 if ( notFound || otherLink ) {
2903 // add element and nodes of the side into the insertMap
2904 insertMapIt = insertMap.insert
2905 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
2906 (*insertMapIt).second.push_back( n1 );
2907 (*insertMapIt).second.push_back( n2 );
2909 // add node to be inserted into elem
2910 (*insertMapIt).second.push_back( nIns );
2911 next[ 1 - intoBord ] = true;
2914 // go to the next segment
2915 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
2916 if ( next[ iBord ] ) {
2917 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
2919 nPrev[ iBord ] = *nIt[ iBord ];
2920 nIt[ iBord ]++; i[ iBord ]++;
2924 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
2926 // perform insertion of nodes into elements
2928 for (insertMapIt = insertMap.begin();
2929 insertMapIt != insertMap.end();
2932 const SMDS_MeshElement* elem = (*insertMapIt).first;
2933 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
2934 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
2935 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
2937 InsertNodesIntoLink( elem, n1, n2, nodeList );
2939 if ( !theSideIsFreeBorder ) {
2940 // look for and insert nodes into the faces adjacent to elem
2942 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
2944 InsertNodesIntoLink( adjElem, n1, n2, nodeList );
2951 } // end: insert new nodes
2953 MergeNodes ( nodeGroupsToMerge );
2958 //=======================================================================
2959 //function : InsertNodesIntoLink
2960 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
2961 // and theBetweenNode2 and split theElement
2962 //=======================================================================
2964 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
2965 const SMDS_MeshNode* theBetweenNode1,
2966 const SMDS_MeshNode* theBetweenNode2,
2967 list<const SMDS_MeshNode*>& theNodesToInsert)
2969 if ( theFace->GetType() != SMDSAbs_Face ) return;
2971 // find indices of 2 link nodes and of the rest nodes
2972 int iNode = 0, il1, il2, i3, i4;
2973 il1 = il2 = i3 = i4 = -1;
2974 const SMDS_MeshNode* nodes[ 8 ];
2975 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
2976 while ( nodeIt->more() ) {
2977 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
2978 if ( n == theBetweenNode1 )
2980 else if ( n == theBetweenNode2 )
2986 nodes[ iNode++ ] = n;
2988 if ( il1 < 0 || il2 < 0 || i3 < 0 )
2991 // arrange link nodes to go one after another regarding the face orientation
2992 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
2997 theNodesToInsert.reverse();
2999 // check that not link nodes of a quadrangles are in good order
3000 int nbFaceNodes = theFace->NbNodes();
3001 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
3007 // put theNodesToInsert between theBetweenNode1 and theBetweenNode2
3008 int nbLinkNodes = 2 + theNodesToInsert.size();
3009 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
3010 linkNodes[ 0 ] = nodes[ il1 ];
3011 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
3012 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
3013 for ( iNode = 1; nIt != theNodesToInsert.end(); nIt++ ) {
3014 linkNodes[ iNode++ ] = *nIt;
3016 // decide how to split a quadrangle: compare possible variants
3017 // and choose which of splits to be a quadrangle
3018 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
3019 if ( nbFaceNodes == 3 )
3021 iBestQuad = nbSplits;
3024 else if ( nbFaceNodes == 4 )
3026 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
3027 double aBestRate = DBL_MAX;
3028 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
3030 double aBadRate = 0;
3031 // evaluate elements quality
3032 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
3033 if ( iSplit == iQuad ) {
3034 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
3038 aBadRate += getBadRate( &quad, aCrit );
3041 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
3043 nodes[ iSplit < iQuad ? i4 : i3 ]);
3044 aBadRate += getBadRate( &tria, aCrit );
3048 if ( aBadRate < aBestRate ) {
3050 aBestRate = aBadRate;
3055 // create new elements
3056 SMESHDS_Mesh *aMesh = GetMeshDS();
3057 int aShapeId = FindShape( theFace );
3060 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
3061 SMDS_MeshElement* newElem = 0;
3062 if ( iSplit == iBestQuad )
3063 newElem = aMesh->AddFace (linkNodes[ i1++ ],
3068 newElem = aMesh->AddFace (linkNodes[ i1++ ],
3070 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
3071 if ( aShapeId && newElem )
3072 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3075 // change nodes of theFace
3076 const SMDS_MeshNode* newNodes[ 4 ];
3077 newNodes[ 0 ] = linkNodes[ i1 ];
3078 newNodes[ 1 ] = linkNodes[ i2 ];
3079 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
3080 newNodes[ 3 ] = nodes[ i4 ];
3081 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
3084 //=======================================================================
3085 //function : SewSideElements
3087 //=======================================================================
3089 SMESH_MeshEditor::Sew_Error
3090 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
3091 set<const SMDS_MeshElement*>& theSide2,
3092 const SMDS_MeshNode* theFirstNode1,
3093 const SMDS_MeshNode* theFirstNode2,
3094 const SMDS_MeshNode* theSecondNode1,
3095 const SMDS_MeshNode* theSecondNode2)
3097 MESSAGE ("::::SewSideElements()");
3098 if ( theSide1.size() != theSide2.size() )
3099 return SEW_DIFF_NB_OF_ELEMENTS;
3101 Sew_Error aResult = SEW_OK;
3103 // 1. Build set of faces representing each side
3104 // 2. Find which nodes of the side 1 to merge with ones on the side 2
3105 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
3107 // =======================================================================
3108 // 1. Build set of faces representing each side:
3109 // =======================================================================
3110 // a. build set of nodes belonging to faces
3111 // b. complete set of faces: find missing fices whose nodes are in set of nodes
3112 // c. create temporary faces representing side of volumes if correspondent
3113 // face does not exist
3115 SMESHDS_Mesh* aMesh = GetMeshDS();
3116 SMDS_Mesh aTmpFacesMesh;
3117 set<const SMDS_MeshElement*> faceSet1, faceSet2;
3118 set<const SMDS_MeshElement*> volSet1, volSet2;
3119 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
3120 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
3121 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
3122 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
3123 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
3124 int iSide, iFace, iNode;
3126 for ( iSide = 0; iSide < 2; iSide++ ) {
3127 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
3128 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
3129 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3130 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
3131 set<const SMDS_MeshElement*>::iterator vIt, eIt;
3132 set<const SMDS_MeshNode*>::iterator nIt;
3134 // -----------------------------------------------------------
3135 // 1a. Collect nodes of existing faces
3136 // and build set of face nodes in order to detect missing
3137 // faces corresponing to sides of volumes
3138 // -----------------------------------------------------------
3140 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
3142 // loop on the given element of a side
3143 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
3144 const SMDS_MeshElement* elem = *eIt;
3145 if ( elem->GetType() == SMDSAbs_Face ) {
3146 faceSet->insert( elem );
3147 set <const SMDS_MeshNode*> faceNodeSet;
3148 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3149 while ( nodeIt->more() ) {
3150 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3151 nodeSet->insert( n );
3152 faceNodeSet.insert( n );
3154 setOfFaceNodeSet.insert( faceNodeSet );
3156 else if ( elem->GetType() == SMDSAbs_Volume )
3157 volSet->insert( elem );
3159 // ------------------------------------------------------------------------------
3160 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
3161 // ------------------------------------------------------------------------------
3163 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3164 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3165 while ( fIt->more() ) { // loop on faces sharing a node
3166 const SMDS_MeshElement* f = fIt->next();
3167 if ( faceSet->find( f ) == faceSet->end() ) {
3168 // check if all nodes are in nodeSet and
3169 // complete setOfFaceNodeSet if they are
3170 set <const SMDS_MeshNode*> faceNodeSet;
3171 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3172 bool allInSet = true;
3173 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3174 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3175 if ( nodeSet->find( n ) == nodeSet->end() )
3178 faceNodeSet.insert( n );
3181 faceSet->insert( f );
3182 setOfFaceNodeSet.insert( faceNodeSet );
3188 // -------------------------------------------------------------------------
3189 // 1c. Create temporary faces representing sides of volumes if correspondent
3190 // face does not exist
3191 // -------------------------------------------------------------------------
3193 if ( !volSet->empty() )
3195 //int nodeSetSize = nodeSet->size();
3197 // loop on given volumes
3198 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
3199 SMDS_VolumeTool vol (*vIt);
3200 // loop on volume faces: find free faces
3201 // --------------------------------------
3202 list<const SMDS_MeshElement* > freeFaceList;
3203 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
3204 if ( !vol.IsFreeFace( iFace ))
3206 // check if there is already a face with same nodes in a face set
3207 const SMDS_MeshElement* aFreeFace = 0;
3208 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
3209 int nbNodes = vol.NbFaceNodes( iFace );
3210 set <const SMDS_MeshNode*> faceNodeSet;
3211 vol.GetFaceNodes( iFace, faceNodeSet );
3212 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
3214 // no such a face is given but it still can exist, check it
3216 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
3218 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3221 // create a temporary face
3223 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
3225 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3228 freeFaceList.push_back( aFreeFace );
3230 } // loop on faces of a volume
3232 // choose one of several free faces
3233 // --------------------------------------
3234 if ( freeFaceList.size() > 1 ) {
3235 // choose a face having max nb of nodes shared by other elems of a side
3236 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
3237 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
3238 while ( fIt != freeFaceList.end() ) { // loop on free faces
3239 int nbSharedNodes = 0;
3240 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3241 while ( nodeIt->more() ) { // loop on free face nodes
3242 const SMDS_MeshNode* n =
3243 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3244 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
3245 while ( invElemIt->more() ) {
3246 const SMDS_MeshElement* e = invElemIt->next();
3247 if ( faceSet->find( e ) != faceSet->end() )
3249 if ( elemSet->find( e ) != elemSet->end() )
3253 if ( nbSharedNodes >= maxNbNodes ) {
3254 maxNbNodes = nbSharedNodes;
3258 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
3260 if ( freeFaceList.size() > 1 )
3262 // could not choose one face, use another way
3263 // choose a face most close to the bary center of the opposite side
3264 gp_XYZ aBC( 0., 0., 0. );
3265 set <const SMDS_MeshNode*> addedNodes;
3266 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
3267 eIt = elemSet2->begin();
3268 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
3269 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
3270 while ( nodeIt->more() ) { // loop on free face nodes
3271 const SMDS_MeshNode* n =
3272 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3273 if ( addedNodes.insert( n ).second )
3274 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
3277 aBC /= addedNodes.size();
3278 double minDist = DBL_MAX;
3279 fIt = freeFaceList.begin();
3280 while ( fIt != freeFaceList.end() ) { // loop on free faces
3282 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3283 while ( nodeIt->more() ) { // loop on free face nodes
3284 const SMDS_MeshNode* n =
3285 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3286 gp_XYZ p( n->X(),n->Y(),n->Z() );
3287 dist += ( aBC - p ).SquareModulus();
3289 if ( dist < minDist ) {
3291 freeFaceList.erase( freeFaceList.begin(), fIt++ );
3294 fIt = freeFaceList.erase( fIt++ );
3297 } // choose one of several free faces of a volume
3299 if ( freeFaceList.size() == 1 ) {
3300 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
3301 faceSet->insert( aFreeFace );
3302 // complete a node set with nodes of a found free face
3303 // for ( iNode = 0; iNode < ; iNode++ )
3304 // nodeSet->insert( fNodes[ iNode ] );
3307 } // loop on volumes of a side
3309 // // complete a set of faces if new nodes in a nodeSet appeared
3310 // // ----------------------------------------------------------
3311 // if ( nodeSetSize != nodeSet->size() ) {
3312 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3313 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3314 // while ( fIt->more() ) { // loop on faces sharing a node
3315 // const SMDS_MeshElement* f = fIt->next();
3316 // if ( faceSet->find( f ) == faceSet->end() ) {
3317 // // check if all nodes are in nodeSet and
3318 // // complete setOfFaceNodeSet if they are
3319 // set <const SMDS_MeshNode*> faceNodeSet;
3320 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3321 // bool allInSet = true;
3322 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3323 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3324 // if ( nodeSet->find( n ) == nodeSet->end() )
3325 // allInSet = false;
3327 // faceNodeSet.insert( n );
3329 // if ( allInSet ) {
3330 // faceSet->insert( f );
3331 // setOfFaceNodeSet.insert( faceNodeSet );
3337 } // Create temporary faces, if there are volumes given
3340 if ( faceSet1.size() != faceSet2.size() ) {
3341 // delete temporary faces: they are in reverseElements of actual nodes
3342 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
3343 while ( tmpFaceIt->more() )
3344 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
3345 MESSAGE("Diff nb of faces");
3346 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3349 // ============================================================
3350 // 2. Find nodes to merge:
3351 // bind a node to remove to a node to put instead
3352 // ============================================================
3354 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
3355 if ( theFirstNode1 != theFirstNode2 )
3356 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
3357 if ( theSecondNode1 != theSecondNode2 )
3358 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
3360 LinkID_Gen aLinkID_Gen( GetMeshDS() );
3361 set< long > linkIdSet; // links to process
3362 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
3364 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
3365 list< TPairOfNodes > linkList[2];
3366 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
3367 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
3368 // loop on links in linkList; find faces by links and append links
3369 // of the found faces to linkList
3370 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
3371 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
3373 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
3374 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
3375 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
3378 // by links, find faces in the face sets,
3379 // and find indices of link nodes in the found faces;
3380 // in a face set, there is only one or no face sharing a link
3381 // ---------------------------------------------------------------
3383 const SMDS_MeshElement* face[] = { 0, 0 };
3384 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
3385 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
3386 int iLinkNode[2][2];
3387 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
3388 const SMDS_MeshNode* n1 = link[iSide].first;
3389 const SMDS_MeshNode* n2 = link[iSide].second;
3390 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3391 set< const SMDS_MeshElement* > fMap;
3392 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
3393 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
3394 SMDS_ElemIteratorPtr fIt = n->facesIterator();
3395 while ( fIt->more() ) { // loop on faces sharing a node
3396 const SMDS_MeshElement* f = fIt->next();
3397 if (faceSet->find( f ) != faceSet->end() && // f is in face set
3398 ! fMap.insert( f ).second ) // f encounters twice
3400 if ( face[ iSide ] ) {
3401 MESSAGE( "2 faces per link " );
3402 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
3406 faceSet->erase( f );
3407 // get face nodes and find ones of a link
3409 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3410 while ( nIt->more() ) {
3411 const SMDS_MeshNode* n =
3412 static_cast<const SMDS_MeshNode*>( nIt->next() );
3414 iLinkNode[ iSide ][ 0 ] = iNode;
3416 iLinkNode[ iSide ][ 1 ] = iNode;
3417 else if ( notLinkNodes[ iSide ][ 0 ] )
3418 notLinkNodes[ iSide ][ 1 ] = n;
3420 notLinkNodes[ iSide ][ 0 ] = n;
3421 faceNodes[ iSide ][ iNode++ ] = n;
3423 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
3428 // check similarity of elements of the sides
3429 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
3430 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
3431 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
3432 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
3434 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3435 break; // do not return because it s necessary to remove tmp faces
3438 // set nodes to merge
3439 // -------------------
3441 if ( face[0] && face[1] )
3443 int nbNodes = face[0]->NbNodes();
3444 if ( nbNodes != face[1]->NbNodes() ) {
3445 MESSAGE("Diff nb of face nodes");
3446 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3447 break; // do not return because it s necessary to remove tmp faces
3449 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
3451 nReplaceMap.insert( TNodeNodeMap::value_type
3452 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
3454 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
3455 // analyse link orientation in faces
3456 int i1 = iLinkNode[ iSide ][ 0 ];
3457 int i2 = iLinkNode[ iSide ][ 1 ];
3458 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
3459 // if notLinkNodes are the first and the last ones, then
3460 // their order does not correspond to the link orientation
3461 if (( i1 == 1 && i2 == 2 ) ||
3462 ( i1 == 2 && i2 == 1 ))
3463 reverse[ iSide ] = !reverse[ iSide ];
3465 if ( reverse[0] == reverse[1] ) {
3466 nReplaceMap.insert( TNodeNodeMap::value_type
3467 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
3468 nReplaceMap.insert( TNodeNodeMap::value_type
3469 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
3472 nReplaceMap.insert( TNodeNodeMap::value_type
3473 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
3474 nReplaceMap.insert( TNodeNodeMap::value_type
3475 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
3479 // add other links of the faces to linkList
3480 // -----------------------------------------
3482 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
3483 for ( iNode = 0; iNode < nbNodes; iNode++ )
3485 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
3486 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
3487 if ( !iter_isnew.second ) { // already in a set: no need to process
3488 linkIdSet.erase( iter_isnew.first );
3490 else // new in set == encountered for the first time: add
3492 const SMDS_MeshNode* n1 = nodes[ iNode ];
3493 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
3494 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
3495 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
3499 } // loop on link lists
3501 if ( aResult == SEW_OK &&
3502 ( linkIt[0] != linkList[0].end() ||
3503 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
3504 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
3505 " " << (faceSetPtr[1]->empty()));
3506 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3509 // ====================================================================
3510 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
3511 // ====================================================================
3513 // delete temporary faces: they are in reverseElements of actual nodes
3514 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
3515 while ( tmpFaceIt->more() )
3516 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
3518 if ( aResult != SEW_OK)
3521 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
3522 // loop on nodes replacement map
3523 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
3524 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
3525 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
3527 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
3528 nodeIDsToRemove.push_back( nToRemove->GetID() );
3529 // loop on elements sharing nToRemove
3530 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3531 while ( invElemIt->more() ) {
3532 const SMDS_MeshElement* e = invElemIt->next();
3533 // get a new suite of nodes: make replacement
3534 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
3535 const SMDS_MeshNode* nodes[ 8 ];
3536 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3537 while ( nIt->more() ) {
3538 const SMDS_MeshNode* n =
3539 static_cast<const SMDS_MeshNode*>( nIt->next() );
3540 nnIt = nReplaceMap.find( n );
3541 if ( nnIt != nReplaceMap.end() ) {
3547 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
3548 // elemIDsToRemove.push_back( e->GetID() );
3551 aMesh->ChangeElementNodes( e, nodes, nbNodes );
3555 Remove( nodeIDsToRemove, true );