1 // SMESH SMESH : idl implementation based on 'SMESH' unit's classes
3 // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
24 // File : SMESH_MeshEditor.cxx
25 // Created : Mon Apr 12 16:10:22 2004
26 // Author : Edward AGAPOV (eap)
29 #include "SMESH_MeshEditor.hxx"
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
38 #include "SMESHDS_Group.hxx"
39 #include "SMESHDS_Mesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_ControlsDef.hxx"
44 #include "utilities.h"
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_ListOfShape.hxx>
52 #include <gp_Trsf.hxx>
58 #include <BRep_Tool.hxx>
59 #include <Geom_Curve.hxx>
60 #include <Geom_Surface.hxx>
61 #include <Geom2d_Curve.hxx>
62 #include <Extrema_GenExtPS.hxx>
63 #include <Extrema_POnSurf.hxx>
64 #include <GeomAdaptor_Surface.hxx>
70 using namespace SMESH::Controls;
72 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
73 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
74 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
75 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
76 typedef TNodeOfNodeListMap::iterator TNodeOfNodeListMapItr;
77 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
79 //=======================================================================
80 //function : SMESH_MeshEditor
82 //=======================================================================
84 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
89 //=======================================================================
91 //purpose : Remove a node or an element.
92 // Modify a compute state of sub-meshes which become empty
93 //=======================================================================
95 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
99 SMESHDS_Mesh* aMesh = GetMeshDS();
100 set< SMESH_subMesh *> smmap;
102 list<int>::const_iterator it = theIDs.begin();
103 for ( ; it != theIDs.end(); it++ )
105 const SMDS_MeshElement * elem;
107 elem = aMesh->FindNode( *it );
109 elem = aMesh->FindElement( *it );
113 // Find sub-meshes to notify about modification
114 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
115 while ( nodeIt->more() )
117 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
118 const SMDS_PositionPtr& aPosition = node->GetPosition();
119 if ( aPosition.get() ) {
120 int aShapeID = aPosition->GetShapeId();
122 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
123 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
132 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
134 aMesh->RemoveElement( elem );
137 // Notify sub-meshes about modification
138 if ( !smmap.empty() ) {
139 set< SMESH_subMesh *>::iterator smIt;
140 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
141 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
146 //=======================================================================
147 //function : FindShape
148 //purpose : Return an index of the shape theElem is on
149 // or zero if a shape not found
150 //=======================================================================
152 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
154 SMESHDS_Mesh * aMesh = GetMeshDS();
155 if ( aMesh->ShapeToMesh().IsNull() )
158 if ( theElem->GetType() == SMDSAbs_Node )
160 const SMDS_PositionPtr& aPosition =
161 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
162 if ( aPosition.get() )
163 return aPosition->GetShapeId();
168 TopoDS_Shape aShape; // the shape a node is on
169 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
170 while ( nodeIt->more() )
172 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
173 const SMDS_PositionPtr& aPosition = node->GetPosition();
174 if ( aPosition.get() ) {
175 int aShapeID = aPosition->GetShapeId();
176 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
179 if ( sm->Contains( theElem ))
181 if ( aShape.IsNull() )
182 aShape = aMesh->IndexToShape( aShapeID );
186 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
191 // None of nodes is on a proper shape,
192 // find the shape among ancestors of aShape on which a node is
193 if ( aShape.IsNull() ) {
194 //MESSAGE ("::FindShape() - NONE node is on shape")
197 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
198 for ( ; ancIt.More(); ancIt.Next() )
200 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
201 if ( sm && sm->Contains( theElem ))
202 return aMesh->ShapeToIndex( ancIt.Value() );
205 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
209 //=======================================================================
210 //function : InverseDiag
211 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
212 // but having other common link.
213 // Return False if args are improper
214 //=======================================================================
216 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
217 const SMDS_MeshElement * theTria2 )
219 if (!theTria1 || !theTria2)
221 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
222 if (!F1) return false;
223 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
224 if (!F2) return false;
226 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
227 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
231 // put nodes in array and find out indices of the same ones
232 const SMDS_MeshNode* aNodes [6];
233 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
235 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
238 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
240 if ( i > 2 ) // theTria2
241 // find same node of theTria1
242 for ( int j = 0; j < 3; j++ )
243 if ( aNodes[ i ] == aNodes[ j ]) {
252 return false; // theTria1 is not a triangle
253 it = theTria2->nodesIterator();
255 if ( i == 6 && it->more() )
256 return false; // theTria2 is not a triangle
259 // find indices of 1,2 and of A,B in theTria1
260 int iA = 0, iB = 0, i1 = 0, i2 = 0;
261 for ( i = 0; i < 6; i++ )
263 if ( sameInd [ i ] == 0 )
270 // nodes 1 and 2 should not be the same
271 if ( aNodes[ i1 ] == aNodes[ i2 ] )
276 aNodes[ iA ] = aNodes[ i2 ];
278 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
280 //MESSAGE( theTria1 << theTria2 );
282 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
283 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
285 //MESSAGE( theTria1 << theTria2 );
290 //=======================================================================
291 //function : findTriangles
292 //purpose : find triangles sharing theNode1-theNode2 link
293 //=======================================================================
295 static bool findTriangles(const SMDS_MeshNode * theNode1,
296 const SMDS_MeshNode * theNode2,
297 const SMDS_MeshElement*& theTria1,
298 const SMDS_MeshElement*& theTria2)
300 if ( !theNode1 || !theNode2 ) return false;
302 theTria1 = theTria2 = 0;
304 set< const SMDS_MeshElement* > emap;
305 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
307 const SMDS_MeshElement* elem = it->next();
308 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
311 it = theNode2->GetInverseElementIterator();
313 const SMDS_MeshElement* elem = it->next();
314 if ( elem->GetType() == SMDSAbs_Face &&
315 emap.find( elem ) != emap.end() )
323 return ( theTria1 && theTria2 );
326 //=======================================================================
327 //function : InverseDiag
328 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
329 // with ones built on the same 4 nodes but having other common link.
330 // Return false if proper faces not found
331 //=======================================================================
333 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
334 const SMDS_MeshNode * theNode2)
336 MESSAGE( "::InverseDiag()" );
338 const SMDS_MeshElement *tr1, *tr2;
339 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
342 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
343 if (!F1) return false;
344 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
345 if (!F2) return false;
347 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
348 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
352 // put nodes in array
353 // and find indices of 1,2 and of A in tr1 and of B in tr2
354 int i, iA1 = 0, i1 = 0;
355 const SMDS_MeshNode* aNodes1 [3];
356 SMDS_ElemIteratorPtr it;
357 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
358 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
359 if ( aNodes1[ i ] == theNode1 )
360 iA1 = i; // node A in tr1
361 else if ( aNodes1[ i ] != theNode2 )
365 const SMDS_MeshNode* aNodes2 [3];
366 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
367 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
368 if ( aNodes2[ i ] == theNode2 )
369 iB2 = i; // node B in tr2
370 else if ( aNodes2[ i ] != theNode1 )
374 // nodes 1 and 2 should not be the same
375 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
379 aNodes1[ iA1 ] = aNodes2[ i2 ];
381 aNodes2[ iB2 ] = aNodes1[ i1 ];
383 //MESSAGE( tr1 << tr2 );
385 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
386 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
388 //MESSAGE( tr1 << tr2 );
394 //=======================================================================
395 //function : getQuadrangleNodes
396 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
397 // fusion of triangles tr1 and tr2 having shared link on
398 // theNode1 and theNode2
399 //=======================================================================
401 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
402 const SMDS_MeshNode * theNode1,
403 const SMDS_MeshNode * theNode2,
404 const SMDS_MeshElement * tr1,
405 const SMDS_MeshElement * tr2 )
407 // find the 4-th node to insert into tr1
408 const SMDS_MeshNode* n4 = 0;
409 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
410 while ( !n4 && it->more() )
412 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
413 bool isDiag = ( n == theNode1 || n == theNode2 );
417 // Make an array of nodes to be in a quadrangle
418 int iNode = 0, iFirstDiag = -1;
419 it = tr1->nodesIterator();
422 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
423 bool isDiag = ( n == theNode1 || n == theNode2 );
426 if ( iFirstDiag < 0 )
428 else if ( iNode - iFirstDiag == 1 )
429 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
433 return false; // tr1 and tr2 should not have all the same nodes
435 theQuadNodes[ iNode++ ] = n;
437 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
438 theQuadNodes[ iNode ] = n4;
443 //=======================================================================
444 //function : DeleteDiag
445 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
446 // with a quadrangle built on the same 4 nodes.
447 // Return false if proper faces not found
448 //=======================================================================
450 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
451 const SMDS_MeshNode * theNode2)
453 MESSAGE( "::DeleteDiag()" );
455 const SMDS_MeshElement *tr1, *tr2;
456 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
459 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
460 if (!F1) return false;
461 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
462 if (!F2) return false;
464 const SMDS_MeshNode* aNodes [ 4 ];
465 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
468 //MESSAGE( endl << tr1 << tr2 );
470 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
471 GetMeshDS()->RemoveElement( tr2 );
473 //MESSAGE( endl << tr1 );
478 //=======================================================================
479 //function : Reorient
480 //purpose : Reverse theElement orientation
481 //=======================================================================
483 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
487 SMDS_ElemIteratorPtr it = theElem->nodesIterator();
488 if ( !it || !it->more() )
491 switch ( theElem->GetType() ) {
496 int i = theElem->NbNodes();
497 vector<const SMDS_MeshNode*> aNodes( i );
499 aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
500 return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
504 if (theElem->IsPoly()) {
505 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
506 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
508 MESSAGE("Warning: bad volumic element");
512 int nbFaces = aPolyedre->NbFaces();
513 vector<const SMDS_MeshNode *> poly_nodes;
514 vector<int> quantities (nbFaces);
516 // reverse each face of the polyedre
517 for (int iface = 1; iface <= nbFaces; iface++) {
518 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
519 quantities[iface - 1] = nbFaceNodes;
521 for (inode = nbFaceNodes; inode >= 1; inode--) {
522 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
523 poly_nodes.push_back(curNode);
527 return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
530 SMDS_VolumeTool vTool;
531 if ( !vTool.Set( theElem ))
534 return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
543 //=======================================================================
544 //function : getBadRate
546 //=======================================================================
548 static double getBadRate (const SMDS_MeshElement* theElem,
549 SMESH::Controls::NumericalFunctorPtr& theCrit)
551 SMESH::Controls::TSequenceOfXYZ P;
552 if ( !theElem || !theCrit->GetPoints( theElem, P ))
554 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
557 //=======================================================================
558 //function : QuadToTri
559 //purpose : Cut quadrangles into triangles.
560 // theCrit is used to select a diagonal to cut
561 //=======================================================================
563 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
564 SMESH::Controls::NumericalFunctorPtr theCrit)
566 MESSAGE( "::QuadToTri()" );
568 if ( !theCrit.get() )
571 SMESHDS_Mesh * aMesh = GetMeshDS();
573 set< const SMDS_MeshElement * >::iterator itElem;
574 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
576 const SMDS_MeshElement* elem = (*itElem);
577 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
580 // retrieve element nodes
581 const SMDS_MeshNode* aNodes [4];
582 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
584 while ( itN->more() )
585 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
587 // compare two sets of possible triangles
588 double aBadRate1, aBadRate2; // to what extent a set is bad
589 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
590 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
591 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
593 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
594 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
595 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
597 int aShapeId = FindShape( elem );
598 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
599 // << " ShapeID = " << aShapeId << endl << elem );
601 if ( aBadRate1 <= aBadRate2 ) {
602 // tr1 + tr2 is better
603 aMesh->ChangeElementNodes( elem, aNodes, 3 );
604 //MESSAGE( endl << elem );
606 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
609 // tr3 + tr4 is better
610 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
611 //MESSAGE( endl << elem );
613 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
615 //MESSAGE( endl << elem );
617 // put a new triangle on the same shape
619 aMesh->SetMeshElementOnShape( elem, aShapeId );
625 //=======================================================================
626 //function : AddToSameGroups
627 //purpose : add elemToAdd to the groups the elemInGroups belongs to
628 //=======================================================================
630 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
631 const SMDS_MeshElement* elemInGroups,
632 SMESHDS_Mesh * aMesh)
634 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
635 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
636 for ( ; grIt != groups.end(); grIt++ ) {
637 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
638 if ( group && group->SMDSGroup().Contains( elemInGroups ))
639 group->SMDSGroup().Add( elemToAdd );
643 //=======================================================================
644 //function : QuadToTri
645 //purpose : Cut quadrangles into triangles.
646 // theCrit is used to select a diagonal to cut
647 //=======================================================================
649 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
650 const bool the13Diag)
652 MESSAGE( "::QuadToTri()" );
654 SMESHDS_Mesh * aMesh = GetMeshDS();
656 set< const SMDS_MeshElement * >::iterator itElem;
657 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
659 const SMDS_MeshElement* elem = (*itElem);
660 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
663 // retrieve element nodes
664 const SMDS_MeshNode* aNodes [4];
665 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
667 while ( itN->more() )
668 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
670 int aShapeId = FindShape( elem );
671 const SMDS_MeshElement* newElem = 0;
674 aMesh->ChangeElementNodes( elem, aNodes, 3 );
675 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
679 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
680 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
683 // put a new triangle on the same shape and add to the same groups
686 aMesh->SetMeshElementOnShape( newElem, aShapeId );
688 AddToSameGroups( newElem, elem, aMesh );
694 //=======================================================================
695 //function : getAngle
697 //=======================================================================
699 double getAngle(const SMDS_MeshElement * tr1,
700 const SMDS_MeshElement * tr2,
701 const SMDS_MeshNode * n1,
702 const SMDS_MeshNode * n2)
704 double angle = 2*PI; // bad angle
707 SMESH::Controls::TSequenceOfXYZ P1, P2;
708 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
709 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
711 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
712 if ( N1.SquareMagnitude() <= gp::Resolution() )
714 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
715 if ( N2.SquareMagnitude() <= gp::Resolution() )
718 // find the first diagonal node n1 in the triangles:
719 // take in account a diagonal link orientation
720 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
721 for ( int t = 0; t < 2; t++ )
723 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
724 int i = 0, iDiag = -1;
725 while ( it->more()) {
726 const SMDS_MeshElement *n = it->next();
727 if ( n == n1 || n == n2 )
731 if ( i - iDiag == 1 )
732 nFirst[ t ] = ( n == n1 ? n2 : n1 );
740 if ( nFirst[ 0 ] == nFirst[ 1 ] )
743 angle = N1.Angle( N2 );
748 // =================================================
749 // class generating a unique ID for a pair of nodes
750 // and able to return nodes by that ID
751 // =================================================
756 LinkID_Gen( const SMESHDS_Mesh* theMesh )
757 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
760 long GetLinkID (const SMDS_MeshNode * n1,
761 const SMDS_MeshNode * n2) const
763 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
766 bool GetNodes (const long theLinkID,
767 const SMDS_MeshNode* & theNode1,
768 const SMDS_MeshNode* & theNode2) const
770 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
771 if ( !theNode1 ) return false;
772 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
773 if ( !theNode2 ) return false;
779 const SMESHDS_Mesh* myMesh;
783 //=======================================================================
784 //function : TriToQuad
785 //purpose : Fuse neighbour triangles into quadrangles.
786 // theCrit is used to select a neighbour to fuse with.
787 // theMaxAngle is a max angle between element normals at which
788 // fusion is still performed.
789 //=======================================================================
791 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
792 SMESH::Controls::NumericalFunctorPtr theCrit,
793 const double theMaxAngle)
795 MESSAGE( "::TriToQuad()" );
797 if ( !theCrit.get() )
800 SMESHDS_Mesh * aMesh = GetMeshDS();
801 LinkID_Gen aLinkID_Gen( aMesh );
804 // Prepare data for algo: build
805 // 1. map of elements with their linkIDs
806 // 2. map of linkIDs with their elements
808 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
809 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
810 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
811 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
813 set<const SMDS_MeshElement*>::iterator itElem;
814 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
816 const SMDS_MeshElement* elem = (*itElem);
817 if ( !elem || elem->NbNodes() != 3 )
820 // retrieve element nodes
821 const SMDS_MeshNode* aNodes [4];
822 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
824 while ( itN->more() )
825 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
827 aNodes[ 3 ] = aNodes[ 0 ];
830 for ( i = 0; i < 3; i++ )
832 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
833 // check if elements sharing a link can be fused
834 itLE = mapLi_listEl.find( linkID );
835 if ( itLE != mapLi_listEl.end() )
837 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
839 const SMDS_MeshElement* elem2 = (*itLE).second.front();
840 // if ( FindShape( elem ) != FindShape( elem2 ))
841 // continue; // do not fuse triangles laying on different shapes
842 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
843 continue; // avoid making badly shaped quads
844 (*itLE).second.push_back( elem );
847 mapLi_listEl[ linkID ].push_back( elem );
848 mapEl_setLi [ elem ].insert( linkID );
851 // Clean the maps from the links shared by a sole element, ie
852 // links to which only one element is bound in mapLi_listEl
854 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
856 int nbElems = (*itLE).second.size();
858 const SMDS_MeshElement* elem = (*itLE).second.front();
859 long link = (*itLE).first;
860 mapEl_setLi[ elem ].erase( link );
861 if ( mapEl_setLi[ elem ].empty() )
862 mapEl_setLi.erase( elem );
866 // Algo: fuse triangles into quadrangles
868 while ( ! mapEl_setLi.empty() )
870 // Look for the start element:
871 // the element having the least nb of shared links
873 const SMDS_MeshElement* startElem = 0;
875 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
877 int nbLinks = (*itEL).second.size();
878 if ( nbLinks < minNbLinks )
880 startElem = (*itEL).first;
881 minNbLinks = nbLinks;
882 if ( minNbLinks == 1 )
887 // search elements to fuse starting from startElem or links of elements
888 // fused earlyer - startLinks
889 list< long > startLinks;
890 while ( startElem || !startLinks.empty() )
892 while ( !startElem && !startLinks.empty() )
894 // Get an element to start, by a link
895 long linkId = startLinks.front();
896 startLinks.pop_front();
897 itLE = mapLi_listEl.find( linkId );
898 if ( itLE != mapLi_listEl.end() )
900 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
901 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
902 for ( ; itE != listElem.end() ; itE++ )
903 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
905 mapLi_listEl.erase( itLE );
911 // Get candidates to be fused
913 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
916 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
917 set< long >& setLi = mapEl_setLi[ tr1 ];
918 ASSERT( !setLi.empty() );
919 set< long >::iterator itLi;
920 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
922 long linkID = (*itLi);
923 itLE = mapLi_listEl.find( linkID );
924 if ( itLE == mapLi_listEl.end() )
926 const SMDS_MeshElement* elem = (*itLE).second.front();
928 elem = (*itLE).second.back();
929 mapLi_listEl.erase( itLE );
930 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
943 // add other links of elem to list of links to re-start from
944 set< long >& links = mapEl_setLi[ elem ];
945 set< long >::iterator it;
946 for ( it = links.begin(); it != links.end(); it++ )
948 long linkID2 = (*it);
949 if ( linkID2 != linkID )
950 startLinks.push_back( linkID2 );
954 // Get nodes of possible quadrangles
956 const SMDS_MeshNode *n12 [4], *n13 [4];
957 bool Ok12 = false, Ok13 = false;
958 const SMDS_MeshNode *linkNode1, *linkNode2;
960 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
961 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
964 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
965 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
968 // Choose a pair to fuse
972 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
973 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
974 double aBadRate12 = getBadRate( &quad12, theCrit );
975 double aBadRate13 = getBadRate( &quad13, theCrit );
976 if ( aBadRate13 < aBadRate12 )
984 // and remove fused elems and removed links from the maps
986 mapEl_setLi.erase( tr1 );
989 mapEl_setLi.erase( tr2 );
990 mapLi_listEl.erase( link12 );
991 aMesh->ChangeElementNodes( tr1, n12, 4 );
992 aMesh->RemoveElement( tr2 );
996 mapEl_setLi.erase( tr3 );
997 mapLi_listEl.erase( link13 );
998 aMesh->ChangeElementNodes( tr1, n13, 4 );
999 aMesh->RemoveElement( tr3 );
1002 // Next element to fuse: the rejected one
1004 startElem = Ok12 ? tr3 : tr2;
1006 } // if ( startElem )
1007 } // while ( startElem || !startLinks.empty() )
1008 } // while ( ! mapEl_setLi.empty() )
1014 /*#define DUMPSO(txt) \
1015 // cout << txt << endl;
1016 //=============================================================================
1020 //=============================================================================
1021 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1025 int tmp = idNodes[ i1 ];
1026 idNodes[ i1 ] = idNodes[ i2 ];
1027 idNodes[ i2 ] = tmp;
1028 gp_Pnt Ptmp = P[ i1 ];
1031 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1034 //=======================================================================
1035 //function : SortQuadNodes
1036 //purpose : Set 4 nodes of a quadrangle face in a good order.
1037 // Swap 1<->2 or 2<->3 nodes and correspondingly return
1039 //=======================================================================
1041 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1046 for ( i = 0; i < 4; i++ ) {
1047 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1049 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1052 gp_Vec V1(P[0], P[1]);
1053 gp_Vec V2(P[0], P[2]);
1054 gp_Vec V3(P[0], P[3]);
1056 gp_Vec Cross1 = V1 ^ V2;
1057 gp_Vec Cross2 = V2 ^ V3;
1060 if (Cross1.Dot(Cross2) < 0)
1065 if (Cross1.Dot(Cross2) < 0)
1069 swap ( i, i + 1, idNodes, P );
1071 // for ( int ii = 0; ii < 4; ii++ ) {
1072 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1073 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1079 //=======================================================================
1080 //function : SortHexaNodes
1081 //purpose : Set 8 nodes of a hexahedron in a good order.
1082 // Return success status
1083 //=======================================================================
1085 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1090 DUMPSO( "INPUT: ========================================");
1091 for ( i = 0; i < 8; i++ ) {
1092 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1093 if ( !n ) return false;
1094 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1095 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1097 DUMPSO( "========================================");
1100 set<int> faceNodes; // ids of bottom face nodes, to be found
1101 set<int> checkedId1; // ids of tried 2-nd nodes
1102 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1103 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1104 int iMin, iLoop1 = 0;
1106 // Loop to try the 2-nd nodes
1108 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1110 // Find not checked 2-nd node
1111 for ( i = 1; i < 8; i++ )
1112 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1113 int id1 = idNodes[i];
1114 swap ( 1, i, idNodes, P );
1115 checkedId1.insert ( id1 );
1119 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1120 // ie that all but meybe one (id3 which is on the same face) nodes
1121 // lay on the same side from the triangle plane.
1123 bool manyInPlane = false; // more than 4 nodes lay in plane
1125 while ( ++iLoop2 < 6 ) {
1127 // get 1-2-3 plane coeffs
1128 Standard_Real A, B, C, D;
1129 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1130 if ( N.SquareMagnitude() > gp::Resolution() )
1132 gp_Pln pln ( P[0], N );
1133 pln.Coefficients( A, B, C, D );
1135 // find the node (iMin) closest to pln
1136 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1138 for ( i = 3; i < 8; i++ ) {
1139 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1140 if ( fabs( dist[i] ) < minDist ) {
1141 minDist = fabs( dist[i] );
1144 if ( fabs( dist[i] ) <= tol )
1145 idInPln.insert( idNodes[i] );
1148 // there should not be more than 4 nodes in bottom plane
1149 if ( idInPln.size() > 1 )
1151 DUMPSO( "### idInPln.size() = " << idInPln.size());
1152 // idInPlane does not contain the first 3 nodes
1153 if ( manyInPlane || idInPln.size() == 5)
1154 return false; // all nodes in one plane
1157 // set the 1-st node to be not in plane
1158 for ( i = 3; i < 8; i++ ) {
1159 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1160 DUMPSO( "### Reset 0-th node");
1161 swap( 0, i, idNodes, P );
1166 // reset to re-check second nodes
1167 leastDist = DBL_MAX;
1171 break; // from iLoop2;
1174 // check that the other 4 nodes are on the same side
1175 bool sameSide = true;
1176 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1177 for ( i = 3; sameSide && i < 8; i++ ) {
1179 sameSide = ( isNeg == dist[i] <= 0.);
1182 // keep best solution
1183 if ( sameSide && minDist < leastDist ) {
1184 leastDist = minDist;
1186 faceNodes.insert( idNodes[ 1 ] );
1187 faceNodes.insert( idNodes[ 2 ] );
1188 faceNodes.insert( idNodes[ iMin ] );
1189 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1190 << " leastDist = " << leastDist);
1191 if ( leastDist <= DBL_MIN )
1196 // set next 3-d node to check
1197 int iNext = 2 + iLoop2;
1199 DUMPSO( "Try 2-nd");
1200 swap ( 2, iNext, idNodes, P );
1202 } // while ( iLoop2 < 6 )
1205 if ( faceNodes.empty() ) return false;
1207 // Put the faceNodes in proper places
1208 for ( i = 4; i < 8; i++ ) {
1209 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1210 // find a place to put
1212 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1214 DUMPSO( "Set faceNodes");
1215 swap ( iTo, i, idNodes, P );
1220 // Set nodes of the found bottom face in good order
1221 DUMPSO( " Found bottom face: ");
1222 i = SortQuadNodes( theMesh, idNodes );
1224 gp_Pnt Ptmp = P[ i ];
1229 // for ( int ii = 0; ii < 4; ii++ ) {
1230 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1231 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1234 // Gravity center of the top and bottom faces
1235 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1236 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1238 // Get direction from the bottom to the top face
1239 gp_Vec upDir ( aGCb, aGCt );
1240 Standard_Real upDirSize = upDir.Magnitude();
1241 if ( upDirSize <= gp::Resolution() ) return false;
1244 // Assure that the bottom face normal points up
1245 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1246 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1247 if ( Nb.Dot( upDir ) < 0 ) {
1248 DUMPSO( "Reverse bottom face");
1249 swap( 1, 3, idNodes, P );
1252 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1253 Standard_Real minDist = DBL_MAX;
1254 for ( i = 4; i < 8; i++ ) {
1255 // projection of P[i] to the plane defined by P[0] and upDir
1256 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1257 Standard_Real sqDist = P[0].SquareDistance( Pp );
1258 if ( sqDist < minDist ) {
1263 DUMPSO( "Set 4-th");
1264 swap ( 4, iMin, idNodes, P );
1266 // Set nodes of the top face in good order
1267 DUMPSO( "Sort top face");
1268 i = SortQuadNodes( theMesh, &idNodes[4] );
1271 gp_Pnt Ptmp = P[ i ];
1276 // Assure that direction of the top face normal is from the bottom face
1277 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1278 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1279 if ( Nt.Dot( upDir ) < 0 ) {
1280 DUMPSO( "Reverse top face");
1281 swap( 5, 7, idNodes, P );
1284 // DUMPSO( "OUTPUT: ========================================");
1285 // for ( i = 0; i < 8; i++ ) {
1286 // float *p = ugrid->GetPoint(idNodes[i]);
1287 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1293 //=======================================================================
1294 //function : laplacianSmooth
1295 //purpose : pulls theNode toward the center of surrounding nodes directly
1296 // connected to that node along an element edge
1297 //=======================================================================
1299 void laplacianSmooth(const SMDS_MeshNode* theNode,
1300 const Handle(Geom_Surface)& theSurface,
1301 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1303 // find surrounding nodes
1305 set< const SMDS_MeshNode* > nodeSet;
1306 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1307 while ( elemIt->more() )
1309 const SMDS_MeshElement* elem = elemIt->next();
1310 if ( elem->GetType() != SMDSAbs_Face )
1313 // put all nodes in array
1314 int nbNodes = 0, iNode = 0;
1315 vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1316 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1317 while ( itN->more() )
1319 aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1320 if ( aNodes[ nbNodes ] == theNode )
1321 iNode = nbNodes; // index of theNode within aNodes
1325 int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1326 nodeSet.insert( aNodes[ iAfter ]);
1327 int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1328 nodeSet.insert( aNodes[ iBefore ]);
1331 // compute new coodrs
1333 double coord[] = { 0., 0., 0. };
1334 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1335 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1336 const SMDS_MeshNode* node = (*nodeSetIt);
1337 if ( theSurface.IsNull() ) { // smooth in 3D
1338 coord[0] += node->X();
1339 coord[1] += node->Y();
1340 coord[2] += node->Z();
1342 else { // smooth in 2D
1343 ASSERT( theUVMap.find( node ) != theUVMap.end() );
1344 gp_XY* uv = theUVMap[ node ];
1345 coord[0] += uv->X();
1346 coord[1] += uv->Y();
1349 int nbNodes = nodeSet.size();
1352 coord[0] /= nbNodes;
1353 coord[1] /= nbNodes;
1355 if ( !theSurface.IsNull() ) {
1356 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1357 theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1358 gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1364 coord[2] /= nbNodes;
1368 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1371 //=======================================================================
1372 //function : centroidalSmooth
1373 //purpose : pulls theNode toward the element-area-weighted centroid of the
1374 // surrounding elements
1375 //=======================================================================
1377 void centroidalSmooth(const SMDS_MeshNode* theNode,
1378 const Handle(Geom_Surface)& theSurface,
1379 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1381 gp_XYZ aNewXYZ(0.,0.,0.);
1382 SMESH::Controls::Area anAreaFunc;
1383 double totalArea = 0.;
1388 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1389 while ( elemIt->more() )
1391 const SMDS_MeshElement* elem = elemIt->next();
1392 if ( elem->GetType() != SMDSAbs_Face )
1396 gp_XYZ elemCenter(0.,0.,0.);
1397 SMESH::Controls::TSequenceOfXYZ aNodePoints;
1398 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1399 while ( itN->more() )
1401 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1402 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1403 aNodePoints.push_back( aP );
1404 if ( !theSurface.IsNull() ) { // smooth in 2D
1405 ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
1406 gp_XY* uv = theUVMap[ aNode ];
1407 aP.SetCoord( uv->X(), uv->Y(), 0. );
1411 double elemArea = anAreaFunc.GetValue( aNodePoints );
1412 totalArea += elemArea;
1413 elemCenter /= elem->NbNodes();
1414 aNewXYZ += elemCenter * elemArea;
1416 aNewXYZ /= totalArea;
1417 if ( !theSurface.IsNull() ) {
1418 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1419 theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1420 aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1425 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1428 //=======================================================================
1429 //function : getClosestUV
1430 //purpose : return UV of closest projection
1431 //=======================================================================
1433 static bool getClosestUV (Extrema_GenExtPS& projector,
1434 const gp_Pnt& point,
1437 projector.Perform( point );
1438 if ( projector.IsDone() ) {
1439 double u, v, minVal = DBL_MAX;
1440 for ( int i = projector.NbExt(); i > 0; i-- )
1441 if ( projector.Value( i ) < minVal ) {
1442 minVal = projector.Value( i );
1443 projector.Point( i ).Parameter( u, v );
1445 result.SetCoord( u, v );
1451 //=======================================================================
1453 //purpose : Smooth theElements during theNbIterations or until a worst
1454 // element has aspect ratio <= theTgtAspectRatio.
1455 // Aspect Ratio varies in range [1.0, inf].
1456 // If theElements is empty, the whole mesh is smoothed.
1457 // theFixedNodes contains additionally fixed nodes. Nodes built
1458 // on edges and boundary nodes are always fixed.
1459 //=======================================================================
1461 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1462 set<const SMDS_MeshNode*> & theFixedNodes,
1463 const SmoothMethod theSmoothMethod,
1464 const int theNbIterations,
1465 double theTgtAspectRatio,
1468 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1470 if ( theTgtAspectRatio < 1.0 )
1471 theTgtAspectRatio = 1.0;
1473 SMESH::Controls::AspectRatio aQualityFunc;
1475 SMESHDS_Mesh* aMesh = GetMeshDS();
1477 if ( theElems.empty() ) {
1478 // add all faces to theElems
1479 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1480 while ( fIt->more() )
1481 theElems.insert( fIt->next() );
1483 // get all face ids theElems are on
1484 set< int > faceIdSet;
1485 set< const SMDS_MeshElement* >::iterator itElem;
1487 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1488 int fId = FindShape( *itElem );
1489 // check that corresponding submesh exists and a shape is face
1491 faceIdSet.find( fId ) == faceIdSet.end() &&
1492 aMesh->MeshElements( fId )) {
1493 TopoDS_Shape F = aMesh->IndexToShape( fId );
1494 if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1495 faceIdSet.insert( fId );
1498 faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1500 // ===============================================
1501 // smooth elements on each TopoDS_Face separately
1502 // ===============================================
1504 set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1505 for ( ; fId != faceIdSet.rend(); ++fId )
1507 // get face surface and submesh
1508 Handle(Geom_Surface) surface;
1509 SMESHDS_SubMesh* faceSubMesh = 0;
1511 double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
1512 double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1513 bool isUPeriodic = false, isVPeriodic = false;
1515 face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1516 surface = BRep_Tool::Surface( face );
1517 faceSubMesh = aMesh->MeshElements( *fId );
1518 fToler2 = BRep_Tool::Tolerance( face );
1519 fToler2 *= fToler2 * 10.;
1520 isUPeriodic = surface->IsUPeriodic();
1522 vPeriod = surface->UPeriod();
1523 isVPeriodic = surface->IsVPeriodic();
1525 uPeriod = surface->VPeriod();
1526 surface->Bounds( u1, u2, v1, v2 );
1528 // ---------------------------------------------------------
1529 // for elements on a face, find movable and fixed nodes and
1530 // compute UV for them
1531 // ---------------------------------------------------------
1532 bool checkBoundaryNodes = false;
1533 set<const SMDS_MeshNode*> setMovableNodes;
1534 map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1535 list< gp_XY > listUV; // uvs the 2 uvMaps refer to
1536 list< const SMDS_MeshElement* > elemsOnFace;
1538 Extrema_GenExtPS projector;
1539 GeomAdaptor_Surface surfAdaptor;
1540 if ( !surface.IsNull() ) {
1541 surfAdaptor.Load( surface );
1542 projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1544 int nbElemOnFace = 0;
1545 itElem = theElems.begin();
1546 // loop on not yet smoothed elements: look for elems on a face
1547 while ( itElem != theElems.end() )
1549 if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
1550 break; // all elements found
1552 const SMDS_MeshElement* elem = (*itElem);
1553 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1554 ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1558 elemsOnFace.push_back( elem );
1559 theElems.erase( itElem++ );
1562 // get movable nodes of elem
1563 const SMDS_MeshNode* node;
1564 SMDS_TypeOfPosition posType;
1565 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1566 while ( itN->more() ) {
1567 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1568 const SMDS_PositionPtr& pos = node->GetPosition();
1569 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1570 if (posType != SMDS_TOP_EDGE &&
1571 posType != SMDS_TOP_VERTEX &&
1572 theFixedNodes.find( node ) == theFixedNodes.end())
1574 // check if all faces around the node are on faceSubMesh
1575 // because a node on edge may be bound to face
1576 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1578 if ( faceSubMesh ) {
1579 while ( eIt->more() && all ) {
1580 const SMDS_MeshElement* e = eIt->next();
1581 if ( e->GetType() == SMDSAbs_Face )
1582 all = faceSubMesh->Contains( e );
1586 setMovableNodes.insert( node );
1588 checkBoundaryNodes = true;
1590 if ( posType == SMDS_TOP_3DSPACE )
1591 checkBoundaryNodes = true;
1594 if ( surface.IsNull() )
1597 // get nodes to check UV
1598 list< const SMDS_MeshNode* > uvCheckNodes;
1599 itN = elem->nodesIterator();
1600 while ( itN->more() ) {
1601 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1602 if ( uvMap.find( node ) == uvMap.end() )
1603 uvCheckNodes.push_back( node );
1604 // add nodes of elems sharing node
1605 // SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1606 // while ( eIt->more() ) {
1607 // const SMDS_MeshElement* e = eIt->next();
1608 // if ( e != elem && e->GetType() == SMDSAbs_Face ) {
1609 // SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1610 // while ( nIt->more() ) {
1611 // const SMDS_MeshNode* n =
1612 // static_cast<const SMDS_MeshNode*>( nIt->next() );
1613 // if ( uvMap.find( n ) == uvMap.end() )
1614 // uvCheckNodes.push_back( n );
1620 list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
1621 for ( ; n != uvCheckNodes.end(); ++n )
1625 const SMDS_PositionPtr& pos = node->GetPosition();
1626 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1628 switch ( posType ) {
1629 case SMDS_TOP_FACE: {
1630 SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1631 uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1634 case SMDS_TOP_EDGE: {
1635 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1636 Handle(Geom2d_Curve) pcurve;
1637 if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
1638 pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
1639 if ( !pcurve.IsNull() ) {
1640 double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
1641 uv = pcurve->Value( u ).XY();
1645 case SMDS_TOP_VERTEX: {
1646 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1647 if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
1648 uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
1653 // check existing UV
1654 bool project = true;
1655 gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1656 double dist1 = DBL_MAX, dist2 = 0;
1657 if ( posType != SMDS_TOP_3DSPACE ) {
1658 dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
1659 project = dist1 > fToler2;
1661 if ( project ) { // compute new UV
1663 if ( !getClosestUV( projector, pNode, newUV )) {
1664 MESSAGE("Node Projection Failed " << node);
1668 newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
1670 newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
1672 if ( posType != SMDS_TOP_3DSPACE )
1673 dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
1674 if ( dist2 < dist1 )
1678 // store UV in the map
1679 listUV.push_back( uv );
1680 uvMap.insert( make_pair( node, &listUV.back() ));
1682 } // loop on not yet smoothed elements
1684 if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
1685 checkBoundaryNodes = true;
1687 // fix nodes on mesh boundary
1689 if ( checkBoundaryNodes )
1691 typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1692 map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1693 map< TLink, int >::iterator link_nb;
1694 // put all elements links to linkNbMap
1695 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1696 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1698 // put elem nodes in array
1699 vector< const SMDS_MeshNode* > nodes;
1700 nodes.reserve( (*elemIt)->NbNodes() + 1 );
1701 SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1702 while ( itN->more() )
1703 nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1704 nodes.push_back( nodes.front() );
1705 // loop on elem links: insert them in linkNbMap
1706 for ( int iN = 1; iN < nodes.size(); ++iN ) {
1708 if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1709 link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1711 link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1712 link_nb = linkNbMap.find( link );
1713 if ( link_nb == linkNbMap.end() )
1714 linkNbMap.insert( make_pair ( link, 1 ));
1719 // remove nodes that are in links encountered only once from setMovableNodes
1720 for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1721 if ( link_nb->second == 1 ) {
1722 setMovableNodes.erase( link_nb->first.first );
1723 setMovableNodes.erase( link_nb->first.second );
1728 // -----------------------------------------------------
1729 // for nodes on seam edge, compute one more UV ( uvMap2 );
1730 // find movable nodes linked to nodes on seam and which
1731 // are to be smoothed using the second UV ( uvMap2 )
1732 // -----------------------------------------------------
1734 set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1735 if ( !surface.IsNull() )
1737 TopExp_Explorer eExp( face, TopAbs_EDGE );
1738 for ( ; eExp.More(); eExp.Next() )
1740 TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1741 if ( !BRep_Tool::IsClosed( edge, face ))
1743 SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1744 if ( !sm ) continue;
1745 // find out which parameter varies for a node on seam
1748 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1749 if ( pcurve.IsNull() ) continue;
1750 uv1 = pcurve->Value( f );
1752 pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1753 if ( pcurve.IsNull() ) continue;
1754 uv2 = pcurve->Value( f );
1755 int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1757 if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1758 gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1760 // get nodes on seam and its vertices
1761 list< const SMDS_MeshNode* > seamNodes;
1762 SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1763 while ( nSeamIt->more() )
1764 seamNodes.push_back( nSeamIt->next() );
1765 TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1766 for ( ; vExp.More(); vExp.Next() ) {
1767 sm = aMesh->MeshElements( vExp.Current() );
1769 nSeamIt = sm->GetNodes();
1770 while ( nSeamIt->more() )
1771 seamNodes.push_back( nSeamIt->next() );
1774 // loop on nodes on seam
1775 list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1776 for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1778 const SMDS_MeshNode* nSeam = *noSeIt;
1779 map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1780 if ( n_uv == uvMap.end() )
1783 n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1784 // set the second UV
1785 listUV.push_back( *n_uv->second );
1786 listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1787 if ( uvMap2.empty() )
1788 uvMap2 = uvMap; // copy the uvMap contents
1789 uvMap2[ nSeam ] = &listUV.back();
1791 // collect movable nodes linked to ones on seam in nodesNearSeam
1792 SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1793 while ( eIt->more() )
1795 const SMDS_MeshElement* e = eIt->next();
1796 if ( e->GetType() != SMDSAbs_Face )
1798 int nbUseMap1 = 0, nbUseMap2 = 0;
1799 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1800 while ( nIt->more() )
1802 const SMDS_MeshNode* n =
1803 static_cast<const SMDS_MeshNode*>( nIt->next() );
1805 setMovableNodes.find( n ) == setMovableNodes.end() )
1807 // add only nodes being closer to uv2 than to uv1
1808 gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1809 0.5 * ( n->Y() + nSeam->Y() ),
1810 0.5 * ( n->Z() + nSeam->Z() ));
1812 getClosestUV( projector, pMid, uv );
1813 if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1814 nodesNearSeam.insert( n );
1820 // for centroidalSmooth all element nodes must
1821 // be on one side of a seam
1822 if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1824 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1825 while ( nIt->more() ) {
1826 const SMDS_MeshNode* n =
1827 static_cast<const SMDS_MeshNode*>( nIt->next() );
1828 setMovableNodes.erase( n );
1832 } // loop on nodes on seam
1833 } // loop on edge of a face
1834 } // if ( !face.IsNull() )
1836 if ( setMovableNodes.empty() ) {
1837 MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
1838 continue; // goto next face
1846 double maxRatio = -1., maxDisplacement = -1.;
1847 set<const SMDS_MeshNode*>::iterator nodeToMove;
1848 for ( it = 0; it < theNbIterations; it++ )
1850 maxDisplacement = 0.;
1851 nodeToMove = setMovableNodes.begin();
1852 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1854 const SMDS_MeshNode* node = (*nodeToMove);
1855 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1858 bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1859 if ( theSmoothMethod == LAPLACIAN )
1860 laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1862 centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1864 // node displacement
1865 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1866 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1867 if ( aDispl > maxDisplacement )
1868 maxDisplacement = aDispl;
1870 // no node movement => exit
1871 if ( maxDisplacement < 1.e-16 ) {
1872 MESSAGE("-- no node movement --");
1876 // check elements quality
1878 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1879 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1881 const SMDS_MeshElement* elem = (*elemIt);
1882 if ( !elem || elem->GetType() != SMDSAbs_Face )
1884 SMESH::Controls::TSequenceOfXYZ aPoints;
1885 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1886 double aValue = aQualityFunc.GetValue( aPoints );
1887 if ( aValue > maxRatio )
1891 if ( maxRatio <= theTgtAspectRatio ) {
1892 MESSAGE("-- quality achived --");
1895 if (it+1 == theNbIterations) {
1896 MESSAGE("-- Iteration limit exceeded --");
1898 } // smoothing iterations
1900 MESSAGE(" Face id: " << *fId <<
1901 " Nb iterstions: " << it <<
1902 " Displacement: " << maxDisplacement <<
1903 " Aspect Ratio " << maxRatio);
1905 // ---------------------------------------
1906 // new nodes positions are computed,
1907 // record movement in DS and set new UV
1908 // ---------------------------------------
1910 nodeToMove = setMovableNodes.begin();
1911 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1913 SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1914 aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1915 map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1916 if ( node_uv != uvMap.end() ) {
1917 gp_XY* uv = node_uv->second;
1919 ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1923 } // loop on face ids
1926 //=======================================================================
1927 //function : isReverse
1928 //purpose : Return true if normal of prevNodes is not co-directied with
1929 // gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1930 // iNotSame is where prevNodes and nextNodes are different
1931 //=======================================================================
1933 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1934 const SMDS_MeshNode* nextNodes[],
1938 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1939 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1941 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1942 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1943 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1944 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1946 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1947 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1948 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1949 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1951 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1953 return (vA ^ vB) * vN < 0.0;
1956 //=======================================================================
1957 //function : sweepElement
1959 //=======================================================================
1961 static void sweepElement(SMESHDS_Mesh* aMesh,
1962 const SMDS_MeshElement* elem,
1963 const vector<TNodeOfNodeListMapItr> & newNodesItVec,
1964 list<const SMDS_MeshElement*>& newElems)
1966 // Loop on elem nodes:
1967 // find new nodes and detect same nodes indices
1968 int nbNodes = elem->NbNodes();
1969 list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
1970 const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
1971 int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
1973 for ( iNode = 0; iNode < nbNodes; iNode++ )
1975 TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
1976 const SMDS_MeshNode* node = nnIt->first;
1977 const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
1978 if ( listNewNodes.empty() )
1981 itNN[ iNode ] = listNewNodes.begin();
1982 prevNod[ iNode ] = node;
1983 nextNod[ iNode ] = listNewNodes.front();
1984 if ( prevNod[ iNode ] != nextNod [ iNode ])
1985 iNotSameNode = iNode;
1991 if ( nbSame == nbNodes || nbSame > 2) {
1992 MESSAGE( " Too many same nodes of element " << elem->GetID() );
1996 int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
1998 iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
1999 iAfterSame = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2000 iOpposSame = ( iSameNode - 2 < 0 ? iSameNode + 2 : iSameNode - 2 );
2003 // check element orientation
2005 if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2006 //MESSAGE("Reversed elem " << elem );
2010 int iAB = iAfterSame + iBeforeSame;
2011 iBeforeSame = iAB - iBeforeSame;
2012 iAfterSame = iAB - iAfterSame;
2016 // make new elements
2017 int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
2018 for (iStep = 0; iStep < nbSteps; iStep++ )
2021 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2022 nextNod[ iNode ] = *itNN[ iNode ];
2025 SMDS_MeshElement* aNewElem = 0;
2032 aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2038 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2039 nextNod[ 1 ], nextNod[ 0 ] );
2041 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2042 nextNod[ iNotSameNode ] );
2045 case 3: { // TRIANGLE
2047 if ( nbSame == 0 ) // --- pentahedron
2048 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2049 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2051 else if ( nbSame == 1 ) // --- pyramid
2052 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2053 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2054 nextNod[ iSameNode ]);
2056 else // 2 same nodes: --- tetrahedron
2057 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2058 nextNod[ iNotSameNode ]);
2061 case 4: { // QUADRANGLE
2063 if ( nbSame == 0 ) // --- hexahedron
2064 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2065 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2067 else if ( nbSame == 1 ) // --- pyramid + pentahedron
2069 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2070 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2071 nextNod[ iSameNode ]);
2072 newElems.push_back( aNewElem );
2073 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2074 prevNod[ iBeforeSame ], nextNod[ iAfterSame ],
2075 nextNod[ iOpposSame ], nextNod[ iBeforeSame ] );
2077 else if ( nbSame == 2 ) // pentahedron
2079 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2080 // iBeforeSame is same too
2081 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2082 nextNod[ iOpposSame ], prevNod[ iSameNode ],
2083 prevNod[ iAfterSame ], nextNod[ iAfterSame ]);
2085 // iAfterSame is same too
2086 aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2087 nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2088 prevNod[ iOpposSame ], nextNod[ iOpposSame ]);
2093 // realized for extrusion only
2094 vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2095 vector<int> quantities (nbNodes + 2);
2097 quantities[0] = nbNodes; // bottom of prism
2098 for (int inode = 0; inode < nbNodes; inode++) {
2099 polyedre_nodes[inode] = prevNod[inode];
2102 quantities[1] = nbNodes; // top of prism
2103 for (int inode = 0; inode < nbNodes; inode++) {
2104 polyedre_nodes[nbNodes + inode] = nextNod[inode];
2107 for (int iface = 0; iface < nbNodes; iface++) {
2108 quantities[iface + 2] = 4;
2109 int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2110 polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2111 polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2112 polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2113 polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2115 aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2119 newElems.push_back( aNewElem );
2121 // set new prev nodes
2122 for ( iNode = 0; iNode < nbNodes; iNode++ )
2123 prevNod[ iNode ] = nextNod[ iNode ];
2128 //=======================================================================
2129 //function : makeWalls
2130 //purpose : create 1D and 2D elements around swept elements
2131 //=======================================================================
2133 static void makeWalls (SMESHDS_Mesh* aMesh,
2134 TNodeOfNodeListMap & mapNewNodes,
2135 TElemOfElemListMap & newElemsMap,
2136 TElemOfVecOfNnlmiMap & elemNewNodesMap,
2137 set<const SMDS_MeshElement*>& elemSet)
2139 ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2141 // Find nodes belonging to only one initial element - sweep them to get edges.
2143 TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2144 for ( ; nList != mapNewNodes.end(); nList++ )
2146 const SMDS_MeshNode* node =
2147 static_cast<const SMDS_MeshNode*>( nList->first );
2148 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2149 int nbInitElems = 0;
2150 while ( eIt->more() && nbInitElems < 2 )
2151 if ( elemSet.find( eIt->next() ) != elemSet.end() )
2153 if ( nbInitElems < 2 ) {
2154 vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2155 list<const SMDS_MeshElement*> newEdges;
2156 sweepElement( aMesh, node, newNodesItVec, newEdges );
2160 // Make a ceiling for each element ie an equal element of last new nodes.
2161 // Find free links of faces - make edges and sweep them into faces.
2163 TElemOfElemListMap::iterator itElem = newElemsMap.begin();
2164 TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2165 for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2167 const SMDS_MeshElement* elem = itElem->first;
2168 vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2170 if ( elem->GetType() == SMDSAbs_Edge )
2172 // create a ceiling edge
2173 aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2174 vecNewNodes[ 1 ]->second.back() );
2176 if ( elem->GetType() != SMDSAbs_Face )
2179 bool hasFreeLinks = false;
2181 set<const SMDS_MeshElement*> avoidSet;
2182 avoidSet.insert( elem );
2184 // loop on a face nodes
2185 set<const SMDS_MeshNode*> aFaceLastNodes;
2186 int iNode, nbNodes = vecNewNodes.size();
2187 for ( iNode = 0; iNode < nbNodes; iNode++ )
2189 aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2190 // look for free links of a face
2191 int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2192 const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2193 const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2194 // check if a link is free
2195 if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2197 hasFreeLinks = true;
2198 // make an edge and a ceiling for a new edge
2199 if ( !aMesh->FindEdge( n1, n2 ))
2200 aMesh->AddEdge( n1, n2 );
2201 n1 = vecNewNodes[ iNode ]->second.back();
2202 n2 = vecNewNodes[ iNext ]->second.back();
2203 if ( !aMesh->FindEdge( n1, n2 ))
2204 aMesh->AddEdge( n1, n2 );
2207 // sweep free links into faces
2211 list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2212 int iStep, nbSteps = vecNewNodes[0]->second.size();
2213 int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2215 set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2216 for ( iNode = 0; iNode < nbNodes; iNode++ )
2217 initNodeSet.insert( vecNewNodes[ iNode ]->first );
2219 for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2221 list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2223 while ( iVol++ < volNb ) v++;
2224 // find indices of free faces of a volume
2226 SMDS_VolumeTool vTool( *v );
2227 int iF, nbF = vTool.NbFaces();
2228 for ( iF = 0; iF < nbF; iF ++ )
2229 if (vTool.IsFreeFace( iF ) &&
2230 vTool.GetFaceNodes( iF, faceNodeSet ) &&
2231 initNodeSet != faceNodeSet) // except an initial face
2232 fInd.push_back( iF );
2236 // create faces for all steps
2237 for ( iStep = 0; iStep < nbSteps; iStep++ )
2240 vTool.SetExternalNormal();
2241 list< int >::iterator ind = fInd.begin();
2242 for ( ; ind != fInd.end(); ind++ )
2244 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2245 switch ( vTool.NbFaceNodes( *ind ) ) {
2247 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2249 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2252 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2253 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2254 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2255 polygon_nodes[inode] = nodes[inode];
2257 aMesh->AddPolygonalFace(polygon_nodes);
2262 // go to the next volume
2264 while ( iVol++ < nbVolumesByStep ) v++;
2267 } // sweep free links into faces
2269 // make a ceiling face with a normal external to a volume
2271 SMDS_VolumeTool lastVol( itElem->second.back() );
2272 int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2275 lastVol.SetExternalNormal();
2276 const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2277 switch ( lastVol.NbFaceNodes( iF ) ) {
2279 if (!hasFreeLinks ||
2280 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2281 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2284 if (!hasFreeLinks ||
2285 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2286 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2290 int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2291 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2292 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2293 polygon_nodes[inode] = nodes[inode];
2295 if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2296 aMesh->AddPolygonalFace(polygon_nodes);
2302 } // loop on swept elements
2305 //=======================================================================
2306 //function : RotationSweep
2308 //=======================================================================
2310 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2311 const gp_Ax1& theAxis,
2312 const double theAngle,
2313 const int theNbSteps,
2314 const double theTol)
2316 MESSAGE( "RotationSweep()");
2318 aTrsf.SetRotation( theAxis, theAngle );
2320 gp_Lin aLine( theAxis );
2321 double aSqTol = theTol * theTol;
2323 SMESHDS_Mesh* aMesh = GetMeshDS();
2325 TNodeOfNodeListMap mapNewNodes;
2326 TElemOfVecOfNnlmiMap mapElemNewNodes;
2327 TElemOfElemListMap newElemsMap;
2330 set< const SMDS_MeshElement* >::iterator itElem;
2331 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2333 const SMDS_MeshElement* elem = (*itElem);
2336 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2337 newNodesItVec.reserve( elem->NbNodes() );
2339 // loop on elem nodes
2340 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2341 while ( itN->more() ) {
2343 // check if a node has been already sweeped
2344 const SMDS_MeshNode* node =
2345 static_cast<const SMDS_MeshNode*>( itN->next() );
2346 TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2347 if ( nIt == mapNewNodes.end() )
2349 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2350 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2353 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2355 aXYZ.Coord( coord[0], coord[1], coord[2] );
2356 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2357 const SMDS_MeshNode * newNode = node;
2358 for ( int i = 0; i < theNbSteps; i++ ) {
2360 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2361 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2363 listNewNodes.push_back( newNode );
2366 newNodesItVec.push_back( nIt );
2368 // make new elements
2369 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2372 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2375 //=======================================================================
2376 //function : ExtrusionSweep
2378 //=======================================================================
2380 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
2381 const gp_Vec& theStep,
2382 const int theNbSteps)
2385 aTrsf.SetTranslation( theStep );
2387 SMESHDS_Mesh* aMesh = GetMeshDS();
2389 TNodeOfNodeListMap mapNewNodes;
2390 TElemOfVecOfNnlmiMap mapElemNewNodes;
2391 TElemOfElemListMap newElemsMap;
2394 set< const SMDS_MeshElement* >::iterator itElem;
2395 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2397 // check element type
2398 const SMDS_MeshElement* elem = (*itElem);
2402 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2403 newNodesItVec.reserve( elem->NbNodes() );
2405 // loop on elem nodes
2406 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2407 while ( itN->more() ) {
2409 // check if a node has been already sweeped
2410 const SMDS_MeshNode* node =
2411 static_cast<const SMDS_MeshNode*>( itN->next() );
2412 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2413 if ( nIt == mapNewNodes.end() )
2415 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2416 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2419 double coord[] = { node->X(), node->Y(), node->Z() };
2420 for ( int i = 0; i < theNbSteps; i++ ) {
2421 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2422 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2423 listNewNodes.push_back( newNode );
2426 newNodesItVec.push_back( nIt );
2428 // make new elements
2429 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2431 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2434 //=======================================================================
2435 //class : SMESH_MeshEditor_PathPoint
2436 //purpose : auxiliary class
2437 //=======================================================================
2438 class SMESH_MeshEditor_PathPoint {
2440 SMESH_MeshEditor_PathPoint() {
2441 myPnt.SetCoord(99., 99., 99.);
2442 myTgt.SetCoord(1.,0.,0.);
2446 void SetPnt(const gp_Pnt& aP3D){
2449 void SetTangent(const gp_Dir& aTgt){
2452 void SetAngle(const double& aBeta){
2455 void SetParameter(const double& aPrm){
2458 const gp_Pnt& Pnt()const{
2461 const gp_Dir& Tangent()const{
2464 double Angle()const{
2467 double Parameter()const{
2478 //=======================================================================
2479 //function : ExtrusionAlongTrack
2481 //=======================================================================
2482 SMESH_MeshEditor::Extrusion_Error
2483 SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2484 SMESH_subMesh* theTrack,
2485 const SMDS_MeshNode* theN1,
2486 const bool theHasAngles,
2487 std::list<double>& theAngles,
2488 const bool theHasRefPoint,
2489 const gp_Pnt& theRefPoint)
2491 MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2492 int j, aNbTP, aNbE, aNb;
2493 double aT1, aT2, aT, aAngle, aX, aY, aZ;
2494 std::list<double> aPrms;
2495 std::list<double>::iterator aItD;
2496 std::set< const SMDS_MeshElement* >::iterator itElem;
2498 Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2502 Handle(Geom_Curve) aC3D;
2503 TopoDS_Edge aTrackEdge;
2504 TopoDS_Vertex aV1, aV2;
2506 SMDS_ElemIteratorPtr aItE;
2507 SMDS_NodeIteratorPtr aItN;
2508 SMDSAbs_ElementType aTypeE;
2510 TNodeOfNodeListMap mapNewNodes;
2511 TElemOfVecOfNnlmiMap mapElemNewNodes;
2512 TElemOfElemListMap newElemsMap;
2515 aTolVec2=aTolVec*aTolVec;
2518 aNbE = theElements.size();
2521 return EXTR_NO_ELEMENTS;
2523 // 1.1 Track Pattern
2526 SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2528 aItE = pSubMeshDS->GetElements();
2529 while ( aItE->more() ) {
2530 const SMDS_MeshElement* pE = aItE->next();
2531 aTypeE = pE->GetType();
2532 // Pattern must contain links only
2533 if ( aTypeE != SMDSAbs_Edge )
2534 return EXTR_PATH_NOT_EDGE;
2537 const TopoDS_Shape& aS = theTrack->GetSubShape();
2538 // Sub shape for the Pattern must be an Edge
2539 if ( aS.ShapeType() != TopAbs_EDGE )
2540 return EXTR_BAD_PATH_SHAPE;
2542 aTrackEdge = TopoDS::Edge( aS );
2543 // the Edge must not be degenerated
2544 if ( BRep_Tool::Degenerated( aTrackEdge ) )
2545 return EXTR_BAD_PATH_SHAPE;
2547 TopExp::Vertices( aTrackEdge, aV1, aV2 );
2548 aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2549 aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2551 aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2552 const SMDS_MeshNode* aN1 = aItN->next();
2554 aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2555 const SMDS_MeshNode* aN2 = aItN->next();
2557 // starting node must be aN1 or aN2
2558 if ( !( aN1 == theN1 || aN2 == theN1 ) )
2559 return EXTR_BAD_STARTING_NODE;
2561 aNbTP = pSubMeshDS->NbNodes() + 2;
2564 vector<double> aAngles( aNbTP );
2566 for ( j=0; j < aNbTP; ++j ) {
2570 if ( theHasAngles ) {
2571 aItD = theAngles.begin();
2572 for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2574 aAngles[j] = aAngle;
2578 // 2. Collect parameters on the track edge
2579 aPrms.push_back( aT1 );
2580 aPrms.push_back( aT2 );
2582 aItN = pSubMeshDS->GetNodes();
2583 while ( aItN->more() ) {
2584 const SMDS_MeshNode* pNode = aItN->next();
2585 const SMDS_EdgePosition* pEPos =
2586 static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2587 aT = pEPos->GetUParameter();
2588 aPrms.push_back( aT );
2593 if ( aN1 == theN1 ) {
2605 SMESH_MeshEditor_PathPoint aPP;
2606 vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2608 aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2610 aItD = aPrms.begin();
2611 for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2613 aC3D->D1( aT, aP3D, aVec );
2614 aL2 = aVec.SquareMagnitude();
2615 if ( aL2 < aTolVec2 )
2616 return EXTR_CANT_GET_TANGENT;
2618 gp_Dir aTgt( aVec );
2619 aAngle = aAngles[j];
2622 aPP.SetTangent( aTgt );
2623 aPP.SetAngle( aAngle );
2624 aPP.SetParameter( aT );
2628 // 3. Center of rotation aV0
2630 if ( !theHasRefPoint ) {
2632 aGC.SetCoord( 0.,0.,0. );
2634 itElem = theElements.begin();
2635 for ( ; itElem != theElements.end(); itElem++ ) {
2636 const SMDS_MeshElement* elem = (*itElem);
2638 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2639 while ( itN->more() ) {
2640 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2645 if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2646 list<const SMDS_MeshNode*> aLNx;
2647 mapNewNodes[node] = aLNx;
2649 gp_XYZ aXYZ( aX, aY, aZ );
2657 } // if (!theHasRefPoint) {
2658 mapNewNodes.clear();
2660 // 4. Processing the elements
2661 SMESHDS_Mesh* aMesh = GetMeshDS();
2663 for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2664 // check element type
2665 const SMDS_MeshElement* elem = (*itElem);
2666 aTypeE = elem->GetType();
2667 if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2670 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2671 newNodesItVec.reserve( elem->NbNodes() );
2673 // loop on elem nodes
2674 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2675 while ( itN->more() ) {
2677 // check if a node has been already processed
2678 const SMDS_MeshNode* node =
2679 static_cast<const SMDS_MeshNode*>( itN->next() );
2680 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2681 if ( nIt == mapNewNodes.end() ) {
2682 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2683 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2686 aX = node->X(); aY = node->Y(); aZ = node->Z();
2688 Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2689 gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2690 gp_Ax1 anAx1, anAxT1T0;
2691 gp_Dir aDT1x, aDT0x, aDT1T0;
2696 aPN0.SetCoord(aX, aY, aZ);
2698 const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2700 aDT0x= aPP0.Tangent();
2702 for ( j = 1; j < aNbTP; ++j ) {
2703 const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2705 aDT1x = aPP1.Tangent();
2706 aAngle1x = aPP1.Angle();
2708 gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2710 gp_Vec aV01x( aP0x, aP1x );
2711 aTrsf.SetTranslation( aV01x );
2714 aV1x = aV0x.Transformed( aTrsf );
2715 aPN1 = aPN0.Transformed( aTrsf );
2717 // rotation 1 [ T1,T0 ]
2718 aAngleT1T0=-aDT1x.Angle( aDT0x );
2719 if (fabs(aAngleT1T0) > aTolAng) {
2721 anAxT1T0.SetLocation( aV1x );
2722 anAxT1T0.SetDirection( aDT1T0 );
2723 aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2725 aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2729 if ( theHasAngles ) {
2730 anAx1.SetLocation( aV1x );
2731 anAx1.SetDirection( aDT1x );
2732 aTrsfRot.SetRotation( anAx1, aAngle1x );
2734 aPN1 = aPN1.Transformed( aTrsfRot );
2741 const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2742 listNewNodes.push_back( newNode );
2750 newNodesItVec.push_back( nIt );
2752 // make new elements
2753 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2756 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2761 //=======================================================================
2762 //function : Transform
2764 //=======================================================================
2766 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2767 const gp_Trsf& theTrsf,
2771 switch ( theTrsf.Form() ) {
2777 needReverse = false;
2780 SMESHDS_Mesh* aMesh = GetMeshDS();
2782 // map old node to new one
2783 TNodeNodeMap nodeMap;
2785 // elements sharing moved nodes; those of them which have all
2786 // nodes mirrored but are not in theElems are to be reversed
2787 set<const SMDS_MeshElement*> inverseElemSet;
2790 set< const SMDS_MeshElement* >::iterator itElem;
2791 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2793 const SMDS_MeshElement* elem = (*itElem);
2797 // loop on elem nodes
2798 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2799 while ( itN->more() ) {
2801 // check if a node has been already transformed
2802 const SMDS_MeshNode* node =
2803 static_cast<const SMDS_MeshNode*>( itN->next() );
2804 if (nodeMap.find( node ) != nodeMap.end() )
2808 coord[0] = node->X();
2809 coord[1] = node->Y();
2810 coord[2] = node->Z();
2811 theTrsf.Transforms( coord[0], coord[1], coord[2] );
2812 const SMDS_MeshNode * newNode = node;
2814 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2816 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2817 // node position on shape becomes invalid
2818 const_cast< SMDS_MeshNode* > ( node )->SetPosition
2819 ( SMDS_SpacePosition::originSpacePosition() );
2821 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2823 // keep inverse elements
2824 if ( !theCopy && needReverse ) {
2825 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2826 while ( invElemIt->more() )
2827 inverseElemSet.insert( invElemIt->next() );
2832 // either new elements are to be created
2833 // or a mirrored element are to be reversed
2834 if ( !theCopy && !needReverse)
2837 if ( !inverseElemSet.empty()) {
2838 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2839 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2840 theElems.insert( *invElemIt );
2843 // replicate or reverse elements
2846 REV_TETRA = 0, // = nbNodes - 4
2847 REV_PYRAMID = 1, // = nbNodes - 4
2848 REV_PENTA = 2, // = nbNodes - 4
2850 REV_HEXA = 4, // = nbNodes - 4
2854 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
2855 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
2856 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
2857 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
2858 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
2859 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
2862 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2864 const SMDS_MeshElement* elem = (*itElem);
2865 if ( !elem || elem->GetType() == SMDSAbs_Node )
2868 int nbNodes = elem->NbNodes();
2869 int elemType = elem->GetType();
2871 if (elem->IsPoly()) {
2872 // Polygon or Polyhedral Volume
2873 switch ( elemType ) {
2876 vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2878 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2879 while (itN->more()) {
2880 const SMDS_MeshNode* node =
2881 static_cast<const SMDS_MeshNode*>(itN->next());
2882 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2883 if (nodeMapIt == nodeMap.end())
2884 break; // not all nodes transformed
2886 // reverse mirrored faces and volumes
2887 poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2889 poly_nodes[iNode] = (*nodeMapIt).second;
2893 if ( iNode != nbNodes )
2894 continue; // not all nodes transformed
2897 aMesh->AddPolygonalFace(poly_nodes);
2899 aMesh->ChangePolygonNodes(elem, poly_nodes);
2903 case SMDSAbs_Volume:
2905 // ATTENTION: Reversing is not yet done!!!
2906 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2907 (const SMDS_PolyhedralVolumeOfNodes*) elem;
2909 MESSAGE("Warning: bad volumic element");
2913 vector<const SMDS_MeshNode*> poly_nodes;
2914 vector<int> quantities;
2916 bool allTransformed = true;
2917 int nbFaces = aPolyedre->NbFaces();
2918 for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2919 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2920 for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2921 const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
2922 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2923 if (nodeMapIt == nodeMap.end()) {
2924 allTransformed = false; // not all nodes transformed
2926 poly_nodes.push_back((*nodeMapIt).second);
2929 quantities.push_back(nbFaceNodes);
2931 if ( !allTransformed )
2932 continue; // not all nodes transformed
2935 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
2937 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
2947 int* i = index[ FORWARD ];
2948 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2949 if ( elemType == SMDSAbs_Face )
2950 i = index[ REV_FACE ];
2952 i = index[ nbNodes - 4 ];
2954 // find transformed nodes
2955 const SMDS_MeshNode* nodes[8];
2957 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2958 while ( itN->more() )
2960 const SMDS_MeshNode* node =
2961 static_cast<const SMDS_MeshNode*>( itN->next() );
2962 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
2963 if ( nodeMapIt == nodeMap.end() )
2964 break; // not all nodes transformed
2965 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
2967 if ( iNode != nbNodes )
2968 continue; // not all nodes transformed
2972 // add a new element
2973 switch ( elemType ) {
2975 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
2979 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2981 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
2983 case SMDSAbs_Volume:
2985 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
2986 else if ( nbNodes == 8 )
2987 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2988 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
2989 else if ( nbNodes == 6 )
2990 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2991 nodes[ 4 ], nodes[ 5 ]);
2992 else if ( nbNodes == 5 )
2993 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3001 // reverse element as it was reversed by transformation
3003 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3008 //=======================================================================
3009 //function : FindCoincidentNodes
3010 //purpose : Return list of group of nodes close to each other within theTolerance
3011 // Search among theNodes or in the whole mesh if theNodes is empty.
3012 //=======================================================================
3014 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3015 const double theTolerance,
3016 TListOfListOfNodes & theGroupsOfNodes)
3018 double tol2 = theTolerance * theTolerance;
3020 list<const SMDS_MeshNode*> nodes;
3021 if ( theNodes.empty() )
3022 { // get all nodes in the mesh
3023 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3024 while ( nIt->more() )
3025 nodes.push_back( nIt->next() );
3029 nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3032 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3033 for ( ; it1 != nodes.end(); it1++ )
3035 const SMDS_MeshNode* n1 = *it1;
3036 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3038 list<const SMDS_MeshNode*> * groupPtr = 0;
3040 for ( it2++; it2 != nodes.end(); it2++ )
3042 const SMDS_MeshNode* n2 = *it2;
3043 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3044 if ( p1.SquareDistance( p2 ) <= tol2 )
3047 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3048 groupPtr = & theGroupsOfNodes.back();
3049 groupPtr->push_back( n1 );
3051 groupPtr->push_back( n2 );
3052 it2 = nodes.erase( it2 );
3059 //=======================================================================
3060 //function : SimplifyFace
3062 //=======================================================================
3063 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3064 vector<const SMDS_MeshNode *>& poly_nodes,
3065 vector<int>& quantities) const
3067 int nbNodes = faceNodes.size();
3072 set<const SMDS_MeshNode*> nodeSet;
3074 // get simple seq of nodes
3075 const SMDS_MeshNode* simpleNodes[ nbNodes ];
3076 int iSimple = 0, nbUnique = 0;
3078 simpleNodes[iSimple++] = faceNodes[0];
3080 for (int iCur = 1; iCur < nbNodes; iCur++) {
3081 if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3082 simpleNodes[iSimple++] = faceNodes[iCur];
3083 if (nodeSet.insert( faceNodes[iCur] ).second)
3087 int nbSimple = iSimple;
3088 if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3098 bool foundLoop = (nbSimple > nbUnique);
3101 set<const SMDS_MeshNode*> loopSet;
3102 for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3103 const SMDS_MeshNode* n = simpleNodes[iSimple];
3104 if (!loopSet.insert( n ).second) {
3108 int iC = 0, curLast = iSimple;
3109 for (; iC < curLast; iC++) {
3110 if (simpleNodes[iC] == n) break;
3112 int loopLen = curLast - iC;
3114 // create sub-element
3116 quantities.push_back(loopLen);
3117 for (; iC < curLast; iC++) {
3118 poly_nodes.push_back(simpleNodes[iC]);
3121 // shift the rest nodes (place from the first loop position)
3122 for (iC = curLast + 1; iC < nbSimple; iC++) {
3123 simpleNodes[iC - loopLen] = simpleNodes[iC];
3125 nbSimple -= loopLen;
3128 } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3129 } // while (foundLoop)
3133 quantities.push_back(iSimple);
3134 for (int i = 0; i < iSimple; i++)
3135 poly_nodes.push_back(simpleNodes[i]);
3141 //=======================================================================
3142 //function : MergeNodes
3143 //purpose : In each group, the cdr of nodes are substituted by the first one
3145 //=======================================================================
3147 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3149 SMESHDS_Mesh* aMesh = GetMeshDS();
3151 TNodeNodeMap nodeNodeMap; // node to replace - new node
3152 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3153 list< int > rmElemIds, rmNodeIds;
3155 // Fill nodeNodeMap and elems
3157 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3158 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3160 list<const SMDS_MeshNode*>& nodes = *grIt;
3161 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3162 const SMDS_MeshNode* nToKeep = *nIt;
3163 for ( ; nIt != nodes.end(); nIt++ )
3165 const SMDS_MeshNode* nToRemove = *nIt;
3166 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3167 if ( nToRemove != nToKeep ) {
3168 rmNodeIds.push_back( nToRemove->GetID() );
3169 AddToSameGroups( nToKeep, nToRemove, aMesh );
3172 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3173 while ( invElemIt->more() )
3174 elems.insert( invElemIt->next() );
3177 // Change element nodes or remove an element
3179 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3180 for ( ; eIt != elems.end(); eIt++ )
3182 const SMDS_MeshElement* elem = *eIt;
3183 int nbNodes = elem->NbNodes();
3184 int aShapeId = FindShape( elem );
3186 set<const SMDS_MeshNode*> nodeSet;
3187 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3188 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3190 // get new seq of nodes
3191 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3192 while ( itN->more() )
3194 const SMDS_MeshNode* n =
3195 static_cast<const SMDS_MeshNode*>( itN->next() );
3197 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3198 if ( nnIt != nodeNodeMap.end() ) { // n sticks
3200 iRepl[ nbRepl++ ] = iCur;
3202 curNodes[ iCur ] = n;
3203 bool isUnique = nodeSet.insert( n ).second;
3205 uniqueNodes[ iUnique++ ] = n;
3209 // Analyse element topology after replacement
3212 int nbUniqueNodes = nodeSet.size();
3213 if ( nbNodes != nbUniqueNodes ) // some nodes stick
3215 // Polygons and Polyhedral volumes
3216 if (elem->IsPoly()) {
3218 if (elem->GetType() == SMDSAbs_Face) {
3220 vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3222 for (; inode < nbNodes; inode++) {
3223 face_nodes[inode] = curNodes[inode];
3226 vector<const SMDS_MeshNode *> polygons_nodes;
3227 vector<int> quantities;
3228 int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3232 for (int iface = 0; iface < nbNew - 1; iface++) {
3233 int nbNodes = quantities[iface];
3234 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3235 for (int ii = 0; ii < nbNodes; ii++, inode++) {
3236 poly_nodes[ii] = polygons_nodes[inode];
3238 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3240 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3242 aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3244 rmElemIds.push_back(elem->GetID());
3247 } else if (elem->GetType() == SMDSAbs_Volume) {
3248 // Polyhedral volume
3249 if (nbUniqueNodes < 4) {
3250 rmElemIds.push_back(elem->GetID());
3252 // each face has to be analized in order to check volume validity
3253 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3254 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3256 int nbFaces = aPolyedre->NbFaces();
3258 vector<const SMDS_MeshNode *> poly_nodes;
3259 vector<int> quantities;
3261 for (int iface = 1; iface <= nbFaces; iface++) {
3262 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3263 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3265 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3266 const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3267 TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3268 if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3269 faceNode = (*nnIt).second;
3271 faceNodes[inode - 1] = faceNode;
3274 SimplifyFace(faceNodes, poly_nodes, quantities);
3277 if (quantities.size() > 3) {
3278 // to be done: remove coincident faces
3281 if (quantities.size() > 3)
3282 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3284 rmElemIds.push_back(elem->GetID());
3287 rmElemIds.push_back(elem->GetID());
3297 switch ( nbNodes ) {
3298 case 2: ///////////////////////////////////// EDGE
3299 isOk = false; break;
3300 case 3: ///////////////////////////////////// TRIANGLE
3301 isOk = false; break;
3303 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3305 else { //////////////////////////////////// QUADRANGLE
3306 if ( nbUniqueNodes < 3 )
3308 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3309 isOk = false; // opposite nodes stick
3312 case 6: ///////////////////////////////////// PENTAHEDRON
3313 if ( nbUniqueNodes == 4 ) {
3314 // ---------------------------------> tetrahedron
3316 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3317 // all top nodes stick: reverse a bottom
3318 uniqueNodes[ 0 ] = curNodes [ 1 ];
3319 uniqueNodes[ 1 ] = curNodes [ 0 ];
3321 else if (nbRepl == 3 &&
3322 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3323 // all bottom nodes stick: set a top before
3324 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3325 uniqueNodes[ 0 ] = curNodes [ 3 ];
3326 uniqueNodes[ 1 ] = curNodes [ 4 ];
3327 uniqueNodes[ 2 ] = curNodes [ 5 ];
3329 else if (nbRepl == 4 &&
3330 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3331 // a lateral face turns into a line: reverse a bottom
3332 uniqueNodes[ 0 ] = curNodes [ 1 ];
3333 uniqueNodes[ 1 ] = curNodes [ 0 ];
3338 else if ( nbUniqueNodes == 5 ) {
3339 // PENTAHEDRON --------------------> 2 tetrahedrons
3340 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3341 // a bottom node sticks with a linked top one
3343 SMDS_MeshElement* newElem =
3344 aMesh->AddVolume(curNodes[ 3 ],
3347 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3349 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3350 // 2. : reverse a bottom
3351 uniqueNodes[ 0 ] = curNodes [ 1 ];
3352 uniqueNodes[ 1 ] = curNodes [ 0 ];
3361 case 8: { //////////////////////////////////// HEXAHEDRON
3363 SMDS_VolumeTool hexa (elem);
3364 hexa.SetExternalNormal();
3365 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3366 //////////////////////// ---> tetrahedron
3367 for ( int iFace = 0; iFace < 6; iFace++ ) {
3368 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3369 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3370 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3371 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3372 // one face turns into a point ...
3373 int iOppFace = hexa.GetOppFaceIndex( iFace );
3374 ind = hexa.GetFaceNodesIndices( iOppFace );
3376 iUnique = 2; // reverse a tetrahedron bottom
3377 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3378 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3380 else if ( iUnique >= 0 )
3381 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3383 if ( nbStick == 1 ) {
3384 // ... and the opposite one - into a triangle.
3386 ind = hexa.GetFaceNodesIndices( iFace );
3387 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3394 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3395 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3396 for ( int iFace = 0; iFace < 6; iFace++ ) {
3397 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3398 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3399 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3400 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3401 // one face turns into a point ...
3402 int iOppFace = hexa.GetOppFaceIndex( iFace );
3403 ind = hexa.GetFaceNodesIndices( iOppFace );
3405 iUnique = 2; // reverse a tetrahedron 1 bottom
3406 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3407 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3409 else if ( iUnique >= 0 )
3410 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3412 if ( nbStick == 0 ) {
3413 // ... and the opposite one is a quadrangle
3415 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3416 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3419 SMDS_MeshElement* newElem =
3420 aMesh->AddVolume(curNodes[ind[ 0 ]],
3423 curNodes[indTop[ 0 ]]);
3425 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3432 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3433 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3434 // find indices of quad and tri faces
3435 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3436 for ( iFace = 0; iFace < 6; iFace++ ) {
3437 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3439 for ( iCur = 0; iCur < 4; iCur++ )
3440 nodeSet.insert( curNodes[ind[ iCur ]] );
3441 nbUniqueNodes = nodeSet.size();
3442 if ( nbUniqueNodes == 3 )
3443 iTriFace[ nbTri++ ] = iFace;
3444 else if ( nbUniqueNodes == 4 )
3445 iQuadFace[ nbQuad++ ] = iFace;
3447 if (nbQuad == 2 && nbTri == 4 &&
3448 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3449 // 2 opposite quadrangles stuck with a diagonal;
3450 // sample groups of merged indices: (0-4)(2-6)
3451 // --------------------------------------------> 2 tetrahedrons
3452 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3453 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3454 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3455 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3456 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3457 // stuck with 0-2 diagonal
3465 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3466 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3467 // stuck with 1-3 diagonal
3479 uniqueNodes[ 0 ] = curNodes [ i0 ];
3480 uniqueNodes[ 1 ] = curNodes [ i1d ];
3481 uniqueNodes[ 2 ] = curNodes [ i3d ];
3482 uniqueNodes[ 3 ] = curNodes [ i0t ];
3485 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3490 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3493 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3494 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3495 // --------------------------------------------> prism
3496 // find 2 opposite triangles
3498 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3499 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3500 // find indices of kept and replaced nodes
3501 // and fill unique nodes of 2 opposite triangles
3502 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3503 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3504 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3505 // fill unique nodes
3508 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3509 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
3510 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3512 // iCur of a linked node of the opposite face (make normals co-directed):
3513 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3514 // check that correspondent corners of triangles are linked
3515 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3518 uniqueNodes[ iUnique ] = n;
3519 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3528 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3534 } // switch ( nbNodes )
3536 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3539 if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3540 // Change nodes of polyedre
3541 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3542 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3544 int nbFaces = aPolyedre->NbFaces();
3546 vector<const SMDS_MeshNode *> poly_nodes;
3547 vector<int> quantities (nbFaces);
3549 for (int iface = 1; iface <= nbFaces; iface++) {
3550 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3551 quantities[iface - 1] = nbFaceNodes;
3553 for (inode = 1; inode <= nbFaceNodes; inode++) {
3554 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3556 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3557 if (nnIt != nodeNodeMap.end()) { // curNode sticks
3558 curNode = (*nnIt).second;
3560 poly_nodes.push_back(curNode);
3563 aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3566 // Change regular element or polygon
3567 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3570 // Remove invalid regular element or invalid polygon
3571 rmElemIds.push_back( elem->GetID() );
3574 } // loop on elements
3576 // Remove equal nodes and bad elements
3578 Remove( rmNodeIds, true );
3579 Remove( rmElemIds, false );
3583 //=======================================================================
3584 //function : MergeEqualElements
3585 //purpose : Remove all but one of elements built on the same nodes.
3586 //=======================================================================
3588 void SMESH_MeshEditor::MergeEqualElements()
3590 SMESHDS_Mesh* aMesh = GetMeshDS();
3592 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
3593 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
3594 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3596 list< int > rmElemIds; // IDs of elems to remove
3598 for ( int iDim = 1; iDim <= 3; iDim++ ) {
3600 set< set <const SMDS_MeshElement*> > setOfNodeSet;
3604 const SMDS_MeshElement* elem = 0;
3606 if ( eIt->more() ) elem = eIt->next();
3607 } else if ( iDim == 2 ) {
3608 if ( fIt->more() ) elem = fIt->next();
3610 if ( vIt->more() ) elem = vIt->next();
3615 set <const SMDS_MeshElement*> nodeSet;
3616 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3617 while ( nodeIt->more() )
3618 nodeSet.insert( nodeIt->next() );
3621 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3623 rmElemIds.push_back( elem->GetID() );
3627 Remove( rmElemIds, false );
3630 //=======================================================================
3631 //function : FindFaceInSet
3632 //purpose : Return a face having linked nodes n1 and n2 and which is
3633 // - not in avoidSet,
3634 // - in elemSet provided that !elemSet.empty()
3635 //=======================================================================
3637 const SMDS_MeshElement*
3638 SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode* n1,
3639 const SMDS_MeshNode* n2,
3640 const set<const SMDS_MeshElement*>& elemSet,
3641 const set<const SMDS_MeshElement*>& avoidSet)
3644 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3645 while ( invElemIt->more() ) { // loop on inverse elements of n1
3646 const SMDS_MeshElement* elem = invElemIt->next();
3647 if (elem->GetType() != SMDSAbs_Face ||
3648 avoidSet.find( elem ) != avoidSet.end() )
3650 if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3652 // get face nodes and find index of n1
3653 int i1, nbN = elem->NbNodes(), iNode = 0;
3654 const SMDS_MeshNode* faceNodes[ nbN ], *n;
3655 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3656 while ( nIt->more() ) {
3657 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3658 if ( faceNodes[ iNode++ ] == n1 )
3661 // find a n2 linked to n1
3662 for ( iNode = 0; iNode < 2; iNode++ ) {
3663 if ( iNode ) // node before n1
3664 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3665 else // node after n1
3666 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3674 //=======================================================================
3675 //function : findAdjacentFace
3677 //=======================================================================
3679 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3680 const SMDS_MeshNode* n2,
3681 const SMDS_MeshElement* elem)
3683 set<const SMDS_MeshElement*> elemSet, avoidSet;
3685 avoidSet.insert ( elem );
3686 return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3689 //=======================================================================
3690 //function : findFreeBorder
3692 //=======================================================================
3694 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3696 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
3697 const SMDS_MeshNode* theSecondNode,
3698 const SMDS_MeshNode* theLastNode,
3699 list< const SMDS_MeshNode* > & theNodes,
3700 list< const SMDS_MeshElement* > & theFaces)
3702 if ( !theFirstNode || !theSecondNode )
3704 // find border face between theFirstNode and theSecondNode
3705 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3709 theFaces.push_back( curElem );
3710 theNodes.push_back( theFirstNode );
3711 theNodes.push_back( theSecondNode );
3713 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3714 set < const SMDS_MeshElement* > foundElems;
3715 bool needTheLast = ( theLastNode != 0 );
3717 while ( nStart != theLastNode )
3719 if ( nStart == theFirstNode )
3720 return !needTheLast;
3722 // find all free border faces sharing form nStart
3724 list< const SMDS_MeshElement* > curElemList;
3725 list< const SMDS_MeshNode* > nStartList;
3726 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3727 while ( invElemIt->more() ) {
3728 const SMDS_MeshElement* e = invElemIt->next();
3729 if ( e == curElem || foundElems.insert( e ).second )
3732 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3733 int iNode = 0, nbNodes = e->NbNodes();
3734 while ( nIt->more() )
3735 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3736 nodes[ iNode ] = nodes[ 0 ];
3738 for ( iNode = 0; iNode < nbNodes; iNode++ )
3739 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3740 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3741 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3743 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3744 curElemList.push_back( e );
3748 // analyse the found
3750 int nbNewBorders = curElemList.size();
3751 if ( nbNewBorders == 0 ) {
3752 // no free border furthermore
3753 return !needTheLast;
3755 else if ( nbNewBorders == 1 ) {
3756 // one more element found
3758 nStart = nStartList.front();
3759 curElem = curElemList.front();
3760 theFaces.push_back( curElem );
3761 theNodes.push_back( nStart );
3764 // several continuations found
3765 list< const SMDS_MeshElement* >::iterator curElemIt;
3766 list< const SMDS_MeshNode* >::iterator nStartIt;
3767 // check if one of them reached the last node
3768 if ( needTheLast ) {
3769 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3770 curElemIt!= curElemList.end();
3771 curElemIt++, nStartIt++ )
3772 if ( *nStartIt == theLastNode ) {
3773 theFaces.push_back( *curElemIt );
3774 theNodes.push_back( *nStartIt );
3778 // find the best free border by the continuations
3779 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
3780 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3781 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3782 curElemIt!= curElemList.end();
3783 curElemIt++, nStartIt++ )
3785 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3786 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3787 // find one more free border
3788 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3792 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3793 // choice: clear a worse one
3794 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3795 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3796 contNodes[ iWorse ].clear();
3797 contFaces[ iWorse ].clear();
3800 if ( contNodes[0].empty() && contNodes[1].empty() )
3803 // append the best free border
3804 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3805 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3806 theNodes.pop_back(); // remove nIgnore
3807 theNodes.pop_back(); // remove nStart
3808 theFaces.pop_back(); // remove curElem
3809 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3810 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3811 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3812 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3815 } // several continuations found
3816 } // while ( nStart != theLastNode )
3821 //=======================================================================
3822 //function : CheckFreeBorderNodes
3823 //purpose : Return true if the tree nodes are on a free border
3824 //=======================================================================
3826 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3827 const SMDS_MeshNode* theNode2,
3828 const SMDS_MeshNode* theNode3)
3830 list< const SMDS_MeshNode* > nodes;
3831 list< const SMDS_MeshElement* > faces;
3832 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3835 //=======================================================================
3836 //function : SewFreeBorder
3838 //=======================================================================
3840 SMESH_MeshEditor::Sew_Error
3841 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3842 const SMDS_MeshNode* theBordSecondNode,
3843 const SMDS_MeshNode* theBordLastNode,
3844 const SMDS_MeshNode* theSideFirstNode,
3845 const SMDS_MeshNode* theSideSecondNode,
3846 const SMDS_MeshNode* theSideThirdNode,
3847 const bool theSideIsFreeBorder,
3848 const bool toCreatePolygons,
3849 const bool toCreatePolyedrs)
3851 MESSAGE("::SewFreeBorder()");
3852 Sew_Error aResult = SEW_OK;
3854 // ====================================
3855 // find side nodes and elements
3856 // ====================================
3858 list< const SMDS_MeshNode* > nSide[ 2 ];
3859 list< const SMDS_MeshElement* > eSide[ 2 ];
3860 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3861 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3865 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3866 nSide[0], eSide[0])) {
3867 MESSAGE(" Free Border 1 not found " );
3868 aResult = SEW_BORDER1_NOT_FOUND;
3870 if (theSideIsFreeBorder)
3874 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3875 nSide[1], eSide[1])) {
3876 MESSAGE(" Free Border 2 not found " );
3877 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3880 if ( aResult != SEW_OK )
3883 if (!theSideIsFreeBorder)
3888 // -------------------------------------------------------------------------
3890 // 1. If nodes to merge are not coincident, move nodes of the free border
3891 // from the coord sys defined by the direction from the first to last
3892 // nodes of the border to the correspondent sys of the side 2
3893 // 2. On the side 2, find the links most co-directed with the correspondent
3894 // links of the free border
3895 // -------------------------------------------------------------------------
3897 // 1. Since sewing may brake if there are volumes to split on the side 2,
3898 // we wont move nodes but just compute new coordinates for them
3899 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3900 TNodeXYZMap nBordXYZ;
3901 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3902 list< const SMDS_MeshNode* >::iterator nBordIt;
3904 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3905 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3906 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3907 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3908 double tol2 = 1.e-8;
3909 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3910 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3912 // Need node movement.
3914 // find X and Z axes to create trsf
3915 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3917 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3919 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3922 gp_Ax3 toBordAx( Pb1, Zb, X );
3923 gp_Ax3 fromSideAx( Ps1, Zs, X );
3924 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
3926 gp_Trsf toBordSys, fromSide2Sys;
3927 toBordSys.SetTransformation( toBordAx );
3928 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
3929 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
3932 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3933 const SMDS_MeshNode* n = *nBordIt;
3934 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
3935 toBordSys.Transforms( xyz );
3936 fromSide2Sys.Transforms( xyz );
3937 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
3942 // just insert nodes XYZ in the nBordXYZ map
3943 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3944 const SMDS_MeshNode* n = *nBordIt;
3945 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
3949 // 2. On the side 2, find the links most co-directed with the correspondent
3950 // links of the free border
3952 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
3953 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
3954 sideNodes.push_back( theSideFirstNode );
3956 bool hasVolumes = false;
3957 LinkID_Gen aLinkID_Gen( GetMeshDS() );
3958 set<long> foundSideLinkIDs, checkedLinkIDs;
3959 SMDS_VolumeTool volume;
3960 //const SMDS_MeshNode* faceNodes[ 4 ];
3962 const SMDS_MeshNode* sideNode;
3963 const SMDS_MeshElement* sideElem;
3964 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
3965 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
3966 nBordIt = bordNodes.begin();
3968 // border node position and border link direction to compare with
3969 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
3970 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
3971 // choose next side node by link direction or by closeness to
3972 // the current border node:
3973 bool searchByDir = ( *nBordIt != theBordLastNode );
3975 // find the next node on the Side 2
3977 double maxDot = -DBL_MAX, minDist = DBL_MAX;
3979 checkedLinkIDs.clear();
3980 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
3982 SMDS_ElemIteratorPtr invElemIt
3983 = prevSideNode->GetInverseElementIterator();
3984 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
3985 const SMDS_MeshElement* elem = invElemIt->next();
3986 // prepare data for a loop on links, of a face or a volume
3987 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
3988 const SMDS_MeshNode* faceNodes[ nbNodes ];
3989 bool isVolume = volume.Set( elem );
3990 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
3991 if ( isVolume ) // --volume
3993 else if ( nbNodes > 2 ) { // --face
3994 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
3995 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3996 while ( nIt->more() ) {
3997 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3998 if ( nodes[ iNode++ ] == prevSideNode )
3999 iPrevNode = iNode - 1;
4001 // there are 2 links to check
4006 // loop on links, to be precise, on the second node of links
4007 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4008 const SMDS_MeshNode* n = nodes[ iNode ];
4010 if ( !volume.IsLinked( n, prevSideNode ))
4013 if ( iNode ) // a node before prevSideNode
4014 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4015 else // a node after prevSideNode
4016 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4018 // check if this link was already used
4019 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4020 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4021 if (!isJustChecked &&
4022 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4023 // test a link geometrically
4024 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4025 bool linkIsBetter = false;
4027 if ( searchByDir ) { // choose most co-directed link
4028 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4029 linkIsBetter = ( dot > maxDot );
4031 else { // choose link with the node closest to bordPos
4032 dist = ( nextXYZ - bordPos ).SquareModulus();
4033 linkIsBetter = ( dist < minDist );
4035 if ( linkIsBetter ) {
4044 } // loop on inverse elements of prevSideNode
4047 MESSAGE(" Cant find path by links of the Side 2 ");
4048 return SEW_BAD_SIDE_NODES;
4050 sideNodes.push_back( sideNode );
4051 sideElems.push_back( sideElem );
4052 foundSideLinkIDs.insert ( linkID );
4053 prevSideNode = sideNode;
4055 if ( *nBordIt == theBordLastNode )
4056 searchByDir = false;
4058 // find the next border link to compare with
4059 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4060 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4061 while ( *nBordIt != theBordLastNode && !searchByDir ) {
4062 prevBordNode = *nBordIt;
4064 bordPos = nBordXYZ[ *nBordIt ];
4065 bordDir = bordPos - nBordXYZ[ prevBordNode ];
4066 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4070 while ( sideNode != theSideSecondNode );
4072 if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4073 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4074 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4076 } // end nodes search on the side 2
4078 // ============================
4079 // sew the border to the side 2
4080 // ============================
4082 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
4083 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4085 TListOfListOfNodes nodeGroupsToMerge;
4086 if ( nbNodes[0] == nbNodes[1] ||
4087 ( theSideIsFreeBorder && !theSideThirdNode)) {
4089 // all nodes are to be merged
4091 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4092 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4093 nIt[0]++, nIt[1]++ )
4095 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4096 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4097 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4102 // insert new nodes into the border and the side to get equal nb of segments
4104 // get normalized parameters of nodes on the borders
4105 double param[ 2 ][ maxNbNodes ];
4107 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4108 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4109 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4110 const SMDS_MeshNode* nPrev = *nIt;
4111 double bordLength = 0;
4112 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4113 const SMDS_MeshNode* nCur = *nIt;
4114 gp_XYZ segment (nCur->X() - nPrev->X(),
4115 nCur->Y() - nPrev->Y(),
4116 nCur->Z() - nPrev->Z());
4117 double segmentLen = segment.Modulus();
4118 bordLength += segmentLen;
4119 param[ iBord ][ iNode ] = bordLength;
4122 // normalize within [0,1]
4123 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4124 param[ iBord ][ iNode ] /= bordLength;
4128 // loop on border segments
4129 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4130 int i[ 2 ] = { 0, 0 };
4131 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4132 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4134 TElemOfNodeListMap insertMap;
4135 TElemOfNodeListMap::iterator insertMapIt;
4137 // key: elem to insert nodes into
4138 // value: 2 nodes to insert between + nodes to be inserted
4140 bool next[ 2 ] = { false, false };
4142 // find min adjacent segment length after sewing
4143 double nextParam = 10., prevParam = 0;
4144 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4145 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4146 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4147 if ( i[ iBord ] > 0 )
4148 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4150 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4151 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4152 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4154 // choose to insert or to merge nodes
4155 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4156 if ( Abs( du ) <= minSegLen * 0.2 ) {
4159 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4160 const SMDS_MeshNode* n0 = *nIt[0];
4161 const SMDS_MeshNode* n1 = *nIt[1];
4162 nodeGroupsToMerge.back().push_back( n1 );
4163 nodeGroupsToMerge.back().push_back( n0 );
4164 // position of node of the border changes due to merge
4165 param[ 0 ][ i[0] ] += du;
4166 // move n1 for the sake of elem shape evaluation during insertion.
4167 // n1 will be removed by MergeNodes() anyway
4168 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4169 next[0] = next[1] = true;
4174 int intoBord = ( du < 0 ) ? 0 : 1;
4175 const SMDS_MeshElement* elem = *eIt[ intoBord ];
4176 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
4177 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
4178 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
4179 if ( intoBord == 1 ) {
4180 // move node of the border to be on a link of elem of the side
4181 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4182 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4183 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4184 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4185 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4187 insertMapIt = insertMap.find( elem );
4188 bool notFound = ( insertMapIt == insertMap.end() );
4189 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4191 // insert into another link of the same element:
4192 // 1. perform insertion into the other link of the elem
4193 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4194 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4195 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4196 InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4197 // 2. perform insertion into the link of adjacent faces
4199 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4201 InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4205 if (toCreatePolyedrs) {
4206 // perform insertion into the links of adjacent volumes
4207 UpdateVolumes(n12, n22, nodeList);
4209 // 3. find an element appeared on n1 and n2 after the insertion
4210 insertMap.erase( elem );
4211 elem = findAdjacentFace( n1, n2, 0 );
4213 if ( notFound || otherLink ) {
4214 // add element and nodes of the side into the insertMap
4215 insertMapIt = insertMap.insert
4216 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4217 (*insertMapIt).second.push_back( n1 );
4218 (*insertMapIt).second.push_back( n2 );
4220 // add node to be inserted into elem
4221 (*insertMapIt).second.push_back( nIns );
4222 next[ 1 - intoBord ] = true;
4225 // go to the next segment
4226 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4227 if ( next[ iBord ] ) {
4228 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4230 nPrev[ iBord ] = *nIt[ iBord ];
4231 nIt[ iBord ]++; i[ iBord ]++;
4235 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4237 // perform insertion of nodes into elements
4239 for (insertMapIt = insertMap.begin();
4240 insertMapIt != insertMap.end();
4243 const SMDS_MeshElement* elem = (*insertMapIt).first;
4244 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4245 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4246 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4248 InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4250 if ( !theSideIsFreeBorder ) {
4251 // look for and insert nodes into the faces adjacent to elem
4253 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4255 InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4260 if (toCreatePolyedrs) {
4261 // perform insertion into the links of adjacent volumes
4262 UpdateVolumes(n1, n2, nodeList);
4266 } // end: insert new nodes
4268 MergeNodes ( nodeGroupsToMerge );
4273 //=======================================================================
4274 //function : InsertNodesIntoLink
4275 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
4276 // and theBetweenNode2 and split theElement
4277 //=======================================================================
4279 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
4280 const SMDS_MeshNode* theBetweenNode1,
4281 const SMDS_MeshNode* theBetweenNode2,
4282 list<const SMDS_MeshNode*>& theNodesToInsert,
4283 const bool toCreatePoly)
4285 if ( theFace->GetType() != SMDSAbs_Face ) return;
4287 // find indices of 2 link nodes and of the rest nodes
4288 int iNode = 0, il1, il2, i3, i4;
4289 il1 = il2 = i3 = i4 = -1;
4290 const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4291 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4292 while ( nodeIt->more() ) {
4293 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4294 if ( n == theBetweenNode1 )
4296 else if ( n == theBetweenNode2 )
4302 nodes[ iNode++ ] = n;
4304 if ( il1 < 0 || il2 < 0 || i3 < 0 )
4307 // arrange link nodes to go one after another regarding the face orientation
4308 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4309 list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4314 aNodesToInsert.reverse();
4316 // check that not link nodes of a quadrangles are in good order
4317 int nbFaceNodes = theFace->NbNodes();
4318 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4324 if (toCreatePoly || theFace->IsPoly()) {
4327 vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4329 // add nodes of face up to first node of link
4331 nodeIt = theFace->nodesIterator();
4332 while ( nodeIt->more() && !isFLN ) {
4333 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4334 poly_nodes[iNode++] = n;
4335 if (n == nodes[il1]) {
4340 // add nodes to insert
4341 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4342 for (; nIt != aNodesToInsert.end(); nIt++) {
4343 poly_nodes[iNode++] = *nIt;
4346 // add nodes of face starting from last node of link
4347 while ( nodeIt->more() ) {
4348 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4349 poly_nodes[iNode++] = n;
4352 // edit or replace the face
4353 SMESHDS_Mesh *aMesh = GetMeshDS();
4355 if (theFace->IsPoly()) {
4356 aMesh->ChangePolygonNodes(theFace, poly_nodes);
4359 int aShapeId = FindShape( theFace );
4361 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4362 if ( aShapeId && newElem )
4363 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4365 aMesh->RemoveElement(theFace);
4370 // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4371 int nbLinkNodes = 2 + aNodesToInsert.size();
4372 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4373 linkNodes[ 0 ] = nodes[ il1 ];
4374 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4375 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4376 for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4377 linkNodes[ iNode++ ] = *nIt;
4379 // decide how to split a quadrangle: compare possible variants
4380 // and choose which of splits to be a quadrangle
4381 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4382 if ( nbFaceNodes == 3 )
4384 iBestQuad = nbSplits;
4387 else if ( nbFaceNodes == 4 )
4389 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4390 double aBestRate = DBL_MAX;
4391 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4393 double aBadRate = 0;
4394 // evaluate elements quality
4395 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4396 if ( iSplit == iQuad ) {
4397 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4401 aBadRate += getBadRate( &quad, aCrit );
4404 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4406 nodes[ iSplit < iQuad ? i4 : i3 ]);
4407 aBadRate += getBadRate( &tria, aCrit );
4411 if ( aBadRate < aBestRate ) {
4413 aBestRate = aBadRate;
4418 // create new elements
4419 SMESHDS_Mesh *aMesh = GetMeshDS();
4420 int aShapeId = FindShape( theFace );
4423 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4424 SMDS_MeshElement* newElem = 0;
4425 if ( iSplit == iBestQuad )
4426 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4431 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4433 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4434 if ( aShapeId && newElem )
4435 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4438 // change nodes of theFace
4439 const SMDS_MeshNode* newNodes[ 4 ];
4440 newNodes[ 0 ] = linkNodes[ i1 ];
4441 newNodes[ 1 ] = linkNodes[ i2 ];
4442 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4443 newNodes[ 3 ] = nodes[ i4 ];
4444 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4447 //=======================================================================
4448 //function : UpdateVolumes
4450 //=======================================================================
4451 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode* theBetweenNode1,
4452 const SMDS_MeshNode* theBetweenNode2,
4453 list<const SMDS_MeshNode*>& theNodesToInsert)
4455 SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4456 while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4457 const SMDS_MeshElement* elem = invElemIt->next();
4458 if (elem->GetType() != SMDSAbs_Volume)
4461 // check, if current volume has link theBetweenNode1 - theBetweenNode2
4462 SMDS_VolumeTool aVolume (elem);
4463 if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4466 // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4467 int iface, nbFaces = aVolume.NbFaces();
4468 vector<const SMDS_MeshNode *> poly_nodes;
4469 vector<int> quantities (nbFaces);
4471 for (iface = 0; iface < nbFaces; iface++) {
4472 int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4473 // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4474 const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4476 for (int inode = 0; inode < nbFaceNodes; inode++) {
4477 poly_nodes.push_back(faceNodes[inode]);
4479 if (nbInserted == 0) {
4480 if (faceNodes[inode] == theBetweenNode1) {
4481 if (faceNodes[inode + 1] == theBetweenNode2) {
4482 nbInserted = theNodesToInsert.size();
4484 // add nodes to insert
4485 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4486 for (; nIt != theNodesToInsert.end(); nIt++) {
4487 poly_nodes.push_back(*nIt);
4490 } else if (faceNodes[inode] == theBetweenNode2) {
4491 if (faceNodes[inode + 1] == theBetweenNode1) {
4492 nbInserted = theNodesToInsert.size();
4494 // add nodes to insert in reversed order
4495 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4497 for (; nIt != theNodesToInsert.begin(); nIt--) {
4498 poly_nodes.push_back(*nIt);
4500 poly_nodes.push_back(*nIt);
4506 quantities[iface] = nbFaceNodes + nbInserted;
4509 // Replace or update the volume
4510 SMESHDS_Mesh *aMesh = GetMeshDS();
4512 if (elem->IsPoly()) {
4513 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4516 int aShapeId = FindShape( elem );
4518 SMDS_MeshElement* newElem =
4519 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4520 if (aShapeId && newElem)
4521 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4523 aMesh->RemoveElement(elem);
4528 //=======================================================================
4529 //function : SewSideElements
4531 //=======================================================================
4533 SMESH_MeshEditor::Sew_Error
4534 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4535 set<const SMDS_MeshElement*>& theSide2,
4536 const SMDS_MeshNode* theFirstNode1,
4537 const SMDS_MeshNode* theFirstNode2,
4538 const SMDS_MeshNode* theSecondNode1,
4539 const SMDS_MeshNode* theSecondNode2)
4541 MESSAGE ("::::SewSideElements()");
4542 if ( theSide1.size() != theSide2.size() )
4543 return SEW_DIFF_NB_OF_ELEMENTS;
4545 Sew_Error aResult = SEW_OK;
4547 // 1. Build set of faces representing each side
4548 // 2. Find which nodes of the side 1 to merge with ones on the side 2
4549 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4551 // =======================================================================
4552 // 1. Build set of faces representing each side:
4553 // =======================================================================
4554 // a. build set of nodes belonging to faces
4555 // b. complete set of faces: find missing fices whose nodes are in set of nodes
4556 // c. create temporary faces representing side of volumes if correspondent
4557 // face does not exist
4559 SMESHDS_Mesh* aMesh = GetMeshDS();
4560 SMDS_Mesh aTmpFacesMesh;
4561 set<const SMDS_MeshElement*> faceSet1, faceSet2;
4562 set<const SMDS_MeshElement*> volSet1, volSet2;
4563 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
4564 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4565 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
4566 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4567 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4568 int iSide, iFace, iNode;
4570 for ( iSide = 0; iSide < 2; iSide++ ) {
4571 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
4572 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4573 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4574 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
4575 set<const SMDS_MeshElement*>::iterator vIt, eIt;
4576 set<const SMDS_MeshNode*>::iterator nIt;
4578 // -----------------------------------------------------------
4579 // 1a. Collect nodes of existing faces
4580 // and build set of face nodes in order to detect missing
4581 // faces corresponing to sides of volumes
4582 // -----------------------------------------------------------
4584 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4586 // loop on the given element of a side
4587 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4588 const SMDS_MeshElement* elem = *eIt;
4589 if ( elem->GetType() == SMDSAbs_Face ) {
4590 faceSet->insert( elem );
4591 set <const SMDS_MeshNode*> faceNodeSet;
4592 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4593 while ( nodeIt->more() ) {
4594 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4595 nodeSet->insert( n );
4596 faceNodeSet.insert( n );
4598 setOfFaceNodeSet.insert( faceNodeSet );
4600 else if ( elem->GetType() == SMDSAbs_Volume )
4601 volSet->insert( elem );
4603 // ------------------------------------------------------------------------------
4604 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4605 // ------------------------------------------------------------------------------
4607 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4608 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4609 while ( fIt->more() ) { // loop on faces sharing a node
4610 const SMDS_MeshElement* f = fIt->next();
4611 if ( faceSet->find( f ) == faceSet->end() ) {
4612 // check if all nodes are in nodeSet and
4613 // complete setOfFaceNodeSet if they are
4614 set <const SMDS_MeshNode*> faceNodeSet;
4615 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4616 bool allInSet = true;
4617 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4618 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4619 if ( nodeSet->find( n ) == nodeSet->end() )
4622 faceNodeSet.insert( n );
4625 faceSet->insert( f );
4626 setOfFaceNodeSet.insert( faceNodeSet );
4632 // -------------------------------------------------------------------------
4633 // 1c. Create temporary faces representing sides of volumes if correspondent
4634 // face does not exist
4635 // -------------------------------------------------------------------------
4637 if ( !volSet->empty() )
4639 //int nodeSetSize = nodeSet->size();
4641 // loop on given volumes
4642 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4643 SMDS_VolumeTool vol (*vIt);
4644 // loop on volume faces: find free faces
4645 // --------------------------------------
4646 list<const SMDS_MeshElement* > freeFaceList;
4647 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4648 if ( !vol.IsFreeFace( iFace ))
4650 // check if there is already a face with same nodes in a face set
4651 const SMDS_MeshElement* aFreeFace = 0;
4652 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4653 int nbNodes = vol.NbFaceNodes( iFace );
4654 set <const SMDS_MeshNode*> faceNodeSet;
4655 vol.GetFaceNodes( iFace, faceNodeSet );
4656 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4658 // no such a face is given but it still can exist, check it
4659 if ( nbNodes == 3 ) {
4660 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4661 } else if ( nbNodes == 4 ) {
4662 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4664 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4665 for (int inode = 0; inode < nbNodes; inode++) {
4666 poly_nodes[inode] = fNodes[inode];
4668 aFreeFace = aMesh->FindFace(poly_nodes);
4672 // create a temporary face
4673 if ( nbNodes == 3 ) {
4674 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4675 } else if ( nbNodes == 4 ) {
4676 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4678 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4679 for (int inode = 0; inode < nbNodes; inode++) {
4680 poly_nodes[inode] = fNodes[inode];
4682 aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4686 freeFaceList.push_back( aFreeFace );
4688 } // loop on faces of a volume
4690 // choose one of several free faces
4691 // --------------------------------------
4692 if ( freeFaceList.size() > 1 ) {
4693 // choose a face having max nb of nodes shared by other elems of a side
4694 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4695 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4696 while ( fIt != freeFaceList.end() ) { // loop on free faces
4697 int nbSharedNodes = 0;
4698 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4699 while ( nodeIt->more() ) { // loop on free face nodes
4700 const SMDS_MeshNode* n =
4701 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4702 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4703 while ( invElemIt->more() ) {
4704 const SMDS_MeshElement* e = invElemIt->next();
4705 if ( faceSet->find( e ) != faceSet->end() )
4707 if ( elemSet->find( e ) != elemSet->end() )
4711 if ( nbSharedNodes >= maxNbNodes ) {
4712 maxNbNodes = nbSharedNodes;
4716 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4718 if ( freeFaceList.size() > 1 )
4720 // could not choose one face, use another way
4721 // choose a face most close to the bary center of the opposite side
4722 gp_XYZ aBC( 0., 0., 0. );
4723 set <const SMDS_MeshNode*> addedNodes;
4724 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4725 eIt = elemSet2->begin();
4726 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4727 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4728 while ( nodeIt->more() ) { // loop on free face nodes
4729 const SMDS_MeshNode* n =
4730 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4731 if ( addedNodes.insert( n ).second )
4732 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4735 aBC /= addedNodes.size();
4736 double minDist = DBL_MAX;
4737 fIt = freeFaceList.begin();
4738 while ( fIt != freeFaceList.end() ) { // loop on free faces
4740 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4741 while ( nodeIt->more() ) { // loop on free face nodes
4742 const SMDS_MeshNode* n =
4743 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4744 gp_XYZ p( n->X(),n->Y(),n->Z() );
4745 dist += ( aBC - p ).SquareModulus();
4747 if ( dist < minDist ) {
4749 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4752 fIt = freeFaceList.erase( fIt++ );
4755 } // choose one of several free faces of a volume
4757 if ( freeFaceList.size() == 1 ) {
4758 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4759 faceSet->insert( aFreeFace );
4760 // complete a node set with nodes of a found free face
4761 // for ( iNode = 0; iNode < ; iNode++ )
4762 // nodeSet->insert( fNodes[ iNode ] );
4765 } // loop on volumes of a side
4767 // // complete a set of faces if new nodes in a nodeSet appeared
4768 // // ----------------------------------------------------------
4769 // if ( nodeSetSize != nodeSet->size() ) {
4770 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4771 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4772 // while ( fIt->more() ) { // loop on faces sharing a node
4773 // const SMDS_MeshElement* f = fIt->next();
4774 // if ( faceSet->find( f ) == faceSet->end() ) {
4775 // // check if all nodes are in nodeSet and
4776 // // complete setOfFaceNodeSet if they are
4777 // set <const SMDS_MeshNode*> faceNodeSet;
4778 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4779 // bool allInSet = true;
4780 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4781 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4782 // if ( nodeSet->find( n ) == nodeSet->end() )
4783 // allInSet = false;
4785 // faceNodeSet.insert( n );
4787 // if ( allInSet ) {
4788 // faceSet->insert( f );
4789 // setOfFaceNodeSet.insert( faceNodeSet );
4795 } // Create temporary faces, if there are volumes given
4798 if ( faceSet1.size() != faceSet2.size() ) {
4799 // delete temporary faces: they are in reverseElements of actual nodes
4800 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4801 while ( tmpFaceIt->more() )
4802 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4803 MESSAGE("Diff nb of faces");
4804 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4807 // ============================================================
4808 // 2. Find nodes to merge:
4809 // bind a node to remove to a node to put instead
4810 // ============================================================
4812 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4813 if ( theFirstNode1 != theFirstNode2 )
4814 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4815 if ( theSecondNode1 != theSecondNode2 )
4816 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4818 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4819 set< long > linkIdSet; // links to process
4820 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4822 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4823 list< TPairOfNodes > linkList[2];
4824 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4825 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4826 // loop on links in linkList; find faces by links and append links
4827 // of the found faces to linkList
4828 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4829 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4831 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4832 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4833 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4836 // by links, find faces in the face sets,
4837 // and find indices of link nodes in the found faces;
4838 // in a face set, there is only one or no face sharing a link
4839 // ---------------------------------------------------------------
4841 const SMDS_MeshElement* face[] = { 0, 0 };
4842 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4843 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4844 int iLinkNode[2][2];
4845 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4846 const SMDS_MeshNode* n1 = link[iSide].first;
4847 const SMDS_MeshNode* n2 = link[iSide].second;
4848 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4849 set< const SMDS_MeshElement* > fMap;
4850 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4851 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4852 SMDS_ElemIteratorPtr fIt = n->facesIterator();
4853 while ( fIt->more() ) { // loop on faces sharing a node
4854 const SMDS_MeshElement* f = fIt->next();
4855 if (faceSet->find( f ) != faceSet->end() && // f is in face set
4856 ! fMap.insert( f ).second ) // f encounters twice
4858 if ( face[ iSide ] ) {
4859 MESSAGE( "2 faces per link " );
4860 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4864 faceSet->erase( f );
4865 // get face nodes and find ones of a link
4867 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4868 while ( nIt->more() ) {
4869 const SMDS_MeshNode* n =
4870 static_cast<const SMDS_MeshNode*>( nIt->next() );
4872 iLinkNode[ iSide ][ 0 ] = iNode;
4874 iLinkNode[ iSide ][ 1 ] = iNode;
4875 else if ( notLinkNodes[ iSide ][ 0 ] )
4876 notLinkNodes[ iSide ][ 1 ] = n;
4878 notLinkNodes[ iSide ][ 0 ] = n;
4879 faceNodes[ iSide ][ iNode++ ] = n;
4881 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4886 // check similarity of elements of the sides
4887 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4888 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4889 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4890 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4892 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4893 break; // do not return because it s necessary to remove tmp faces
4896 // set nodes to merge
4897 // -------------------
4899 if ( face[0] && face[1] )
4901 int nbNodes = face[0]->NbNodes();
4902 if ( nbNodes != face[1]->NbNodes() ) {
4903 MESSAGE("Diff nb of face nodes");
4904 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4905 break; // do not return because it s necessary to remove tmp faces
4907 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4909 nReplaceMap.insert( TNodeNodeMap::value_type
4910 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4912 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4913 // analyse link orientation in faces
4914 int i1 = iLinkNode[ iSide ][ 0 ];
4915 int i2 = iLinkNode[ iSide ][ 1 ];
4916 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4917 // if notLinkNodes are the first and the last ones, then
4918 // their order does not correspond to the link orientation
4919 if (( i1 == 1 && i2 == 2 ) ||
4920 ( i1 == 2 && i2 == 1 ))
4921 reverse[ iSide ] = !reverse[ iSide ];
4923 if ( reverse[0] == reverse[1] ) {
4924 nReplaceMap.insert( TNodeNodeMap::value_type
4925 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4926 nReplaceMap.insert( TNodeNodeMap::value_type
4927 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
4930 nReplaceMap.insert( TNodeNodeMap::value_type
4931 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
4932 nReplaceMap.insert( TNodeNodeMap::value_type
4933 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
4937 // add other links of the faces to linkList
4938 // -----------------------------------------
4940 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
4941 for ( iNode = 0; iNode < nbNodes; iNode++ )
4943 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
4944 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
4945 if ( !iter_isnew.second ) { // already in a set: no need to process
4946 linkIdSet.erase( iter_isnew.first );
4948 else // new in set == encountered for the first time: add
4950 const SMDS_MeshNode* n1 = nodes[ iNode ];
4951 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
4952 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
4953 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
4957 } // loop on link lists
4959 if ( aResult == SEW_OK &&
4960 ( linkIt[0] != linkList[0].end() ||
4961 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
4962 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
4963 " " << (faceSetPtr[1]->empty()));
4964 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4967 // ====================================================================
4968 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4969 // ====================================================================
4971 // delete temporary faces: they are in reverseElements of actual nodes
4972 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4973 while ( tmpFaceIt->more() )
4974 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4976 if ( aResult != SEW_OK)
4979 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
4980 // loop on nodes replacement map
4981 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
4982 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
4983 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
4985 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
4986 nodeIDsToRemove.push_back( nToRemove->GetID() );
4987 // loop on elements sharing nToRemove
4988 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
4989 while ( invElemIt->more() ) {
4990 const SMDS_MeshElement* e = invElemIt->next();
4991 // get a new suite of nodes: make replacement
4992 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
4993 const SMDS_MeshNode* nodes[ 8 ];
4994 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4995 while ( nIt->more() ) {
4996 const SMDS_MeshNode* n =
4997 static_cast<const SMDS_MeshNode*>( nIt->next() );
4998 nnIt = nReplaceMap.find( n );
4999 if ( nnIt != nReplaceMap.end() ) {
5005 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5006 // elemIDsToRemove.push_back( e->GetID() );
5009 aMesh->ChangeElementNodes( e, nodes, nbNodes );
5013 Remove( nodeIDsToRemove, true );