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>
66 #include <TColStd_ListOfInteger.hxx>
71 using namespace SMESH::Controls;
73 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
74 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
75 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
76 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
77 typedef TNodeOfNodeListMap::iterator TNodeOfNodeListMapItr;
78 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
80 //=======================================================================
81 //function : SMESH_MeshEditor
83 //=======================================================================
85 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
90 //=======================================================================
92 //purpose : Remove a node or an element.
93 // Modify a compute state of sub-meshes which become empty
94 //=======================================================================
96 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
100 SMESHDS_Mesh* aMesh = GetMeshDS();
101 set< SMESH_subMesh *> smmap;
103 list<int>::const_iterator it = theIDs.begin();
104 for ( ; it != theIDs.end(); it++ )
106 const SMDS_MeshElement * elem;
108 elem = aMesh->FindNode( *it );
110 elem = aMesh->FindElement( *it );
114 // Find sub-meshes to notify about modification
115 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
116 while ( nodeIt->more() )
118 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
119 const SMDS_PositionPtr& aPosition = node->GetPosition();
120 if ( aPosition.get() ) {
121 int aShapeID = aPosition->GetShapeId();
123 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
124 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
133 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
135 aMesh->RemoveElement( elem );
138 // Notify sub-meshes about modification
139 if ( !smmap.empty() ) {
140 set< SMESH_subMesh *>::iterator smIt;
141 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
142 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
147 //=======================================================================
148 //function : FindShape
149 //purpose : Return an index of the shape theElem is on
150 // or zero if a shape not found
151 //=======================================================================
153 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
155 SMESHDS_Mesh * aMesh = GetMeshDS();
156 if ( aMesh->ShapeToMesh().IsNull() )
159 if ( theElem->GetType() == SMDSAbs_Node )
161 const SMDS_PositionPtr& aPosition =
162 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
163 if ( aPosition.get() )
164 return aPosition->GetShapeId();
169 TopoDS_Shape aShape; // the shape a node is on
170 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
171 while ( nodeIt->more() )
173 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
174 const SMDS_PositionPtr& aPosition = node->GetPosition();
175 if ( aPosition.get() ) {
176 int aShapeID = aPosition->GetShapeId();
177 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
180 if ( sm->Contains( theElem ))
182 if ( aShape.IsNull() )
183 aShape = aMesh->IndexToShape( aShapeID );
187 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
192 // None of nodes is on a proper shape,
193 // find the shape among ancestors of aShape on which a node is
194 if ( aShape.IsNull() ) {
195 //MESSAGE ("::FindShape() - NONE node is on shape")
198 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
199 for ( ; ancIt.More(); ancIt.Next() )
201 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
202 if ( sm && sm->Contains( theElem ))
203 return aMesh->ShapeToIndex( ancIt.Value() );
206 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
210 //=======================================================================
211 //function : InverseDiag
212 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
213 // but having other common link.
214 // Return False if args are improper
215 //=======================================================================
217 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
218 const SMDS_MeshElement * theTria2 )
220 if (!theTria1 || !theTria2)
222 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
223 if (!F1) return false;
224 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
225 if (!F2) return false;
227 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
228 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
232 // put nodes in array and find out indices of the same ones
233 const SMDS_MeshNode* aNodes [6];
234 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
236 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
239 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
241 if ( i > 2 ) // theTria2
242 // find same node of theTria1
243 for ( int j = 0; j < 3; j++ )
244 if ( aNodes[ i ] == aNodes[ j ]) {
253 return false; // theTria1 is not a triangle
254 it = theTria2->nodesIterator();
256 if ( i == 6 && it->more() )
257 return false; // theTria2 is not a triangle
260 // find indices of 1,2 and of A,B in theTria1
261 int iA = 0, iB = 0, i1 = 0, i2 = 0;
262 for ( i = 0; i < 6; i++ )
264 if ( sameInd [ i ] == 0 )
271 // nodes 1 and 2 should not be the same
272 if ( aNodes[ i1 ] == aNodes[ i2 ] )
277 aNodes[ iA ] = aNodes[ i2 ];
279 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
281 //MESSAGE( theTria1 << theTria2 );
283 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
284 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
286 //MESSAGE( theTria1 << theTria2 );
291 //=======================================================================
292 //function : findTriangles
293 //purpose : find triangles sharing theNode1-theNode2 link
294 //=======================================================================
296 static bool findTriangles(const SMDS_MeshNode * theNode1,
297 const SMDS_MeshNode * theNode2,
298 const SMDS_MeshElement*& theTria1,
299 const SMDS_MeshElement*& theTria2)
301 if ( !theNode1 || !theNode2 ) return false;
303 theTria1 = theTria2 = 0;
305 set< const SMDS_MeshElement* > emap;
306 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
308 const SMDS_MeshElement* elem = it->next();
309 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
312 it = theNode2->GetInverseElementIterator();
314 const SMDS_MeshElement* elem = it->next();
315 if ( elem->GetType() == SMDSAbs_Face &&
316 emap.find( elem ) != emap.end() )
324 return ( theTria1 && theTria2 );
327 //=======================================================================
328 //function : InverseDiag
329 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
330 // with ones built on the same 4 nodes but having other common link.
331 // Return false if proper faces not found
332 //=======================================================================
334 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
335 const SMDS_MeshNode * theNode2)
337 MESSAGE( "::InverseDiag()" );
339 const SMDS_MeshElement *tr1, *tr2;
340 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
343 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
344 if (!F1) return false;
345 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
346 if (!F2) return false;
348 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
349 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
353 // put nodes in array
354 // and find indices of 1,2 and of A in tr1 and of B in tr2
355 int i, iA1 = 0, i1 = 0;
356 const SMDS_MeshNode* aNodes1 [3];
357 SMDS_ElemIteratorPtr it;
358 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
359 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
360 if ( aNodes1[ i ] == theNode1 )
361 iA1 = i; // node A in tr1
362 else if ( aNodes1[ i ] != theNode2 )
366 const SMDS_MeshNode* aNodes2 [3];
367 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
368 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
369 if ( aNodes2[ i ] == theNode2 )
370 iB2 = i; // node B in tr2
371 else if ( aNodes2[ i ] != theNode1 )
375 // nodes 1 and 2 should not be the same
376 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
380 aNodes1[ iA1 ] = aNodes2[ i2 ];
382 aNodes2[ iB2 ] = aNodes1[ i1 ];
384 //MESSAGE( tr1 << tr2 );
386 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
387 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
389 //MESSAGE( tr1 << tr2 );
395 //=======================================================================
396 //function : getQuadrangleNodes
397 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
398 // fusion of triangles tr1 and tr2 having shared link on
399 // theNode1 and theNode2
400 //=======================================================================
402 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
403 const SMDS_MeshNode * theNode1,
404 const SMDS_MeshNode * theNode2,
405 const SMDS_MeshElement * tr1,
406 const SMDS_MeshElement * tr2 )
408 // find the 4-th node to insert into tr1
409 const SMDS_MeshNode* n4 = 0;
410 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
411 while ( !n4 && it->more() )
413 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
414 bool isDiag = ( n == theNode1 || n == theNode2 );
418 // Make an array of nodes to be in a quadrangle
419 int iNode = 0, iFirstDiag = -1;
420 it = tr1->nodesIterator();
423 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
424 bool isDiag = ( n == theNode1 || n == theNode2 );
427 if ( iFirstDiag < 0 )
429 else if ( iNode - iFirstDiag == 1 )
430 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
434 return false; // tr1 and tr2 should not have all the same nodes
436 theQuadNodes[ iNode++ ] = n;
438 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
439 theQuadNodes[ iNode ] = n4;
444 //=======================================================================
445 //function : DeleteDiag
446 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
447 // with a quadrangle built on the same 4 nodes.
448 // Return false if proper faces not found
449 //=======================================================================
451 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
452 const SMDS_MeshNode * theNode2)
454 MESSAGE( "::DeleteDiag()" );
456 const SMDS_MeshElement *tr1, *tr2;
457 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
460 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
461 if (!F1) return false;
462 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
463 if (!F2) return false;
465 const SMDS_MeshNode* aNodes [ 4 ];
466 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
469 //MESSAGE( endl << tr1 << tr2 );
471 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
472 GetMeshDS()->RemoveElement( tr2 );
474 //MESSAGE( endl << tr1 );
479 //=======================================================================
480 //function : Reorient
481 //purpose : Reverse theElement orientation
482 //=======================================================================
484 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
488 SMDS_ElemIteratorPtr it = theElem->nodesIterator();
489 if ( !it || !it->more() )
492 switch ( theElem->GetType() ) {
497 int i = theElem->NbNodes();
498 vector<const SMDS_MeshNode*> aNodes( i );
500 aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
501 return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
505 if (theElem->IsPoly()) {
506 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
507 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
509 MESSAGE("Warning: bad volumic element");
513 int nbFaces = aPolyedre->NbFaces();
514 vector<const SMDS_MeshNode *> poly_nodes;
515 vector<int> quantities (nbFaces);
517 // reverse each face of the polyedre
518 for (int iface = 1; iface <= nbFaces; iface++) {
519 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
520 quantities[iface - 1] = nbFaceNodes;
522 for (inode = nbFaceNodes; inode >= 1; inode--) {
523 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
524 poly_nodes.push_back(curNode);
528 return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
531 SMDS_VolumeTool vTool;
532 if ( !vTool.Set( theElem ))
535 return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
544 //=======================================================================
545 //function : getBadRate
547 //=======================================================================
549 static double getBadRate (const SMDS_MeshElement* theElem,
550 SMESH::Controls::NumericalFunctorPtr& theCrit)
552 SMESH::Controls::TSequenceOfXYZ P;
553 if ( !theElem || !theCrit->GetPoints( theElem, P ))
555 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
556 //return theCrit->GetBadRate( theCrit->GetValue( theElem->GetID() ), theElem->NbNodes() );
559 //=======================================================================
560 //function : QuadToTri
561 //purpose : Cut quadrangles into triangles.
562 // theCrit is used to select a diagonal to cut
563 //=======================================================================
565 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
566 SMESH::Controls::NumericalFunctorPtr theCrit)
568 MESSAGE( "::QuadToTri()" );
570 if ( !theCrit.get() )
573 SMESHDS_Mesh * aMesh = GetMeshDS();
575 set< const SMDS_MeshElement * >::iterator itElem;
576 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
578 const SMDS_MeshElement* elem = (*itElem);
579 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
582 // retrieve element nodes
583 const SMDS_MeshNode* aNodes [4];
584 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
586 while ( itN->more() )
587 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
589 // compare two sets of possible triangles
590 double aBadRate1, aBadRate2; // to what extent a set is bad
591 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
592 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
593 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
595 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
596 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
597 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
599 int aShapeId = FindShape( elem );
600 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
601 // << " ShapeID = " << aShapeId << endl << elem );
603 if ( aBadRate1 <= aBadRate2 ) {
604 // tr1 + tr2 is better
605 aMesh->ChangeElementNodes( elem, aNodes, 3 );
606 //MESSAGE( endl << elem );
608 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
611 // tr3 + tr4 is better
612 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
613 //MESSAGE( endl << elem );
615 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
617 //MESSAGE( endl << elem );
619 // put a new triangle on the same shape
621 aMesh->SetMeshElementOnShape( elem, aShapeId );
627 //=======================================================================
628 //function : BestSplit
629 //purpose : Find better diagonal for cutting.
630 //=======================================================================
631 int SMESH_MeshEditor::BestSplit (const SMDS_MeshElement* theQuad,
632 SMESH::Controls::NumericalFunctorPtr theCrit)
637 if (!theQuad || theQuad->GetType() != SMDSAbs_Face || theQuad->NbNodes() != 4)
640 // retrieve element nodes
641 const SMDS_MeshNode* aNodes [4];
642 SMDS_ElemIteratorPtr itN = theQuad->nodesIterator();
645 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
647 // compare two sets of possible triangles
648 double aBadRate1, aBadRate2; // to what extent a set is bad
649 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
650 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
651 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
653 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
654 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
655 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
657 if (aBadRate1 <= aBadRate2) // tr1 + tr2 is better
658 return 1; // diagonal 1-3
660 return 2; // diagonal 2-4
663 //=======================================================================
664 //function : AddToSameGroups
665 //purpose : add elemToAdd to the groups the elemInGroups belongs to
666 //=======================================================================
668 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
669 const SMDS_MeshElement* elemInGroups,
670 SMESHDS_Mesh * aMesh)
672 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
673 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
674 for ( ; grIt != groups.end(); grIt++ ) {
675 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
676 if ( group && group->SMDSGroup().Contains( elemInGroups ))
677 group->SMDSGroup().Add( elemToAdd );
681 //=======================================================================
682 //function : QuadToTri
683 //purpose : Cut quadrangles into triangles.
684 // theCrit is used to select a diagonal to cut
685 //=======================================================================
687 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
688 const bool the13Diag)
690 MESSAGE( "::QuadToTri()" );
692 SMESHDS_Mesh * aMesh = GetMeshDS();
694 set< const SMDS_MeshElement * >::iterator itElem;
695 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
697 const SMDS_MeshElement* elem = (*itElem);
698 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
701 // retrieve element nodes
702 const SMDS_MeshNode* aNodes [4];
703 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
705 while ( itN->more() )
706 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
708 int aShapeId = FindShape( elem );
709 const SMDS_MeshElement* newElem = 0;
712 aMesh->ChangeElementNodes( elem, aNodes, 3 );
713 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
717 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
718 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
721 // put a new triangle on the same shape and add to the same groups
724 aMesh->SetMeshElementOnShape( newElem, aShapeId );
726 AddToSameGroups( newElem, elem, aMesh );
732 //=======================================================================
733 //function : getAngle
735 //=======================================================================
737 double getAngle(const SMDS_MeshElement * tr1,
738 const SMDS_MeshElement * tr2,
739 const SMDS_MeshNode * n1,
740 const SMDS_MeshNode * n2)
742 double angle = 2*PI; // bad angle
745 SMESH::Controls::TSequenceOfXYZ P1, P2;
746 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
747 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
749 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
750 if ( N1.SquareMagnitude() <= gp::Resolution() )
752 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
753 if ( N2.SquareMagnitude() <= gp::Resolution() )
756 // find the first diagonal node n1 in the triangles:
757 // take in account a diagonal link orientation
758 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
759 for ( int t = 0; t < 2; t++ )
761 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
762 int i = 0, iDiag = -1;
763 while ( it->more()) {
764 const SMDS_MeshElement *n = it->next();
765 if ( n == n1 || n == n2 )
769 if ( i - iDiag == 1 )
770 nFirst[ t ] = ( n == n1 ? n2 : n1 );
778 if ( nFirst[ 0 ] == nFirst[ 1 ] )
781 angle = N1.Angle( N2 );
786 // =================================================
787 // class generating a unique ID for a pair of nodes
788 // and able to return nodes by that ID
789 // =================================================
794 LinkID_Gen( const SMESHDS_Mesh* theMesh )
795 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
798 long GetLinkID (const SMDS_MeshNode * n1,
799 const SMDS_MeshNode * n2) const
801 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
804 bool GetNodes (const long theLinkID,
805 const SMDS_MeshNode* & theNode1,
806 const SMDS_MeshNode* & theNode2) const
808 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
809 if ( !theNode1 ) return false;
810 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
811 if ( !theNode2 ) return false;
817 const SMESHDS_Mesh* myMesh;
821 //=======================================================================
822 //function : TriToQuad
823 //purpose : Fuse neighbour triangles into quadrangles.
824 // theCrit is used to select a neighbour to fuse with.
825 // theMaxAngle is a max angle between element normals at which
826 // fusion is still performed.
827 //=======================================================================
829 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
830 SMESH::Controls::NumericalFunctorPtr theCrit,
831 const double theMaxAngle)
833 MESSAGE( "::TriToQuad()" );
835 if ( !theCrit.get() )
838 SMESHDS_Mesh * aMesh = GetMeshDS();
839 LinkID_Gen aLinkID_Gen( aMesh );
842 // Prepare data for algo: build
843 // 1. map of elements with their linkIDs
844 // 2. map of linkIDs with their elements
846 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
847 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
848 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
849 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
851 set<const SMDS_MeshElement*>::iterator itElem;
852 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
854 const SMDS_MeshElement* elem = (*itElem);
855 if ( !elem || elem->NbNodes() != 3 )
858 // retrieve element nodes
859 const SMDS_MeshNode* aNodes [4];
860 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
862 while ( itN->more() )
863 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
865 aNodes[ 3 ] = aNodes[ 0 ];
868 for ( i = 0; i < 3; i++ )
870 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
871 // check if elements sharing a link can be fused
872 itLE = mapLi_listEl.find( linkID );
873 if ( itLE != mapLi_listEl.end() )
875 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
877 const SMDS_MeshElement* elem2 = (*itLE).second.front();
878 // if ( FindShape( elem ) != FindShape( elem2 ))
879 // continue; // do not fuse triangles laying on different shapes
880 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
881 continue; // avoid making badly shaped quads
882 (*itLE).second.push_back( elem );
885 mapLi_listEl[ linkID ].push_back( elem );
886 mapEl_setLi [ elem ].insert( linkID );
889 // Clean the maps from the links shared by a sole element, ie
890 // links to which only one element is bound in mapLi_listEl
892 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
894 int nbElems = (*itLE).second.size();
896 const SMDS_MeshElement* elem = (*itLE).second.front();
897 long link = (*itLE).first;
898 mapEl_setLi[ elem ].erase( link );
899 if ( mapEl_setLi[ elem ].empty() )
900 mapEl_setLi.erase( elem );
904 // Algo: fuse triangles into quadrangles
906 while ( ! mapEl_setLi.empty() )
908 // Look for the start element:
909 // the element having the least nb of shared links
911 const SMDS_MeshElement* startElem = 0;
913 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
915 int nbLinks = (*itEL).second.size();
916 if ( nbLinks < minNbLinks )
918 startElem = (*itEL).first;
919 minNbLinks = nbLinks;
920 if ( minNbLinks == 1 )
925 // search elements to fuse starting from startElem or links of elements
926 // fused earlyer - startLinks
927 list< long > startLinks;
928 while ( startElem || !startLinks.empty() )
930 while ( !startElem && !startLinks.empty() )
932 // Get an element to start, by a link
933 long linkId = startLinks.front();
934 startLinks.pop_front();
935 itLE = mapLi_listEl.find( linkId );
936 if ( itLE != mapLi_listEl.end() )
938 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
939 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
940 for ( ; itE != listElem.end() ; itE++ )
941 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
943 mapLi_listEl.erase( itLE );
949 // Get candidates to be fused
951 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
954 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
955 set< long >& setLi = mapEl_setLi[ tr1 ];
956 ASSERT( !setLi.empty() );
957 set< long >::iterator itLi;
958 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
960 long linkID = (*itLi);
961 itLE = mapLi_listEl.find( linkID );
962 if ( itLE == mapLi_listEl.end() )
964 const SMDS_MeshElement* elem = (*itLE).second.front();
966 elem = (*itLE).second.back();
967 mapLi_listEl.erase( itLE );
968 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
981 // add other links of elem to list of links to re-start from
982 set< long >& links = mapEl_setLi[ elem ];
983 set< long >::iterator it;
984 for ( it = links.begin(); it != links.end(); it++ )
986 long linkID2 = (*it);
987 if ( linkID2 != linkID )
988 startLinks.push_back( linkID2 );
992 // Get nodes of possible quadrangles
994 const SMDS_MeshNode *n12 [4], *n13 [4];
995 bool Ok12 = false, Ok13 = false;
996 const SMDS_MeshNode *linkNode1, *linkNode2;
998 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
999 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
1002 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
1003 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1006 // Choose a pair to fuse
1010 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
1011 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
1012 double aBadRate12 = getBadRate( &quad12, theCrit );
1013 double aBadRate13 = getBadRate( &quad13, theCrit );
1014 if ( aBadRate13 < aBadRate12 )
1022 // and remove fused elems and removed links from the maps
1024 mapEl_setLi.erase( tr1 );
1027 mapEl_setLi.erase( tr2 );
1028 mapLi_listEl.erase( link12 );
1029 aMesh->ChangeElementNodes( tr1, n12, 4 );
1030 aMesh->RemoveElement( tr2 );
1034 mapEl_setLi.erase( tr3 );
1035 mapLi_listEl.erase( link13 );
1036 aMesh->ChangeElementNodes( tr1, n13, 4 );
1037 aMesh->RemoveElement( tr3 );
1040 // Next element to fuse: the rejected one
1042 startElem = Ok12 ? tr3 : tr2;
1044 } // if ( startElem )
1045 } // while ( startElem || !startLinks.empty() )
1046 } // while ( ! mapEl_setLi.empty() )
1052 /*#define DUMPSO(txt) \
1053 // cout << txt << endl;
1054 //=============================================================================
1058 //=============================================================================
1059 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1063 int tmp = idNodes[ i1 ];
1064 idNodes[ i1 ] = idNodes[ i2 ];
1065 idNodes[ i2 ] = tmp;
1066 gp_Pnt Ptmp = P[ i1 ];
1069 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1072 //=======================================================================
1073 //function : SortQuadNodes
1074 //purpose : Set 4 nodes of a quadrangle face in a good order.
1075 // Swap 1<->2 or 2<->3 nodes and correspondingly return
1077 //=======================================================================
1079 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1084 for ( i = 0; i < 4; i++ ) {
1085 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1087 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1090 gp_Vec V1(P[0], P[1]);
1091 gp_Vec V2(P[0], P[2]);
1092 gp_Vec V3(P[0], P[3]);
1094 gp_Vec Cross1 = V1 ^ V2;
1095 gp_Vec Cross2 = V2 ^ V3;
1098 if (Cross1.Dot(Cross2) < 0)
1103 if (Cross1.Dot(Cross2) < 0)
1107 swap ( i, i + 1, idNodes, P );
1109 // for ( int ii = 0; ii < 4; ii++ ) {
1110 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1111 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1117 //=======================================================================
1118 //function : SortHexaNodes
1119 //purpose : Set 8 nodes of a hexahedron in a good order.
1120 // Return success status
1121 //=======================================================================
1123 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1128 DUMPSO( "INPUT: ========================================");
1129 for ( i = 0; i < 8; i++ ) {
1130 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1131 if ( !n ) return false;
1132 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1133 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1135 DUMPSO( "========================================");
1138 set<int> faceNodes; // ids of bottom face nodes, to be found
1139 set<int> checkedId1; // ids of tried 2-nd nodes
1140 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1141 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1142 int iMin, iLoop1 = 0;
1144 // Loop to try the 2-nd nodes
1146 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1148 // Find not checked 2-nd node
1149 for ( i = 1; i < 8; i++ )
1150 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1151 int id1 = idNodes[i];
1152 swap ( 1, i, idNodes, P );
1153 checkedId1.insert ( id1 );
1157 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1158 // ie that all but meybe one (id3 which is on the same face) nodes
1159 // lay on the same side from the triangle plane.
1161 bool manyInPlane = false; // more than 4 nodes lay in plane
1163 while ( ++iLoop2 < 6 ) {
1165 // get 1-2-3 plane coeffs
1166 Standard_Real A, B, C, D;
1167 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1168 if ( N.SquareMagnitude() > gp::Resolution() )
1170 gp_Pln pln ( P[0], N );
1171 pln.Coefficients( A, B, C, D );
1173 // find the node (iMin) closest to pln
1174 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1176 for ( i = 3; i < 8; i++ ) {
1177 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1178 if ( fabs( dist[i] ) < minDist ) {
1179 minDist = fabs( dist[i] );
1182 if ( fabs( dist[i] ) <= tol )
1183 idInPln.insert( idNodes[i] );
1186 // there should not be more than 4 nodes in bottom plane
1187 if ( idInPln.size() > 1 )
1189 DUMPSO( "### idInPln.size() = " << idInPln.size());
1190 // idInPlane does not contain the first 3 nodes
1191 if ( manyInPlane || idInPln.size() == 5)
1192 return false; // all nodes in one plane
1195 // set the 1-st node to be not in plane
1196 for ( i = 3; i < 8; i++ ) {
1197 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1198 DUMPSO( "### Reset 0-th node");
1199 swap( 0, i, idNodes, P );
1204 // reset to re-check second nodes
1205 leastDist = DBL_MAX;
1209 break; // from iLoop2;
1212 // check that the other 4 nodes are on the same side
1213 bool sameSide = true;
1214 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1215 for ( i = 3; sameSide && i < 8; i++ ) {
1217 sameSide = ( isNeg == dist[i] <= 0.);
1220 // keep best solution
1221 if ( sameSide && minDist < leastDist ) {
1222 leastDist = minDist;
1224 faceNodes.insert( idNodes[ 1 ] );
1225 faceNodes.insert( idNodes[ 2 ] );
1226 faceNodes.insert( idNodes[ iMin ] );
1227 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1228 << " leastDist = " << leastDist);
1229 if ( leastDist <= DBL_MIN )
1234 // set next 3-d node to check
1235 int iNext = 2 + iLoop2;
1237 DUMPSO( "Try 2-nd");
1238 swap ( 2, iNext, idNodes, P );
1240 } // while ( iLoop2 < 6 )
1243 if ( faceNodes.empty() ) return false;
1245 // Put the faceNodes in proper places
1246 for ( i = 4; i < 8; i++ ) {
1247 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1248 // find a place to put
1250 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1252 DUMPSO( "Set faceNodes");
1253 swap ( iTo, i, idNodes, P );
1258 // Set nodes of the found bottom face in good order
1259 DUMPSO( " Found bottom face: ");
1260 i = SortQuadNodes( theMesh, idNodes );
1262 gp_Pnt Ptmp = P[ i ];
1267 // for ( int ii = 0; ii < 4; ii++ ) {
1268 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1269 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1272 // Gravity center of the top and bottom faces
1273 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1274 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1276 // Get direction from the bottom to the top face
1277 gp_Vec upDir ( aGCb, aGCt );
1278 Standard_Real upDirSize = upDir.Magnitude();
1279 if ( upDirSize <= gp::Resolution() ) return false;
1282 // Assure that the bottom face normal points up
1283 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1284 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1285 if ( Nb.Dot( upDir ) < 0 ) {
1286 DUMPSO( "Reverse bottom face");
1287 swap( 1, 3, idNodes, P );
1290 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1291 Standard_Real minDist = DBL_MAX;
1292 for ( i = 4; i < 8; i++ ) {
1293 // projection of P[i] to the plane defined by P[0] and upDir
1294 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1295 Standard_Real sqDist = P[0].SquareDistance( Pp );
1296 if ( sqDist < minDist ) {
1301 DUMPSO( "Set 4-th");
1302 swap ( 4, iMin, idNodes, P );
1304 // Set nodes of the top face in good order
1305 DUMPSO( "Sort top face");
1306 i = SortQuadNodes( theMesh, &idNodes[4] );
1309 gp_Pnt Ptmp = P[ i ];
1314 // Assure that direction of the top face normal is from the bottom face
1315 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1316 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1317 if ( Nt.Dot( upDir ) < 0 ) {
1318 DUMPSO( "Reverse top face");
1319 swap( 5, 7, idNodes, P );
1322 // DUMPSO( "OUTPUT: ========================================");
1323 // for ( i = 0; i < 8; i++ ) {
1324 // float *p = ugrid->GetPoint(idNodes[i]);
1325 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1331 //=======================================================================
1332 //function : laplacianSmooth
1333 //purpose : pulls theNode toward the center of surrounding nodes directly
1334 // connected to that node along an element edge
1335 //=======================================================================
1337 void laplacianSmooth(const SMDS_MeshNode* theNode,
1338 const Handle(Geom_Surface)& theSurface,
1339 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1341 // find surrounding nodes
1343 set< const SMDS_MeshNode* > nodeSet;
1344 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1345 while ( elemIt->more() )
1347 const SMDS_MeshElement* elem = elemIt->next();
1348 if ( elem->GetType() != SMDSAbs_Face )
1351 // put all nodes in array
1352 int nbNodes = 0, iNode = 0;
1353 vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1354 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1355 while ( itN->more() )
1357 aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1358 if ( aNodes[ nbNodes ] == theNode )
1359 iNode = nbNodes; // index of theNode within aNodes
1363 int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1364 nodeSet.insert( aNodes[ iAfter ]);
1365 int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1366 nodeSet.insert( aNodes[ iBefore ]);
1369 // compute new coodrs
1371 double coord[] = { 0., 0., 0. };
1372 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1373 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1374 const SMDS_MeshNode* node = (*nodeSetIt);
1375 if ( theSurface.IsNull() ) { // smooth in 3D
1376 coord[0] += node->X();
1377 coord[1] += node->Y();
1378 coord[2] += node->Z();
1380 else { // smooth in 2D
1381 ASSERT( theUVMap.find( node ) != theUVMap.end() );
1382 gp_XY* uv = theUVMap[ node ];
1383 coord[0] += uv->X();
1384 coord[1] += uv->Y();
1387 int nbNodes = nodeSet.size();
1390 coord[0] /= nbNodes;
1391 coord[1] /= nbNodes;
1393 if ( !theSurface.IsNull() ) {
1394 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1395 theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1396 gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1402 coord[2] /= nbNodes;
1406 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1409 //=======================================================================
1410 //function : centroidalSmooth
1411 //purpose : pulls theNode toward the element-area-weighted centroid of the
1412 // surrounding elements
1413 //=======================================================================
1415 void centroidalSmooth(const SMDS_MeshNode* theNode,
1416 const Handle(Geom_Surface)& theSurface,
1417 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1419 gp_XYZ aNewXYZ(0.,0.,0.);
1420 SMESH::Controls::Area anAreaFunc;
1421 double totalArea = 0.;
1426 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1427 while ( elemIt->more() )
1429 const SMDS_MeshElement* elem = elemIt->next();
1430 if ( elem->GetType() != SMDSAbs_Face )
1434 gp_XYZ elemCenter(0.,0.,0.);
1435 SMESH::Controls::TSequenceOfXYZ aNodePoints;
1436 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1437 while ( itN->more() )
1439 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1440 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1441 aNodePoints.push_back( aP );
1442 if ( !theSurface.IsNull() ) { // smooth in 2D
1443 ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
1444 gp_XY* uv = theUVMap[ aNode ];
1445 aP.SetCoord( uv->X(), uv->Y(), 0. );
1449 double elemArea = anAreaFunc.GetValue( aNodePoints );
1450 totalArea += elemArea;
1451 elemCenter /= elem->NbNodes();
1452 aNewXYZ += elemCenter * elemArea;
1454 aNewXYZ /= totalArea;
1455 if ( !theSurface.IsNull() ) {
1456 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1457 theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1458 aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1463 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1466 //=======================================================================
1467 //function : getClosestUV
1468 //purpose : return UV of closest projection
1469 //=======================================================================
1471 static bool getClosestUV (Extrema_GenExtPS& projector,
1472 const gp_Pnt& point,
1475 projector.Perform( point );
1476 if ( projector.IsDone() ) {
1477 double u, v, minVal = DBL_MAX;
1478 for ( int i = projector.NbExt(); i > 0; i-- )
1479 if ( projector.Value( i ) < minVal ) {
1480 minVal = projector.Value( i );
1481 projector.Point( i ).Parameter( u, v );
1483 result.SetCoord( u, v );
1489 //=======================================================================
1491 //purpose : Smooth theElements during theNbIterations or until a worst
1492 // element has aspect ratio <= theTgtAspectRatio.
1493 // Aspect Ratio varies in range [1.0, inf].
1494 // If theElements is empty, the whole mesh is smoothed.
1495 // theFixedNodes contains additionally fixed nodes. Nodes built
1496 // on edges and boundary nodes are always fixed.
1497 //=======================================================================
1499 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1500 set<const SMDS_MeshNode*> & theFixedNodes,
1501 const SmoothMethod theSmoothMethod,
1502 const int theNbIterations,
1503 double theTgtAspectRatio,
1506 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1508 if ( theTgtAspectRatio < 1.0 )
1509 theTgtAspectRatio = 1.0;
1511 SMESH::Controls::AspectRatio aQualityFunc;
1513 SMESHDS_Mesh* aMesh = GetMeshDS();
1515 if ( theElems.empty() ) {
1516 // add all faces to theElems
1517 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1518 while ( fIt->more() )
1519 theElems.insert( fIt->next() );
1521 // get all face ids theElems are on
1522 set< int > faceIdSet;
1523 set< const SMDS_MeshElement* >::iterator itElem;
1525 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1526 int fId = FindShape( *itElem );
1527 // check that corresponding submesh exists and a shape is face
1529 faceIdSet.find( fId ) == faceIdSet.end() &&
1530 aMesh->MeshElements( fId )) {
1531 TopoDS_Shape F = aMesh->IndexToShape( fId );
1532 if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1533 faceIdSet.insert( fId );
1536 faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1538 // ===============================================
1539 // smooth elements on each TopoDS_Face separately
1540 // ===============================================
1542 set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1543 for ( ; fId != faceIdSet.rend(); ++fId )
1545 // get face surface and submesh
1546 Handle(Geom_Surface) surface;
1547 SMESHDS_SubMesh* faceSubMesh = 0;
1549 double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
1550 double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1551 bool isUPeriodic = false, isVPeriodic = false;
1553 face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1554 surface = BRep_Tool::Surface( face );
1555 faceSubMesh = aMesh->MeshElements( *fId );
1556 fToler2 = BRep_Tool::Tolerance( face );
1557 fToler2 *= fToler2 * 10.;
1558 isUPeriodic = surface->IsUPeriodic();
1560 vPeriod = surface->UPeriod();
1561 isVPeriodic = surface->IsVPeriodic();
1563 uPeriod = surface->VPeriod();
1564 surface->Bounds( u1, u2, v1, v2 );
1566 // ---------------------------------------------------------
1567 // for elements on a face, find movable and fixed nodes and
1568 // compute UV for them
1569 // ---------------------------------------------------------
1570 bool checkBoundaryNodes = false;
1571 set<const SMDS_MeshNode*> setMovableNodes;
1572 map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1573 list< gp_XY > listUV; // uvs the 2 uvMaps refer to
1574 list< const SMDS_MeshElement* > elemsOnFace;
1576 Extrema_GenExtPS projector;
1577 GeomAdaptor_Surface surfAdaptor;
1578 if ( !surface.IsNull() ) {
1579 surfAdaptor.Load( surface );
1580 projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1582 int nbElemOnFace = 0;
1583 itElem = theElems.begin();
1584 // loop on not yet smoothed elements: look for elems on a face
1585 while ( itElem != theElems.end() )
1587 if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
1588 break; // all elements found
1590 const SMDS_MeshElement* elem = (*itElem);
1591 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1592 ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1596 elemsOnFace.push_back( elem );
1597 theElems.erase( itElem++ );
1600 // get movable nodes of elem
1601 const SMDS_MeshNode* node;
1602 SMDS_TypeOfPosition posType;
1603 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1604 while ( itN->more() ) {
1605 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1606 const SMDS_PositionPtr& pos = node->GetPosition();
1607 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1608 if (posType != SMDS_TOP_EDGE &&
1609 posType != SMDS_TOP_VERTEX &&
1610 theFixedNodes.find( node ) == theFixedNodes.end())
1612 // check if all faces around the node are on faceSubMesh
1613 // because a node on edge may be bound to face
1614 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1616 if ( faceSubMesh ) {
1617 while ( eIt->more() && all ) {
1618 const SMDS_MeshElement* e = eIt->next();
1619 if ( e->GetType() == SMDSAbs_Face )
1620 all = faceSubMesh->Contains( e );
1624 setMovableNodes.insert( node );
1626 checkBoundaryNodes = true;
1628 if ( posType == SMDS_TOP_3DSPACE )
1629 checkBoundaryNodes = true;
1632 if ( surface.IsNull() )
1635 // get nodes to check UV
1636 list< const SMDS_MeshNode* > uvCheckNodes;
1637 itN = elem->nodesIterator();
1638 while ( itN->more() ) {
1639 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1640 if ( uvMap.find( node ) == uvMap.end() )
1641 uvCheckNodes.push_back( node );
1642 // add nodes of elems sharing node
1643 // SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1644 // while ( eIt->more() ) {
1645 // const SMDS_MeshElement* e = eIt->next();
1646 // if ( e != elem && e->GetType() == SMDSAbs_Face ) {
1647 // SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1648 // while ( nIt->more() ) {
1649 // const SMDS_MeshNode* n =
1650 // static_cast<const SMDS_MeshNode*>( nIt->next() );
1651 // if ( uvMap.find( n ) == uvMap.end() )
1652 // uvCheckNodes.push_back( n );
1658 list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
1659 for ( ; n != uvCheckNodes.end(); ++n )
1663 const SMDS_PositionPtr& pos = node->GetPosition();
1664 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1666 switch ( posType ) {
1667 case SMDS_TOP_FACE: {
1668 SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1669 uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1672 case SMDS_TOP_EDGE: {
1673 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1674 Handle(Geom2d_Curve) pcurve;
1675 if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
1676 pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
1677 if ( !pcurve.IsNull() ) {
1678 double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
1679 uv = pcurve->Value( u ).XY();
1683 case SMDS_TOP_VERTEX: {
1684 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1685 if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
1686 uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
1691 // check existing UV
1692 bool project = true;
1693 gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1694 double dist1 = DBL_MAX, dist2 = 0;
1695 if ( posType != SMDS_TOP_3DSPACE ) {
1696 dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
1697 project = dist1 > fToler2;
1699 if ( project ) { // compute new UV
1701 if ( !getClosestUV( projector, pNode, newUV )) {
1702 MESSAGE("Node Projection Failed " << node);
1706 newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
1708 newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
1710 if ( posType != SMDS_TOP_3DSPACE )
1711 dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
1712 if ( dist2 < dist1 )
1716 // store UV in the map
1717 listUV.push_back( uv );
1718 uvMap.insert( make_pair( node, &listUV.back() ));
1720 } // loop on not yet smoothed elements
1722 if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
1723 checkBoundaryNodes = true;
1725 // fix nodes on mesh boundary
1727 if ( checkBoundaryNodes )
1729 typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1730 map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1731 map< TLink, int >::iterator link_nb;
1732 // put all elements links to linkNbMap
1733 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1734 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1736 // put elem nodes in array
1737 vector< const SMDS_MeshNode* > nodes;
1738 nodes.reserve( (*elemIt)->NbNodes() + 1 );
1739 SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1740 while ( itN->more() )
1741 nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1742 nodes.push_back( nodes.front() );
1743 // loop on elem links: insert them in linkNbMap
1744 for ( int iN = 1; iN < nodes.size(); ++iN ) {
1746 if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1747 link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1749 link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1750 link_nb = linkNbMap.find( link );
1751 if ( link_nb == linkNbMap.end() )
1752 linkNbMap.insert( make_pair ( link, 1 ));
1757 // remove nodes that are in links encountered only once from setMovableNodes
1758 for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1759 if ( link_nb->second == 1 ) {
1760 setMovableNodes.erase( link_nb->first.first );
1761 setMovableNodes.erase( link_nb->first.second );
1766 // -----------------------------------------------------
1767 // for nodes on seam edge, compute one more UV ( uvMap2 );
1768 // find movable nodes linked to nodes on seam and which
1769 // are to be smoothed using the second UV ( uvMap2 )
1770 // -----------------------------------------------------
1772 set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1773 if ( !surface.IsNull() )
1775 TopExp_Explorer eExp( face, TopAbs_EDGE );
1776 for ( ; eExp.More(); eExp.Next() )
1778 TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1779 if ( !BRep_Tool::IsClosed( edge, face ))
1781 SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1782 if ( !sm ) continue;
1783 // find out which parameter varies for a node on seam
1786 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1787 if ( pcurve.IsNull() ) continue;
1788 uv1 = pcurve->Value( f );
1790 pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1791 if ( pcurve.IsNull() ) continue;
1792 uv2 = pcurve->Value( f );
1793 int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1795 if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1796 gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1798 // get nodes on seam and its vertices
1799 list< const SMDS_MeshNode* > seamNodes;
1800 SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1801 while ( nSeamIt->more() )
1802 seamNodes.push_back( nSeamIt->next() );
1803 TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1804 for ( ; vExp.More(); vExp.Next() ) {
1805 sm = aMesh->MeshElements( vExp.Current() );
1807 nSeamIt = sm->GetNodes();
1808 while ( nSeamIt->more() )
1809 seamNodes.push_back( nSeamIt->next() );
1812 // loop on nodes on seam
1813 list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1814 for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1816 const SMDS_MeshNode* nSeam = *noSeIt;
1817 map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1818 if ( n_uv == uvMap.end() )
1821 n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1822 // set the second UV
1823 listUV.push_back( *n_uv->second );
1824 listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1825 if ( uvMap2.empty() )
1826 uvMap2 = uvMap; // copy the uvMap contents
1827 uvMap2[ nSeam ] = &listUV.back();
1829 // collect movable nodes linked to ones on seam in nodesNearSeam
1830 SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1831 while ( eIt->more() )
1833 const SMDS_MeshElement* e = eIt->next();
1834 if ( e->GetType() != SMDSAbs_Face )
1836 int nbUseMap1 = 0, nbUseMap2 = 0;
1837 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1838 while ( nIt->more() )
1840 const SMDS_MeshNode* n =
1841 static_cast<const SMDS_MeshNode*>( nIt->next() );
1843 setMovableNodes.find( n ) == setMovableNodes.end() )
1845 // add only nodes being closer to uv2 than to uv1
1846 gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1847 0.5 * ( n->Y() + nSeam->Y() ),
1848 0.5 * ( n->Z() + nSeam->Z() ));
1850 getClosestUV( projector, pMid, uv );
1851 if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1852 nodesNearSeam.insert( n );
1858 // for centroidalSmooth all element nodes must
1859 // be on one side of a seam
1860 if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1862 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1863 while ( nIt->more() ) {
1864 const SMDS_MeshNode* n =
1865 static_cast<const SMDS_MeshNode*>( nIt->next() );
1866 setMovableNodes.erase( n );
1870 } // loop on nodes on seam
1871 } // loop on edge of a face
1872 } // if ( !face.IsNull() )
1874 if ( setMovableNodes.empty() ) {
1875 MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
1876 continue; // goto next face
1884 double maxRatio = -1., maxDisplacement = -1.;
1885 set<const SMDS_MeshNode*>::iterator nodeToMove;
1886 for ( it = 0; it < theNbIterations; it++ )
1888 maxDisplacement = 0.;
1889 nodeToMove = setMovableNodes.begin();
1890 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1892 const SMDS_MeshNode* node = (*nodeToMove);
1893 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1896 bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1897 if ( theSmoothMethod == LAPLACIAN )
1898 laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1900 centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1902 // node displacement
1903 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1904 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1905 if ( aDispl > maxDisplacement )
1906 maxDisplacement = aDispl;
1908 // no node movement => exit
1909 if ( maxDisplacement < 1.e-16 ) {
1910 MESSAGE("-- no node movement --");
1914 // check elements quality
1916 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1917 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1919 const SMDS_MeshElement* elem = (*elemIt);
1920 if ( !elem || elem->GetType() != SMDSAbs_Face )
1922 SMESH::Controls::TSequenceOfXYZ aPoints;
1923 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1924 double aValue = aQualityFunc.GetValue( aPoints );
1925 if ( aValue > maxRatio )
1929 if ( maxRatio <= theTgtAspectRatio ) {
1930 MESSAGE("-- quality achived --");
1933 if (it+1 == theNbIterations) {
1934 MESSAGE("-- Iteration limit exceeded --");
1936 } // smoothing iterations
1938 MESSAGE(" Face id: " << *fId <<
1939 " Nb iterstions: " << it <<
1940 " Displacement: " << maxDisplacement <<
1941 " Aspect Ratio " << maxRatio);
1943 // ---------------------------------------
1944 // new nodes positions are computed,
1945 // record movement in DS and set new UV
1946 // ---------------------------------------
1948 nodeToMove = setMovableNodes.begin();
1949 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1951 SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1952 aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1953 map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1954 if ( node_uv != uvMap.end() ) {
1955 gp_XY* uv = node_uv->second;
1957 ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1961 } // loop on face ids
1964 //=======================================================================
1965 //function : isReverse
1966 //purpose : Return true if normal of prevNodes is not co-directied with
1967 // gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1968 // iNotSame is where prevNodes and nextNodes are different
1969 //=======================================================================
1971 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1972 const SMDS_MeshNode* nextNodes[],
1976 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1977 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1979 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1980 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1981 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1982 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1984 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1985 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1986 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1987 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1989 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1991 return (vA ^ vB) * vN < 0.0;
1994 //=======================================================================
1995 //function : sweepElement
1997 //=======================================================================
1999 static void sweepElement(SMESHDS_Mesh* aMesh,
2000 const SMDS_MeshElement* elem,
2001 const vector<TNodeOfNodeListMapItr> & newNodesItVec,
2002 list<const SMDS_MeshElement*>& newElems)
2004 // Loop on elem nodes:
2005 // find new nodes and detect same nodes indices
2006 int nbNodes = elem->NbNodes();
2007 list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
2008 const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
2009 int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
2011 for ( iNode = 0; iNode < nbNodes; iNode++ )
2013 TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
2014 const SMDS_MeshNode* node = nnIt->first;
2015 const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
2016 if ( listNewNodes.empty() )
2019 itNN[ iNode ] = listNewNodes.begin();
2020 prevNod[ iNode ] = node;
2021 nextNod[ iNode ] = listNewNodes.front();
2022 if ( prevNod[ iNode ] != nextNod [ iNode ])
2023 iNotSameNode = iNode;
2029 if ( nbSame == nbNodes || nbSame > 2) {
2030 MESSAGE( " Too many same nodes of element " << elem->GetID() );
2034 int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
2036 iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
2037 iAfterSame = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2038 iOpposSame = ( iSameNode - 2 < 0 ? iSameNode + 2 : iSameNode - 2 );
2041 // check element orientation
2043 if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2044 //MESSAGE("Reversed elem " << elem );
2048 int iAB = iAfterSame + iBeforeSame;
2049 iBeforeSame = iAB - iBeforeSame;
2050 iAfterSame = iAB - iAfterSame;
2054 // make new elements
2055 int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
2056 for (iStep = 0; iStep < nbSteps; iStep++ )
2059 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2060 nextNod[ iNode ] = *itNN[ iNode ];
2063 SMDS_MeshElement* aNewElem = 0;
2070 aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2076 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2077 nextNod[ 1 ], nextNod[ 0 ] );
2079 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2080 nextNod[ iNotSameNode ] );
2083 case 3: { // TRIANGLE
2085 if ( nbSame == 0 ) // --- pentahedron
2086 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2087 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2089 else if ( nbSame == 1 ) // --- pyramid
2090 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2091 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2092 nextNod[ iSameNode ]);
2094 else // 2 same nodes: --- tetrahedron
2095 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2096 nextNod[ iNotSameNode ]);
2099 case 4: { // QUADRANGLE
2101 if ( nbSame == 0 ) // --- hexahedron
2102 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2103 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2105 else if ( nbSame == 1 ) // --- pyramid + pentahedron
2107 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2108 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2109 nextNod[ iSameNode ]);
2110 newElems.push_back( aNewElem );
2111 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2112 prevNod[ iBeforeSame ], nextNod[ iAfterSame ],
2113 nextNod[ iOpposSame ], nextNod[ iBeforeSame ] );
2115 else if ( nbSame == 2 ) // pentahedron
2117 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2118 // iBeforeSame is same too
2119 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2120 nextNod[ iOpposSame ], prevNod[ iSameNode ],
2121 prevNod[ iAfterSame ], nextNod[ iAfterSame ]);
2123 // iAfterSame is same too
2124 aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2125 nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2126 prevNod[ iOpposSame ], nextNod[ iOpposSame ]);
2131 // realized for extrusion only
2132 vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2133 vector<int> quantities (nbNodes + 2);
2135 quantities[0] = nbNodes; // bottom of prism
2136 for (int inode = 0; inode < nbNodes; inode++) {
2137 polyedre_nodes[inode] = prevNod[inode];
2140 quantities[1] = nbNodes; // top of prism
2141 for (int inode = 0; inode < nbNodes; inode++) {
2142 polyedre_nodes[nbNodes + inode] = nextNod[inode];
2145 for (int iface = 0; iface < nbNodes; iface++) {
2146 quantities[iface + 2] = 4;
2147 int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2148 polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2149 polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2150 polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2151 polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2153 aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2157 newElems.push_back( aNewElem );
2159 // set new prev nodes
2160 for ( iNode = 0; iNode < nbNodes; iNode++ )
2161 prevNod[ iNode ] = nextNod[ iNode ];
2166 //=======================================================================
2167 //function : makeWalls
2168 //purpose : create 1D and 2D elements around swept elements
2169 //=======================================================================
2171 static void makeWalls (SMESHDS_Mesh* aMesh,
2172 TNodeOfNodeListMap & mapNewNodes,
2173 TElemOfElemListMap & newElemsMap,
2174 TElemOfVecOfNnlmiMap & elemNewNodesMap,
2175 set<const SMDS_MeshElement*>& elemSet)
2177 ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2179 // Find nodes belonging to only one initial element - sweep them to get edges.
2181 TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2182 for ( ; nList != mapNewNodes.end(); nList++ )
2184 const SMDS_MeshNode* node =
2185 static_cast<const SMDS_MeshNode*>( nList->first );
2186 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2187 int nbInitElems = 0;
2188 while ( eIt->more() && nbInitElems < 2 )
2189 if ( elemSet.find( eIt->next() ) != elemSet.end() )
2191 if ( nbInitElems < 2 ) {
2192 vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2193 list<const SMDS_MeshElement*> newEdges;
2194 sweepElement( aMesh, node, newNodesItVec, newEdges );
2198 // Make a ceiling for each element ie an equal element of last new nodes.
2199 // Find free links of faces - make edges and sweep them into faces.
2201 TElemOfElemListMap::iterator itElem = newElemsMap.begin();
2202 TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2203 for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2205 const SMDS_MeshElement* elem = itElem->first;
2206 vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2208 if ( elem->GetType() == SMDSAbs_Edge )
2210 // create a ceiling edge
2211 aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2212 vecNewNodes[ 1 ]->second.back() );
2214 if ( elem->GetType() != SMDSAbs_Face )
2217 bool hasFreeLinks = false;
2219 set<const SMDS_MeshElement*> avoidSet;
2220 avoidSet.insert( elem );
2222 // loop on a face nodes
2223 set<const SMDS_MeshNode*> aFaceLastNodes;
2224 int iNode, nbNodes = vecNewNodes.size();
2225 for ( iNode = 0; iNode < nbNodes; iNode++ )
2227 aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2228 // look for free links of a face
2229 int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2230 const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2231 const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2232 // check if a link is free
2233 if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2235 hasFreeLinks = true;
2236 // make an edge and a ceiling for a new edge
2237 if ( !aMesh->FindEdge( n1, n2 ))
2238 aMesh->AddEdge( n1, n2 );
2239 n1 = vecNewNodes[ iNode ]->second.back();
2240 n2 = vecNewNodes[ iNext ]->second.back();
2241 if ( !aMesh->FindEdge( n1, n2 ))
2242 aMesh->AddEdge( n1, n2 );
2245 // sweep free links into faces
2249 list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2250 int iStep, nbSteps = vecNewNodes[0]->second.size();
2251 int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2253 set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2254 for ( iNode = 0; iNode < nbNodes; iNode++ )
2255 initNodeSet.insert( vecNewNodes[ iNode ]->first );
2257 for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2259 list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2261 while ( iVol++ < volNb ) v++;
2262 // find indices of free faces of a volume
2264 SMDS_VolumeTool vTool( *v );
2265 int iF, nbF = vTool.NbFaces();
2266 for ( iF = 0; iF < nbF; iF ++ )
2267 if (vTool.IsFreeFace( iF ) &&
2268 vTool.GetFaceNodes( iF, faceNodeSet ) &&
2269 initNodeSet != faceNodeSet) // except an initial face
2270 fInd.push_back( iF );
2274 // create faces for all steps
2275 for ( iStep = 0; iStep < nbSteps; iStep++ )
2278 vTool.SetExternalNormal();
2279 list< int >::iterator ind = fInd.begin();
2280 for ( ; ind != fInd.end(); ind++ )
2282 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2283 switch ( vTool.NbFaceNodes( *ind ) ) {
2285 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2287 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2290 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2291 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2292 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2293 polygon_nodes[inode] = nodes[inode];
2295 aMesh->AddPolygonalFace(polygon_nodes);
2300 // go to the next volume
2302 while ( iVol++ < nbVolumesByStep ) v++;
2305 } // sweep free links into faces
2307 // make a ceiling face with a normal external to a volume
2309 SMDS_VolumeTool lastVol( itElem->second.back() );
2310 int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2313 lastVol.SetExternalNormal();
2314 const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2315 switch ( lastVol.NbFaceNodes( iF ) ) {
2317 if (!hasFreeLinks ||
2318 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2319 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2322 if (!hasFreeLinks ||
2323 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2324 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2328 int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2329 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2330 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2331 polygon_nodes[inode] = nodes[inode];
2333 if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2334 aMesh->AddPolygonalFace(polygon_nodes);
2340 } // loop on swept elements
2343 //=======================================================================
2344 //function : RotationSweep
2346 //=======================================================================
2348 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2349 const gp_Ax1& theAxis,
2350 const double theAngle,
2351 const int theNbSteps,
2352 const double theTol)
2354 MESSAGE( "RotationSweep()");
2356 aTrsf.SetRotation( theAxis, theAngle );
2358 gp_Lin aLine( theAxis );
2359 double aSqTol = theTol * theTol;
2361 SMESHDS_Mesh* aMesh = GetMeshDS();
2363 TNodeOfNodeListMap mapNewNodes;
2364 TElemOfVecOfNnlmiMap mapElemNewNodes;
2365 TElemOfElemListMap newElemsMap;
2368 set< const SMDS_MeshElement* >::iterator itElem;
2369 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2371 const SMDS_MeshElement* elem = (*itElem);
2374 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2375 newNodesItVec.reserve( elem->NbNodes() );
2377 // loop on elem nodes
2378 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2379 while ( itN->more() ) {
2381 // check if a node has been already sweeped
2382 const SMDS_MeshNode* node =
2383 static_cast<const SMDS_MeshNode*>( itN->next() );
2384 TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2385 if ( nIt == mapNewNodes.end() )
2387 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2388 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2391 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2393 aXYZ.Coord( coord[0], coord[1], coord[2] );
2394 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2395 const SMDS_MeshNode * newNode = node;
2396 for ( int i = 0; i < theNbSteps; i++ ) {
2398 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2399 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2401 listNewNodes.push_back( newNode );
2404 newNodesItVec.push_back( nIt );
2406 // make new elements
2407 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2410 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2415 //=======================================================================
2416 //function : CreateNode
2418 //=======================================================================
2419 const SMDS_MeshNode* SMESH_MeshEditor::CreateNode(const double x,
2422 const double tolnode)
2425 SMESHDS_Mesh * aMesh = myMesh->GetMeshDS();
2426 // try to search in sequence of existing nodes
2427 SMDS_NodeIteratorPtr itn = aMesh->nodesIterator();
2428 while(itn->more()) {
2429 const SMDS_MeshNode* aN = static_cast<const SMDS_MeshNode*> (itn->next());
2430 gp_Pnt P2(aN->X(),aN->Y(),aN->Z());
2431 if(P1.Distance(P2)<tolnode)
2434 // create new node and return it
2435 const SMDS_MeshNode* NewNode = aMesh->AddNode(x,y,z);
2440 //=======================================================================
2441 //function : ExtrusionSweep
2443 //=======================================================================
2445 void SMESH_MeshEditor::ExtrusionSweep
2446 (set<const SMDS_MeshElement*> & theElems,
2447 const gp_Vec& theStep,
2448 const int theNbSteps,
2449 TElemOfElemListMap& newElemsMap,
2451 const double theTolerance)
2454 aTrsf.SetTranslation( theStep );
2456 SMESHDS_Mesh* aMesh = GetMeshDS();
2458 TNodeOfNodeListMap mapNewNodes;
2459 TElemOfVecOfNnlmiMap mapElemNewNodes;
2460 //TElemOfElemListMap newElemsMap;
2463 set< const SMDS_MeshElement* >::iterator itElem;
2464 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2466 // check element type
2467 const SMDS_MeshElement* elem = (*itElem);
2471 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2472 newNodesItVec.reserve( elem->NbNodes() );
2474 // loop on elem nodes
2475 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2476 while ( itN->more() ) {
2478 // check if a node has been already sweeped
2479 const SMDS_MeshNode* node =
2480 static_cast<const SMDS_MeshNode*>( itN->next() );
2481 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2482 if ( nIt == mapNewNodes.end() )
2484 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2485 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2488 double coord[] = { node->X(), node->Y(), node->Z() };
2489 for ( int i = 0; i < theNbSteps; i++ ) {
2490 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2491 if( theFlags & EXTRUSION_FLAG_SEW ) {
2492 const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1],
2493 coord[2], theTolerance);
2494 listNewNodes.push_back( newNode );
2497 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2498 listNewNodes.push_back( newNode );
2502 newNodesItVec.push_back( nIt );
2504 // make new elements
2505 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2507 if( theFlags & EXTRUSION_FLAG_BOUNDARY ) {
2508 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2512 //=======================================================================
2513 //class : SMESH_MeshEditor_PathPoint
2514 //purpose : auxiliary class
2515 //=======================================================================
2516 class SMESH_MeshEditor_PathPoint {
2518 SMESH_MeshEditor_PathPoint() {
2519 myPnt.SetCoord(99., 99., 99.);
2520 myTgt.SetCoord(1.,0.,0.);
2524 void SetPnt(const gp_Pnt& aP3D){
2527 void SetTangent(const gp_Dir& aTgt){
2530 void SetAngle(const double& aBeta){
2533 void SetParameter(const double& aPrm){
2536 const gp_Pnt& Pnt()const{
2539 const gp_Dir& Tangent()const{
2542 double Angle()const{
2545 double Parameter()const{
2556 //=======================================================================
2557 //function : ExtrusionAlongTrack
2559 //=======================================================================
2560 SMESH_MeshEditor::Extrusion_Error
2561 SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2562 SMESH_subMesh* theTrack,
2563 const SMDS_MeshNode* theN1,
2564 const bool theHasAngles,
2565 std::list<double>& theAngles,
2566 const bool theHasRefPoint,
2567 const gp_Pnt& theRefPoint)
2569 MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2570 int j, aNbTP, aNbE, aNb;
2571 double aT1, aT2, aT, aAngle, aX, aY, aZ;
2572 std::list<double> aPrms;
2573 std::list<double>::iterator aItD;
2574 std::set< const SMDS_MeshElement* >::iterator itElem;
2576 Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2580 Handle(Geom_Curve) aC3D;
2581 TopoDS_Edge aTrackEdge;
2582 TopoDS_Vertex aV1, aV2;
2584 SMDS_ElemIteratorPtr aItE;
2585 SMDS_NodeIteratorPtr aItN;
2586 SMDSAbs_ElementType aTypeE;
2588 TNodeOfNodeListMap mapNewNodes;
2589 TElemOfVecOfNnlmiMap mapElemNewNodes;
2590 TElemOfElemListMap newElemsMap;
2593 aTolVec2=aTolVec*aTolVec;
2596 aNbE = theElements.size();
2599 return EXTR_NO_ELEMENTS;
2601 // 1.1 Track Pattern
2604 SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2606 aItE = pSubMeshDS->GetElements();
2607 while ( aItE->more() ) {
2608 const SMDS_MeshElement* pE = aItE->next();
2609 aTypeE = pE->GetType();
2610 // Pattern must contain links only
2611 if ( aTypeE != SMDSAbs_Edge )
2612 return EXTR_PATH_NOT_EDGE;
2615 const TopoDS_Shape& aS = theTrack->GetSubShape();
2616 // Sub shape for the Pattern must be an Edge
2617 if ( aS.ShapeType() != TopAbs_EDGE )
2618 return EXTR_BAD_PATH_SHAPE;
2620 aTrackEdge = TopoDS::Edge( aS );
2621 // the Edge must not be degenerated
2622 if ( BRep_Tool::Degenerated( aTrackEdge ) )
2623 return EXTR_BAD_PATH_SHAPE;
2625 TopExp::Vertices( aTrackEdge, aV1, aV2 );
2626 aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2627 aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2629 aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2630 const SMDS_MeshNode* aN1 = aItN->next();
2632 aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2633 const SMDS_MeshNode* aN2 = aItN->next();
2635 // starting node must be aN1 or aN2
2636 if ( !( aN1 == theN1 || aN2 == theN1 ) )
2637 return EXTR_BAD_STARTING_NODE;
2639 aNbTP = pSubMeshDS->NbNodes() + 2;
2642 vector<double> aAngles( aNbTP );
2644 for ( j=0; j < aNbTP; ++j ) {
2648 if ( theHasAngles ) {
2649 aItD = theAngles.begin();
2650 for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2652 aAngles[j] = aAngle;
2656 // 2. Collect parameters on the track edge
2657 aPrms.push_back( aT1 );
2658 aPrms.push_back( aT2 );
2660 aItN = pSubMeshDS->GetNodes();
2661 while ( aItN->more() ) {
2662 const SMDS_MeshNode* pNode = aItN->next();
2663 const SMDS_EdgePosition* pEPos =
2664 static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2665 aT = pEPos->GetUParameter();
2666 aPrms.push_back( aT );
2671 if ( aN1 == theN1 ) {
2683 SMESH_MeshEditor_PathPoint aPP;
2684 vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2686 aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2688 aItD = aPrms.begin();
2689 for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2691 aC3D->D1( aT, aP3D, aVec );
2692 aL2 = aVec.SquareMagnitude();
2693 if ( aL2 < aTolVec2 )
2694 return EXTR_CANT_GET_TANGENT;
2696 gp_Dir aTgt( aVec );
2697 aAngle = aAngles[j];
2700 aPP.SetTangent( aTgt );
2701 aPP.SetAngle( aAngle );
2702 aPP.SetParameter( aT );
2706 // 3. Center of rotation aV0
2708 if ( !theHasRefPoint ) {
2710 aGC.SetCoord( 0.,0.,0. );
2712 itElem = theElements.begin();
2713 for ( ; itElem != theElements.end(); itElem++ ) {
2714 const SMDS_MeshElement* elem = (*itElem);
2716 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2717 while ( itN->more() ) {
2718 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2723 if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2724 list<const SMDS_MeshNode*> aLNx;
2725 mapNewNodes[node] = aLNx;
2727 gp_XYZ aXYZ( aX, aY, aZ );
2735 } // if (!theHasRefPoint) {
2736 mapNewNodes.clear();
2738 // 4. Processing the elements
2739 SMESHDS_Mesh* aMesh = GetMeshDS();
2741 for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2742 // check element type
2743 const SMDS_MeshElement* elem = (*itElem);
2744 aTypeE = elem->GetType();
2745 if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2748 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2749 newNodesItVec.reserve( elem->NbNodes() );
2751 // loop on elem nodes
2752 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2753 while ( itN->more() ) {
2755 // check if a node has been already processed
2756 const SMDS_MeshNode* node =
2757 static_cast<const SMDS_MeshNode*>( itN->next() );
2758 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2759 if ( nIt == mapNewNodes.end() ) {
2760 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2761 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2764 aX = node->X(); aY = node->Y(); aZ = node->Z();
2766 Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2767 gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2768 gp_Ax1 anAx1, anAxT1T0;
2769 gp_Dir aDT1x, aDT0x, aDT1T0;
2774 aPN0.SetCoord(aX, aY, aZ);
2776 const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2778 aDT0x= aPP0.Tangent();
2780 for ( j = 1; j < aNbTP; ++j ) {
2781 const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2783 aDT1x = aPP1.Tangent();
2784 aAngle1x = aPP1.Angle();
2786 gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2788 gp_Vec aV01x( aP0x, aP1x );
2789 aTrsf.SetTranslation( aV01x );
2792 aV1x = aV0x.Transformed( aTrsf );
2793 aPN1 = aPN0.Transformed( aTrsf );
2795 // rotation 1 [ T1,T0 ]
2796 aAngleT1T0=-aDT1x.Angle( aDT0x );
2797 if (fabs(aAngleT1T0) > aTolAng) {
2799 anAxT1T0.SetLocation( aV1x );
2800 anAxT1T0.SetDirection( aDT1T0 );
2801 aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2803 aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2807 if ( theHasAngles ) {
2808 anAx1.SetLocation( aV1x );
2809 anAx1.SetDirection( aDT1x );
2810 aTrsfRot.SetRotation( anAx1, aAngle1x );
2812 aPN1 = aPN1.Transformed( aTrsfRot );
2819 const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2820 listNewNodes.push_back( newNode );
2828 newNodesItVec.push_back( nIt );
2830 // make new elements
2831 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2834 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2839 //=======================================================================
2840 //function : Transform
2842 //=======================================================================
2844 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2845 const gp_Trsf& theTrsf,
2849 switch ( theTrsf.Form() ) {
2855 needReverse = false;
2858 SMESHDS_Mesh* aMesh = GetMeshDS();
2860 // map old node to new one
2861 TNodeNodeMap nodeMap;
2863 // elements sharing moved nodes; those of them which have all
2864 // nodes mirrored but are not in theElems are to be reversed
2865 set<const SMDS_MeshElement*> inverseElemSet;
2868 set< const SMDS_MeshElement* >::iterator itElem;
2869 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2871 const SMDS_MeshElement* elem = (*itElem);
2875 // loop on elem nodes
2876 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2877 while ( itN->more() ) {
2879 // check if a node has been already transformed
2880 const SMDS_MeshNode* node =
2881 static_cast<const SMDS_MeshNode*>( itN->next() );
2882 if (nodeMap.find( node ) != nodeMap.end() )
2886 coord[0] = node->X();
2887 coord[1] = node->Y();
2888 coord[2] = node->Z();
2889 theTrsf.Transforms( coord[0], coord[1], coord[2] );
2890 const SMDS_MeshNode * newNode = node;
2892 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2894 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2895 // node position on shape becomes invalid
2896 const_cast< SMDS_MeshNode* > ( node )->SetPosition
2897 ( SMDS_SpacePosition::originSpacePosition() );
2899 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2901 // keep inverse elements
2902 if ( !theCopy && needReverse ) {
2903 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2904 while ( invElemIt->more() )
2905 inverseElemSet.insert( invElemIt->next() );
2910 // either new elements are to be created
2911 // or a mirrored element are to be reversed
2912 if ( !theCopy && !needReverse)
2915 if ( !inverseElemSet.empty()) {
2916 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2917 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2918 theElems.insert( *invElemIt );
2921 // replicate or reverse elements
2924 REV_TETRA = 0, // = nbNodes - 4
2925 REV_PYRAMID = 1, // = nbNodes - 4
2926 REV_PENTA = 2, // = nbNodes - 4
2928 REV_HEXA = 4, // = nbNodes - 4
2932 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
2933 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
2934 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
2935 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
2936 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
2937 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
2940 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2942 const SMDS_MeshElement* elem = (*itElem);
2943 if ( !elem || elem->GetType() == SMDSAbs_Node )
2946 int nbNodes = elem->NbNodes();
2947 int elemType = elem->GetType();
2949 if (elem->IsPoly()) {
2950 // Polygon or Polyhedral Volume
2951 switch ( elemType ) {
2954 vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2956 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2957 while (itN->more()) {
2958 const SMDS_MeshNode* node =
2959 static_cast<const SMDS_MeshNode*>(itN->next());
2960 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2961 if (nodeMapIt == nodeMap.end())
2962 break; // not all nodes transformed
2964 // reverse mirrored faces and volumes
2965 poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2967 poly_nodes[iNode] = (*nodeMapIt).second;
2971 if ( iNode != nbNodes )
2972 continue; // not all nodes transformed
2975 aMesh->AddPolygonalFace(poly_nodes);
2977 aMesh->ChangePolygonNodes(elem, poly_nodes);
2981 case SMDSAbs_Volume:
2983 // ATTENTION: Reversing is not yet done!!!
2984 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2985 (const SMDS_PolyhedralVolumeOfNodes*) elem;
2987 MESSAGE("Warning: bad volumic element");
2991 vector<const SMDS_MeshNode*> poly_nodes;
2992 vector<int> quantities;
2994 bool allTransformed = true;
2995 int nbFaces = aPolyedre->NbFaces();
2996 for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2997 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2998 for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2999 const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
3000 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
3001 if (nodeMapIt == nodeMap.end()) {
3002 allTransformed = false; // not all nodes transformed
3004 poly_nodes.push_back((*nodeMapIt).second);
3007 quantities.push_back(nbFaceNodes);
3009 if ( !allTransformed )
3010 continue; // not all nodes transformed
3013 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
3015 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3025 int* i = index[ FORWARD ];
3026 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
3027 if ( elemType == SMDSAbs_Face )
3028 i = index[ REV_FACE ];
3030 i = index[ nbNodes - 4 ];
3032 // find transformed nodes
3033 const SMDS_MeshNode* nodes[8];
3035 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3036 while ( itN->more() )
3038 const SMDS_MeshNode* node =
3039 static_cast<const SMDS_MeshNode*>( itN->next() );
3040 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
3041 if ( nodeMapIt == nodeMap.end() )
3042 break; // not all nodes transformed
3043 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
3045 if ( iNode != nbNodes )
3046 continue; // not all nodes transformed
3050 // add a new element
3051 switch ( elemType ) {
3053 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
3057 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
3059 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
3061 case SMDSAbs_Volume:
3063 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
3064 else if ( nbNodes == 8 )
3065 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3066 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
3067 else if ( nbNodes == 6 )
3068 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3069 nodes[ 4 ], nodes[ 5 ]);
3070 else if ( nbNodes == 5 )
3071 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3079 // reverse element as it was reversed by transformation
3081 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3086 //=======================================================================
3087 //function : FindCoincidentNodes
3088 //purpose : Return list of group of nodes close to each other within theTolerance
3089 // Search among theNodes or in the whole mesh if theNodes is empty.
3090 //=======================================================================
3092 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3093 const double theTolerance,
3094 TListOfListOfNodes & theGroupsOfNodes)
3096 double tol2 = theTolerance * theTolerance;
3098 list<const SMDS_MeshNode*> nodes;
3099 if ( theNodes.empty() )
3100 { // get all nodes in the mesh
3101 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3102 while ( nIt->more() )
3103 nodes.push_back( nIt->next() );
3107 nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3110 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3111 for ( ; it1 != nodes.end(); it1++ )
3113 const SMDS_MeshNode* n1 = *it1;
3114 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3116 list<const SMDS_MeshNode*> * groupPtr = 0;
3118 for ( it2++; it2 != nodes.end(); it2++ )
3120 const SMDS_MeshNode* n2 = *it2;
3121 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3122 if ( p1.SquareDistance( p2 ) <= tol2 )
3125 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3126 groupPtr = & theGroupsOfNodes.back();
3127 groupPtr->push_back( n1 );
3129 groupPtr->push_back( n2 );
3130 it2 = nodes.erase( it2 );
3137 //=======================================================================
3138 //function : SimplifyFace
3140 //=======================================================================
3141 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3142 vector<const SMDS_MeshNode *>& poly_nodes,
3143 vector<int>& quantities) const
3145 int nbNodes = faceNodes.size();
3150 set<const SMDS_MeshNode*> nodeSet;
3152 // get simple seq of nodes
3153 const SMDS_MeshNode* simpleNodes[ nbNodes ];
3154 int iSimple = 0, nbUnique = 0;
3156 simpleNodes[iSimple++] = faceNodes[0];
3158 for (int iCur = 1; iCur < nbNodes; iCur++) {
3159 if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3160 simpleNodes[iSimple++] = faceNodes[iCur];
3161 if (nodeSet.insert( faceNodes[iCur] ).second)
3165 int nbSimple = iSimple;
3166 if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3176 bool foundLoop = (nbSimple > nbUnique);
3179 set<const SMDS_MeshNode*> loopSet;
3180 for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3181 const SMDS_MeshNode* n = simpleNodes[iSimple];
3182 if (!loopSet.insert( n ).second) {
3186 int iC = 0, curLast = iSimple;
3187 for (; iC < curLast; iC++) {
3188 if (simpleNodes[iC] == n) break;
3190 int loopLen = curLast - iC;
3192 // create sub-element
3194 quantities.push_back(loopLen);
3195 for (; iC < curLast; iC++) {
3196 poly_nodes.push_back(simpleNodes[iC]);
3199 // shift the rest nodes (place from the first loop position)
3200 for (iC = curLast + 1; iC < nbSimple; iC++) {
3201 simpleNodes[iC - loopLen] = simpleNodes[iC];
3203 nbSimple -= loopLen;
3206 } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3207 } // while (foundLoop)
3211 quantities.push_back(iSimple);
3212 for (int i = 0; i < iSimple; i++)
3213 poly_nodes.push_back(simpleNodes[i]);
3219 //=======================================================================
3220 //function : MergeNodes
3221 //purpose : In each group, the cdr of nodes are substituted by the first one
3223 //=======================================================================
3225 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3227 SMESHDS_Mesh* aMesh = GetMeshDS();
3229 TNodeNodeMap nodeNodeMap; // node to replace - new node
3230 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3231 list< int > rmElemIds, rmNodeIds;
3233 // Fill nodeNodeMap and elems
3235 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3236 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3238 list<const SMDS_MeshNode*>& nodes = *grIt;
3239 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3240 const SMDS_MeshNode* nToKeep = *nIt;
3241 for ( ; nIt != nodes.end(); nIt++ )
3243 const SMDS_MeshNode* nToRemove = *nIt;
3244 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3245 if ( nToRemove != nToKeep ) {
3246 rmNodeIds.push_back( nToRemove->GetID() );
3247 AddToSameGroups( nToKeep, nToRemove, aMesh );
3250 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3251 while ( invElemIt->more() )
3252 elems.insert( invElemIt->next() );
3255 // Change element nodes or remove an element
3257 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3258 for ( ; eIt != elems.end(); eIt++ )
3260 const SMDS_MeshElement* elem = *eIt;
3261 int nbNodes = elem->NbNodes();
3262 int aShapeId = FindShape( elem );
3264 set<const SMDS_MeshNode*> nodeSet;
3265 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3266 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3268 // get new seq of nodes
3269 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3270 while ( itN->more() )
3272 const SMDS_MeshNode* n =
3273 static_cast<const SMDS_MeshNode*>( itN->next() );
3275 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3276 if ( nnIt != nodeNodeMap.end() ) { // n sticks
3278 iRepl[ nbRepl++ ] = iCur;
3280 curNodes[ iCur ] = n;
3281 bool isUnique = nodeSet.insert( n ).second;
3283 uniqueNodes[ iUnique++ ] = n;
3287 // Analyse element topology after replacement
3290 int nbUniqueNodes = nodeSet.size();
3291 if ( nbNodes != nbUniqueNodes ) // some nodes stick
3293 // Polygons and Polyhedral volumes
3294 if (elem->IsPoly()) {
3296 if (elem->GetType() == SMDSAbs_Face) {
3298 vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3300 for (; inode < nbNodes; inode++) {
3301 face_nodes[inode] = curNodes[inode];
3304 vector<const SMDS_MeshNode *> polygons_nodes;
3305 vector<int> quantities;
3306 int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3310 for (int iface = 0; iface < nbNew - 1; iface++) {
3311 int nbNodes = quantities[iface];
3312 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3313 for (int ii = 0; ii < nbNodes; ii++, inode++) {
3314 poly_nodes[ii] = polygons_nodes[inode];
3316 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3318 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3320 aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3322 rmElemIds.push_back(elem->GetID());
3325 } else if (elem->GetType() == SMDSAbs_Volume) {
3326 // Polyhedral volume
3327 if (nbUniqueNodes < 4) {
3328 rmElemIds.push_back(elem->GetID());
3330 // each face has to be analized in order to check volume validity
3331 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3332 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3334 int nbFaces = aPolyedre->NbFaces();
3336 vector<const SMDS_MeshNode *> poly_nodes;
3337 vector<int> quantities;
3339 for (int iface = 1; iface <= nbFaces; iface++) {
3340 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3341 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3343 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3344 const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3345 TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3346 if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3347 faceNode = (*nnIt).second;
3349 faceNodes[inode - 1] = faceNode;
3352 SimplifyFace(faceNodes, poly_nodes, quantities);
3355 if (quantities.size() > 3) {
3356 // to be done: remove coincident faces
3359 if (quantities.size() > 3)
3360 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3362 rmElemIds.push_back(elem->GetID());
3365 rmElemIds.push_back(elem->GetID());
3375 switch ( nbNodes ) {
3376 case 2: ///////////////////////////////////// EDGE
3377 isOk = false; break;
3378 case 3: ///////////////////////////////////// TRIANGLE
3379 isOk = false; break;
3381 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3383 else { //////////////////////////////////// QUADRANGLE
3384 if ( nbUniqueNodes < 3 )
3386 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3387 isOk = false; // opposite nodes stick
3390 case 6: ///////////////////////////////////// PENTAHEDRON
3391 if ( nbUniqueNodes == 4 ) {
3392 // ---------------------------------> tetrahedron
3394 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3395 // all top nodes stick: reverse a bottom
3396 uniqueNodes[ 0 ] = curNodes [ 1 ];
3397 uniqueNodes[ 1 ] = curNodes [ 0 ];
3399 else if (nbRepl == 3 &&
3400 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3401 // all bottom nodes stick: set a top before
3402 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3403 uniqueNodes[ 0 ] = curNodes [ 3 ];
3404 uniqueNodes[ 1 ] = curNodes [ 4 ];
3405 uniqueNodes[ 2 ] = curNodes [ 5 ];
3407 else if (nbRepl == 4 &&
3408 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3409 // a lateral face turns into a line: reverse a bottom
3410 uniqueNodes[ 0 ] = curNodes [ 1 ];
3411 uniqueNodes[ 1 ] = curNodes [ 0 ];
3416 else if ( nbUniqueNodes == 5 ) {
3417 // PENTAHEDRON --------------------> 2 tetrahedrons
3418 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3419 // a bottom node sticks with a linked top one
3421 SMDS_MeshElement* newElem =
3422 aMesh->AddVolume(curNodes[ 3 ],
3425 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3427 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3428 // 2. : reverse a bottom
3429 uniqueNodes[ 0 ] = curNodes [ 1 ];
3430 uniqueNodes[ 1 ] = curNodes [ 0 ];
3439 case 8: { //////////////////////////////////// HEXAHEDRON
3441 SMDS_VolumeTool hexa (elem);
3442 hexa.SetExternalNormal();
3443 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3444 //////////////////////// ---> tetrahedron
3445 for ( int iFace = 0; iFace < 6; iFace++ ) {
3446 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3447 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3448 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3449 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3450 // one face turns into a point ...
3451 int iOppFace = hexa.GetOppFaceIndex( iFace );
3452 ind = hexa.GetFaceNodesIndices( iOppFace );
3454 iUnique = 2; // reverse a tetrahedron bottom
3455 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3456 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3458 else if ( iUnique >= 0 )
3459 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3461 if ( nbStick == 1 ) {
3462 // ... and the opposite one - into a triangle.
3464 ind = hexa.GetFaceNodesIndices( iFace );
3465 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3472 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3473 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3474 for ( int iFace = 0; iFace < 6; iFace++ ) {
3475 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3476 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3477 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3478 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3479 // one face turns into a point ...
3480 int iOppFace = hexa.GetOppFaceIndex( iFace );
3481 ind = hexa.GetFaceNodesIndices( iOppFace );
3483 iUnique = 2; // reverse a tetrahedron 1 bottom
3484 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3485 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3487 else if ( iUnique >= 0 )
3488 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3490 if ( nbStick == 0 ) {
3491 // ... and the opposite one is a quadrangle
3493 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3494 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3497 SMDS_MeshElement* newElem =
3498 aMesh->AddVolume(curNodes[ind[ 0 ]],
3501 curNodes[indTop[ 0 ]]);
3503 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3510 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3511 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3512 // find indices of quad and tri faces
3513 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3514 for ( iFace = 0; iFace < 6; iFace++ ) {
3515 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3517 for ( iCur = 0; iCur < 4; iCur++ )
3518 nodeSet.insert( curNodes[ind[ iCur ]] );
3519 nbUniqueNodes = nodeSet.size();
3520 if ( nbUniqueNodes == 3 )
3521 iTriFace[ nbTri++ ] = iFace;
3522 else if ( nbUniqueNodes == 4 )
3523 iQuadFace[ nbQuad++ ] = iFace;
3525 if (nbQuad == 2 && nbTri == 4 &&
3526 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3527 // 2 opposite quadrangles stuck with a diagonal;
3528 // sample groups of merged indices: (0-4)(2-6)
3529 // --------------------------------------------> 2 tetrahedrons
3530 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3531 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3532 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3533 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3534 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3535 // stuck with 0-2 diagonal
3543 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3544 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3545 // stuck with 1-3 diagonal
3557 uniqueNodes[ 0 ] = curNodes [ i0 ];
3558 uniqueNodes[ 1 ] = curNodes [ i1d ];
3559 uniqueNodes[ 2 ] = curNodes [ i3d ];
3560 uniqueNodes[ 3 ] = curNodes [ i0t ];
3563 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3568 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3571 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3572 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3573 // --------------------------------------------> prism
3574 // find 2 opposite triangles
3576 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3577 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3578 // find indices of kept and replaced nodes
3579 // and fill unique nodes of 2 opposite triangles
3580 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3581 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3582 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3583 // fill unique nodes
3586 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3587 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
3588 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3590 // iCur of a linked node of the opposite face (make normals co-directed):
3591 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3592 // check that correspondent corners of triangles are linked
3593 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3596 uniqueNodes[ iUnique ] = n;
3597 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3606 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3612 } // switch ( nbNodes )
3614 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3617 if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3618 // Change nodes of polyedre
3619 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3620 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3622 int nbFaces = aPolyedre->NbFaces();
3624 vector<const SMDS_MeshNode *> poly_nodes;
3625 vector<int> quantities (nbFaces);
3627 for (int iface = 1; iface <= nbFaces; iface++) {
3628 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3629 quantities[iface - 1] = nbFaceNodes;
3631 for (inode = 1; inode <= nbFaceNodes; inode++) {
3632 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3634 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3635 if (nnIt != nodeNodeMap.end()) { // curNode sticks
3636 curNode = (*nnIt).second;
3638 poly_nodes.push_back(curNode);
3641 aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3644 // Change regular element or polygon
3645 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3648 // Remove invalid regular element or invalid polygon
3649 rmElemIds.push_back( elem->GetID() );
3652 } // loop on elements
3654 // Remove equal nodes and bad elements
3656 Remove( rmNodeIds, true );
3657 Remove( rmElemIds, false );
3661 //=======================================================================
3662 //function : MergeEqualElements
3663 //purpose : Remove all but one of elements built on the same nodes.
3664 //=======================================================================
3666 void SMESH_MeshEditor::MergeEqualElements()
3668 SMESHDS_Mesh* aMesh = GetMeshDS();
3670 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
3671 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
3672 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3674 list< int > rmElemIds; // IDs of elems to remove
3676 for ( int iDim = 1; iDim <= 3; iDim++ ) {
3678 set< set <const SMDS_MeshElement*> > setOfNodeSet;
3682 const SMDS_MeshElement* elem = 0;
3684 if ( eIt->more() ) elem = eIt->next();
3685 } else if ( iDim == 2 ) {
3686 if ( fIt->more() ) elem = fIt->next();
3688 if ( vIt->more() ) elem = vIt->next();
3693 set <const SMDS_MeshElement*> nodeSet;
3694 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3695 while ( nodeIt->more() )
3696 nodeSet.insert( nodeIt->next() );
3699 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3701 rmElemIds.push_back( elem->GetID() );
3705 Remove( rmElemIds, false );
3708 //=======================================================================
3709 //function : FindFaceInSet
3710 //purpose : Return a face having linked nodes n1 and n2 and which is
3711 // - not in avoidSet,
3712 // - in elemSet provided that !elemSet.empty()
3713 //=======================================================================
3715 const SMDS_MeshElement*
3716 SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode* n1,
3717 const SMDS_MeshNode* n2,
3718 const set<const SMDS_MeshElement*>& elemSet,
3719 const set<const SMDS_MeshElement*>& avoidSet)
3722 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3723 while ( invElemIt->more() ) { // loop on inverse elements of n1
3724 const SMDS_MeshElement* elem = invElemIt->next();
3725 if (elem->GetType() != SMDSAbs_Face ||
3726 avoidSet.find( elem ) != avoidSet.end() )
3728 if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3730 // get face nodes and find index of n1
3731 int i1, nbN = elem->NbNodes(), iNode = 0;
3732 const SMDS_MeshNode* faceNodes[ nbN ], *n;
3733 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3734 while ( nIt->more() ) {
3735 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3736 if ( faceNodes[ iNode++ ] == n1 )
3739 // find a n2 linked to n1
3740 for ( iNode = 0; iNode < 2; iNode++ ) {
3741 if ( iNode ) // node before n1
3742 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3743 else // node after n1
3744 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3752 //=======================================================================
3753 //function : findAdjacentFace
3755 //=======================================================================
3757 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3758 const SMDS_MeshNode* n2,
3759 const SMDS_MeshElement* elem)
3761 set<const SMDS_MeshElement*> elemSet, avoidSet;
3763 avoidSet.insert ( elem );
3764 return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3767 //=======================================================================
3768 //function : findFreeBorder
3770 //=======================================================================
3772 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3774 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
3775 const SMDS_MeshNode* theSecondNode,
3776 const SMDS_MeshNode* theLastNode,
3777 list< const SMDS_MeshNode* > & theNodes,
3778 list< const SMDS_MeshElement* > & theFaces)
3780 if ( !theFirstNode || !theSecondNode )
3782 // find border face between theFirstNode and theSecondNode
3783 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3787 theFaces.push_back( curElem );
3788 theNodes.push_back( theFirstNode );
3789 theNodes.push_back( theSecondNode );
3791 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3792 set < const SMDS_MeshElement* > foundElems;
3793 bool needTheLast = ( theLastNode != 0 );
3795 while ( nStart != theLastNode )
3797 if ( nStart == theFirstNode )
3798 return !needTheLast;
3800 // find all free border faces sharing form nStart
3802 list< const SMDS_MeshElement* > curElemList;
3803 list< const SMDS_MeshNode* > nStartList;
3804 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3805 while ( invElemIt->more() ) {
3806 const SMDS_MeshElement* e = invElemIt->next();
3807 if ( e == curElem || foundElems.insert( e ).second )
3810 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3811 int iNode = 0, nbNodes = e->NbNodes();
3812 while ( nIt->more() )
3813 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3814 nodes[ iNode ] = nodes[ 0 ];
3816 for ( iNode = 0; iNode < nbNodes; iNode++ )
3817 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3818 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3819 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3821 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3822 curElemList.push_back( e );
3826 // analyse the found
3828 int nbNewBorders = curElemList.size();
3829 if ( nbNewBorders == 0 ) {
3830 // no free border furthermore
3831 return !needTheLast;
3833 else if ( nbNewBorders == 1 ) {
3834 // one more element found
3836 nStart = nStartList.front();
3837 curElem = curElemList.front();
3838 theFaces.push_back( curElem );
3839 theNodes.push_back( nStart );
3842 // several continuations found
3843 list< const SMDS_MeshElement* >::iterator curElemIt;
3844 list< const SMDS_MeshNode* >::iterator nStartIt;
3845 // check if one of them reached the last node
3846 if ( needTheLast ) {
3847 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3848 curElemIt!= curElemList.end();
3849 curElemIt++, nStartIt++ )
3850 if ( *nStartIt == theLastNode ) {
3851 theFaces.push_back( *curElemIt );
3852 theNodes.push_back( *nStartIt );
3856 // find the best free border by the continuations
3857 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
3858 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3859 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3860 curElemIt!= curElemList.end();
3861 curElemIt++, nStartIt++ )
3863 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3864 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3865 // find one more free border
3866 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3870 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3871 // choice: clear a worse one
3872 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3873 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3874 contNodes[ iWorse ].clear();
3875 contFaces[ iWorse ].clear();
3878 if ( contNodes[0].empty() && contNodes[1].empty() )
3881 // append the best free border
3882 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3883 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3884 theNodes.pop_back(); // remove nIgnore
3885 theNodes.pop_back(); // remove nStart
3886 theFaces.pop_back(); // remove curElem
3887 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3888 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3889 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3890 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3893 } // several continuations found
3894 } // while ( nStart != theLastNode )
3899 //=======================================================================
3900 //function : CheckFreeBorderNodes
3901 //purpose : Return true if the tree nodes are on a free border
3902 //=======================================================================
3904 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3905 const SMDS_MeshNode* theNode2,
3906 const SMDS_MeshNode* theNode3)
3908 list< const SMDS_MeshNode* > nodes;
3909 list< const SMDS_MeshElement* > faces;
3910 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3913 //=======================================================================
3914 //function : SewFreeBorder
3916 //=======================================================================
3918 SMESH_MeshEditor::Sew_Error
3919 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3920 const SMDS_MeshNode* theBordSecondNode,
3921 const SMDS_MeshNode* theBordLastNode,
3922 const SMDS_MeshNode* theSideFirstNode,
3923 const SMDS_MeshNode* theSideSecondNode,
3924 const SMDS_MeshNode* theSideThirdNode,
3925 const bool theSideIsFreeBorder,
3926 const bool toCreatePolygons,
3927 const bool toCreatePolyedrs)
3929 MESSAGE("::SewFreeBorder()");
3930 Sew_Error aResult = SEW_OK;
3932 // ====================================
3933 // find side nodes and elements
3934 // ====================================
3936 list< const SMDS_MeshNode* > nSide[ 2 ];
3937 list< const SMDS_MeshElement* > eSide[ 2 ];
3938 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3939 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3943 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3944 nSide[0], eSide[0])) {
3945 MESSAGE(" Free Border 1 not found " );
3946 aResult = SEW_BORDER1_NOT_FOUND;
3948 if (theSideIsFreeBorder)
3952 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3953 nSide[1], eSide[1])) {
3954 MESSAGE(" Free Border 2 not found " );
3955 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3958 if ( aResult != SEW_OK )
3961 if (!theSideIsFreeBorder)
3966 // -------------------------------------------------------------------------
3968 // 1. If nodes to merge are not coincident, move nodes of the free border
3969 // from the coord sys defined by the direction from the first to last
3970 // nodes of the border to the correspondent sys of the side 2
3971 // 2. On the side 2, find the links most co-directed with the correspondent
3972 // links of the free border
3973 // -------------------------------------------------------------------------
3975 // 1. Since sewing may brake if there are volumes to split on the side 2,
3976 // we wont move nodes but just compute new coordinates for them
3977 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3978 TNodeXYZMap nBordXYZ;
3979 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3980 list< const SMDS_MeshNode* >::iterator nBordIt;
3982 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3983 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3984 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3985 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3986 double tol2 = 1.e-8;
3987 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3988 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3990 // Need node movement.
3992 // find X and Z axes to create trsf
3993 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3995 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3997 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
4000 gp_Ax3 toBordAx( Pb1, Zb, X );
4001 gp_Ax3 fromSideAx( Ps1, Zs, X );
4002 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
4004 gp_Trsf toBordSys, fromSide2Sys;
4005 toBordSys.SetTransformation( toBordAx );
4006 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
4007 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
4010 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
4011 const SMDS_MeshNode* n = *nBordIt;
4012 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
4013 toBordSys.Transforms( xyz );
4014 fromSide2Sys.Transforms( xyz );
4015 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
4020 // just insert nodes XYZ in the nBordXYZ map
4021 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
4022 const SMDS_MeshNode* n = *nBordIt;
4023 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
4027 // 2. On the side 2, find the links most co-directed with the correspondent
4028 // links of the free border
4030 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
4031 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
4032 sideNodes.push_back( theSideFirstNode );
4034 bool hasVolumes = false;
4035 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4036 set<long> foundSideLinkIDs, checkedLinkIDs;
4037 SMDS_VolumeTool volume;
4038 //const SMDS_MeshNode* faceNodes[ 4 ];
4040 const SMDS_MeshNode* sideNode;
4041 const SMDS_MeshElement* sideElem;
4042 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
4043 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
4044 nBordIt = bordNodes.begin();
4046 // border node position and border link direction to compare with
4047 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
4048 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
4049 // choose next side node by link direction or by closeness to
4050 // the current border node:
4051 bool searchByDir = ( *nBordIt != theBordLastNode );
4053 // find the next node on the Side 2
4055 double maxDot = -DBL_MAX, minDist = DBL_MAX;
4057 checkedLinkIDs.clear();
4058 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
4060 SMDS_ElemIteratorPtr invElemIt
4061 = prevSideNode->GetInverseElementIterator();
4062 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
4063 const SMDS_MeshElement* elem = invElemIt->next();
4064 // prepare data for a loop on links, of a face or a volume
4065 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
4066 const SMDS_MeshNode* faceNodes[ nbNodes ];
4067 bool isVolume = volume.Set( elem );
4068 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
4069 if ( isVolume ) // --volume
4071 else if ( nbNodes > 2 ) { // --face
4072 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
4073 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4074 while ( nIt->more() ) {
4075 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4076 if ( nodes[ iNode++ ] == prevSideNode )
4077 iPrevNode = iNode - 1;
4079 // there are 2 links to check
4084 // loop on links, to be precise, on the second node of links
4085 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4086 const SMDS_MeshNode* n = nodes[ iNode ];
4088 if ( !volume.IsLinked( n, prevSideNode ))
4091 if ( iNode ) // a node before prevSideNode
4092 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4093 else // a node after prevSideNode
4094 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4096 // check if this link was already used
4097 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4098 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4099 if (!isJustChecked &&
4100 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4101 // test a link geometrically
4102 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4103 bool linkIsBetter = false;
4105 if ( searchByDir ) { // choose most co-directed link
4106 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4107 linkIsBetter = ( dot > maxDot );
4109 else { // choose link with the node closest to bordPos
4110 dist = ( nextXYZ - bordPos ).SquareModulus();
4111 linkIsBetter = ( dist < minDist );
4113 if ( linkIsBetter ) {
4122 } // loop on inverse elements of prevSideNode
4125 MESSAGE(" Cant find path by links of the Side 2 ");
4126 return SEW_BAD_SIDE_NODES;
4128 sideNodes.push_back( sideNode );
4129 sideElems.push_back( sideElem );
4130 foundSideLinkIDs.insert ( linkID );
4131 prevSideNode = sideNode;
4133 if ( *nBordIt == theBordLastNode )
4134 searchByDir = false;
4136 // find the next border link to compare with
4137 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4138 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4139 while ( *nBordIt != theBordLastNode && !searchByDir ) {
4140 prevBordNode = *nBordIt;
4142 bordPos = nBordXYZ[ *nBordIt ];
4143 bordDir = bordPos - nBordXYZ[ prevBordNode ];
4144 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4148 while ( sideNode != theSideSecondNode );
4150 if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4151 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4152 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4154 } // end nodes search on the side 2
4156 // ============================
4157 // sew the border to the side 2
4158 // ============================
4160 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
4161 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4163 TListOfListOfNodes nodeGroupsToMerge;
4164 if ( nbNodes[0] == nbNodes[1] ||
4165 ( theSideIsFreeBorder && !theSideThirdNode)) {
4167 // all nodes are to be merged
4169 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4170 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4171 nIt[0]++, nIt[1]++ )
4173 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4174 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4175 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4180 // insert new nodes into the border and the side to get equal nb of segments
4182 // get normalized parameters of nodes on the borders
4183 double param[ 2 ][ maxNbNodes ];
4185 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4186 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4187 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4188 const SMDS_MeshNode* nPrev = *nIt;
4189 double bordLength = 0;
4190 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4191 const SMDS_MeshNode* nCur = *nIt;
4192 gp_XYZ segment (nCur->X() - nPrev->X(),
4193 nCur->Y() - nPrev->Y(),
4194 nCur->Z() - nPrev->Z());
4195 double segmentLen = segment.Modulus();
4196 bordLength += segmentLen;
4197 param[ iBord ][ iNode ] = bordLength;
4200 // normalize within [0,1]
4201 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4202 param[ iBord ][ iNode ] /= bordLength;
4206 // loop on border segments
4207 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4208 int i[ 2 ] = { 0, 0 };
4209 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4210 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4212 TElemOfNodeListMap insertMap;
4213 TElemOfNodeListMap::iterator insertMapIt;
4215 // key: elem to insert nodes into
4216 // value: 2 nodes to insert between + nodes to be inserted
4218 bool next[ 2 ] = { false, false };
4220 // find min adjacent segment length after sewing
4221 double nextParam = 10., prevParam = 0;
4222 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4223 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4224 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4225 if ( i[ iBord ] > 0 )
4226 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4228 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4229 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4230 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4232 // choose to insert or to merge nodes
4233 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4234 if ( Abs( du ) <= minSegLen * 0.2 ) {
4237 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4238 const SMDS_MeshNode* n0 = *nIt[0];
4239 const SMDS_MeshNode* n1 = *nIt[1];
4240 nodeGroupsToMerge.back().push_back( n1 );
4241 nodeGroupsToMerge.back().push_back( n0 );
4242 // position of node of the border changes due to merge
4243 param[ 0 ][ i[0] ] += du;
4244 // move n1 for the sake of elem shape evaluation during insertion.
4245 // n1 will be removed by MergeNodes() anyway
4246 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4247 next[0] = next[1] = true;
4252 int intoBord = ( du < 0 ) ? 0 : 1;
4253 const SMDS_MeshElement* elem = *eIt[ intoBord ];
4254 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
4255 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
4256 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
4257 if ( intoBord == 1 ) {
4258 // move node of the border to be on a link of elem of the side
4259 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4260 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4261 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4262 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4263 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4265 insertMapIt = insertMap.find( elem );
4266 bool notFound = ( insertMapIt == insertMap.end() );
4267 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4269 // insert into another link of the same element:
4270 // 1. perform insertion into the other link of the elem
4271 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4272 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4273 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4274 InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4275 // 2. perform insertion into the link of adjacent faces
4277 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4279 InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4283 if (toCreatePolyedrs) {
4284 // perform insertion into the links of adjacent volumes
4285 UpdateVolumes(n12, n22, nodeList);
4287 // 3. find an element appeared on n1 and n2 after the insertion
4288 insertMap.erase( elem );
4289 elem = findAdjacentFace( n1, n2, 0 );
4291 if ( notFound || otherLink ) {
4292 // add element and nodes of the side into the insertMap
4293 insertMapIt = insertMap.insert
4294 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4295 (*insertMapIt).second.push_back( n1 );
4296 (*insertMapIt).second.push_back( n2 );
4298 // add node to be inserted into elem
4299 (*insertMapIt).second.push_back( nIns );
4300 next[ 1 - intoBord ] = true;
4303 // go to the next segment
4304 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4305 if ( next[ iBord ] ) {
4306 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4308 nPrev[ iBord ] = *nIt[ iBord ];
4309 nIt[ iBord ]++; i[ iBord ]++;
4313 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4315 // perform insertion of nodes into elements
4317 for (insertMapIt = insertMap.begin();
4318 insertMapIt != insertMap.end();
4321 const SMDS_MeshElement* elem = (*insertMapIt).first;
4322 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4323 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4324 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4326 InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4328 if ( !theSideIsFreeBorder ) {
4329 // look for and insert nodes into the faces adjacent to elem
4331 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4333 InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4338 if (toCreatePolyedrs) {
4339 // perform insertion into the links of adjacent volumes
4340 UpdateVolumes(n1, n2, nodeList);
4344 } // end: insert new nodes
4346 MergeNodes ( nodeGroupsToMerge );
4351 //=======================================================================
4352 //function : InsertNodesIntoLink
4353 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
4354 // and theBetweenNode2 and split theElement
4355 //=======================================================================
4357 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
4358 const SMDS_MeshNode* theBetweenNode1,
4359 const SMDS_MeshNode* theBetweenNode2,
4360 list<const SMDS_MeshNode*>& theNodesToInsert,
4361 const bool toCreatePoly)
4363 if ( theFace->GetType() != SMDSAbs_Face ) return;
4365 // find indices of 2 link nodes and of the rest nodes
4366 int iNode = 0, il1, il2, i3, i4;
4367 il1 = il2 = i3 = i4 = -1;
4368 const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4369 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4370 while ( nodeIt->more() ) {
4371 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4372 if ( n == theBetweenNode1 )
4374 else if ( n == theBetweenNode2 )
4380 nodes[ iNode++ ] = n;
4382 if ( il1 < 0 || il2 < 0 || i3 < 0 )
4385 // arrange link nodes to go one after another regarding the face orientation
4386 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4387 list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4392 aNodesToInsert.reverse();
4394 // check that not link nodes of a quadrangles are in good order
4395 int nbFaceNodes = theFace->NbNodes();
4396 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4402 if (toCreatePoly || theFace->IsPoly()) {
4405 vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4407 // add nodes of face up to first node of link
4409 nodeIt = theFace->nodesIterator();
4410 while ( nodeIt->more() && !isFLN ) {
4411 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4412 poly_nodes[iNode++] = n;
4413 if (n == nodes[il1]) {
4418 // add nodes to insert
4419 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4420 for (; nIt != aNodesToInsert.end(); nIt++) {
4421 poly_nodes[iNode++] = *nIt;
4424 // add nodes of face starting from last node of link
4425 while ( nodeIt->more() ) {
4426 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4427 poly_nodes[iNode++] = n;
4430 // edit or replace the face
4431 SMESHDS_Mesh *aMesh = GetMeshDS();
4433 if (theFace->IsPoly()) {
4434 aMesh->ChangePolygonNodes(theFace, poly_nodes);
4437 int aShapeId = FindShape( theFace );
4439 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4440 if ( aShapeId && newElem )
4441 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4443 aMesh->RemoveElement(theFace);
4448 // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4449 int nbLinkNodes = 2 + aNodesToInsert.size();
4450 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4451 linkNodes[ 0 ] = nodes[ il1 ];
4452 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4453 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4454 for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4455 linkNodes[ iNode++ ] = *nIt;
4457 // decide how to split a quadrangle: compare possible variants
4458 // and choose which of splits to be a quadrangle
4459 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4460 if ( nbFaceNodes == 3 )
4462 iBestQuad = nbSplits;
4465 else if ( nbFaceNodes == 4 )
4467 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4468 double aBestRate = DBL_MAX;
4469 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4471 double aBadRate = 0;
4472 // evaluate elements quality
4473 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4474 if ( iSplit == iQuad ) {
4475 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4479 aBadRate += getBadRate( &quad, aCrit );
4482 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4484 nodes[ iSplit < iQuad ? i4 : i3 ]);
4485 aBadRate += getBadRate( &tria, aCrit );
4489 if ( aBadRate < aBestRate ) {
4491 aBestRate = aBadRate;
4496 // create new elements
4497 SMESHDS_Mesh *aMesh = GetMeshDS();
4498 int aShapeId = FindShape( theFace );
4501 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4502 SMDS_MeshElement* newElem = 0;
4503 if ( iSplit == iBestQuad )
4504 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4509 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4511 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4512 if ( aShapeId && newElem )
4513 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4516 // change nodes of theFace
4517 const SMDS_MeshNode* newNodes[ 4 ];
4518 newNodes[ 0 ] = linkNodes[ i1 ];
4519 newNodes[ 1 ] = linkNodes[ i2 ];
4520 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4521 newNodes[ 3 ] = nodes[ i4 ];
4522 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4525 //=======================================================================
4526 //function : UpdateVolumes
4528 //=======================================================================
4529 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode* theBetweenNode1,
4530 const SMDS_MeshNode* theBetweenNode2,
4531 list<const SMDS_MeshNode*>& theNodesToInsert)
4533 SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4534 while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4535 const SMDS_MeshElement* elem = invElemIt->next();
4536 if (elem->GetType() != SMDSAbs_Volume)
4539 // check, if current volume has link theBetweenNode1 - theBetweenNode2
4540 SMDS_VolumeTool aVolume (elem);
4541 if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4544 // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4545 int iface, nbFaces = aVolume.NbFaces();
4546 vector<const SMDS_MeshNode *> poly_nodes;
4547 vector<int> quantities (nbFaces);
4549 for (iface = 0; iface < nbFaces; iface++) {
4550 int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4551 // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4552 const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4554 for (int inode = 0; inode < nbFaceNodes; inode++) {
4555 poly_nodes.push_back(faceNodes[inode]);
4557 if (nbInserted == 0) {
4558 if (faceNodes[inode] == theBetweenNode1) {
4559 if (faceNodes[inode + 1] == theBetweenNode2) {
4560 nbInserted = theNodesToInsert.size();
4562 // add nodes to insert
4563 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4564 for (; nIt != theNodesToInsert.end(); nIt++) {
4565 poly_nodes.push_back(*nIt);
4568 } else if (faceNodes[inode] == theBetweenNode2) {
4569 if (faceNodes[inode + 1] == theBetweenNode1) {
4570 nbInserted = theNodesToInsert.size();
4572 // add nodes to insert in reversed order
4573 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4575 for (; nIt != theNodesToInsert.begin(); nIt--) {
4576 poly_nodes.push_back(*nIt);
4578 poly_nodes.push_back(*nIt);
4584 quantities[iface] = nbFaceNodes + nbInserted;
4587 // Replace or update the volume
4588 SMESHDS_Mesh *aMesh = GetMeshDS();
4590 if (elem->IsPoly()) {
4591 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4594 int aShapeId = FindShape( elem );
4596 SMDS_MeshElement* newElem =
4597 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4598 if (aShapeId && newElem)
4599 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4601 aMesh->RemoveElement(elem);
4606 //=======================================================================
4607 //function : SewSideElements
4609 //=======================================================================
4611 SMESH_MeshEditor::Sew_Error
4612 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4613 set<const SMDS_MeshElement*>& theSide2,
4614 const SMDS_MeshNode* theFirstNode1,
4615 const SMDS_MeshNode* theFirstNode2,
4616 const SMDS_MeshNode* theSecondNode1,
4617 const SMDS_MeshNode* theSecondNode2)
4619 MESSAGE ("::::SewSideElements()");
4620 if ( theSide1.size() != theSide2.size() )
4621 return SEW_DIFF_NB_OF_ELEMENTS;
4623 Sew_Error aResult = SEW_OK;
4625 // 1. Build set of faces representing each side
4626 // 2. Find which nodes of the side 1 to merge with ones on the side 2
4627 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4629 // =======================================================================
4630 // 1. Build set of faces representing each side:
4631 // =======================================================================
4632 // a. build set of nodes belonging to faces
4633 // b. complete set of faces: find missing fices whose nodes are in set of nodes
4634 // c. create temporary faces representing side of volumes if correspondent
4635 // face does not exist
4637 SMESHDS_Mesh* aMesh = GetMeshDS();
4638 SMDS_Mesh aTmpFacesMesh;
4639 set<const SMDS_MeshElement*> faceSet1, faceSet2;
4640 set<const SMDS_MeshElement*> volSet1, volSet2;
4641 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
4642 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4643 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
4644 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4645 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4646 int iSide, iFace, iNode;
4648 for ( iSide = 0; iSide < 2; iSide++ ) {
4649 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
4650 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4651 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4652 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
4653 set<const SMDS_MeshElement*>::iterator vIt, eIt;
4654 set<const SMDS_MeshNode*>::iterator nIt;
4656 // -----------------------------------------------------------
4657 // 1a. Collect nodes of existing faces
4658 // and build set of face nodes in order to detect missing
4659 // faces corresponing to sides of volumes
4660 // -----------------------------------------------------------
4662 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4664 // loop on the given element of a side
4665 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4666 const SMDS_MeshElement* elem = *eIt;
4667 if ( elem->GetType() == SMDSAbs_Face ) {
4668 faceSet->insert( elem );
4669 set <const SMDS_MeshNode*> faceNodeSet;
4670 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4671 while ( nodeIt->more() ) {
4672 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4673 nodeSet->insert( n );
4674 faceNodeSet.insert( n );
4676 setOfFaceNodeSet.insert( faceNodeSet );
4678 else if ( elem->GetType() == SMDSAbs_Volume )
4679 volSet->insert( elem );
4681 // ------------------------------------------------------------------------------
4682 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4683 // ------------------------------------------------------------------------------
4685 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4686 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4687 while ( fIt->more() ) { // loop on faces sharing a node
4688 const SMDS_MeshElement* f = fIt->next();
4689 if ( faceSet->find( f ) == faceSet->end() ) {
4690 // check if all nodes are in nodeSet and
4691 // complete setOfFaceNodeSet if they are
4692 set <const SMDS_MeshNode*> faceNodeSet;
4693 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4694 bool allInSet = true;
4695 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4696 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4697 if ( nodeSet->find( n ) == nodeSet->end() )
4700 faceNodeSet.insert( n );
4703 faceSet->insert( f );
4704 setOfFaceNodeSet.insert( faceNodeSet );
4710 // -------------------------------------------------------------------------
4711 // 1c. Create temporary faces representing sides of volumes if correspondent
4712 // face does not exist
4713 // -------------------------------------------------------------------------
4715 if ( !volSet->empty() )
4717 //int nodeSetSize = nodeSet->size();
4719 // loop on given volumes
4720 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4721 SMDS_VolumeTool vol (*vIt);
4722 // loop on volume faces: find free faces
4723 // --------------------------------------
4724 list<const SMDS_MeshElement* > freeFaceList;
4725 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4726 if ( !vol.IsFreeFace( iFace ))
4728 // check if there is already a face with same nodes in a face set
4729 const SMDS_MeshElement* aFreeFace = 0;
4730 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4731 int nbNodes = vol.NbFaceNodes( iFace );
4732 set <const SMDS_MeshNode*> faceNodeSet;
4733 vol.GetFaceNodes( iFace, faceNodeSet );
4734 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4736 // no such a face is given but it still can exist, check it
4737 if ( nbNodes == 3 ) {
4738 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4739 } else if ( nbNodes == 4 ) {
4740 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4742 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4743 for (int inode = 0; inode < nbNodes; inode++) {
4744 poly_nodes[inode] = fNodes[inode];
4746 aFreeFace = aMesh->FindFace(poly_nodes);
4750 // create a temporary face
4751 if ( nbNodes == 3 ) {
4752 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4753 } else if ( nbNodes == 4 ) {
4754 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4756 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4757 for (int inode = 0; inode < nbNodes; inode++) {
4758 poly_nodes[inode] = fNodes[inode];
4760 aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4764 freeFaceList.push_back( aFreeFace );
4766 } // loop on faces of a volume
4768 // choose one of several free faces
4769 // --------------------------------------
4770 if ( freeFaceList.size() > 1 ) {
4771 // choose a face having max nb of nodes shared by other elems of a side
4772 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4773 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4774 while ( fIt != freeFaceList.end() ) { // loop on free faces
4775 int nbSharedNodes = 0;
4776 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4777 while ( nodeIt->more() ) { // loop on free face nodes
4778 const SMDS_MeshNode* n =
4779 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4780 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4781 while ( invElemIt->more() ) {
4782 const SMDS_MeshElement* e = invElemIt->next();
4783 if ( faceSet->find( e ) != faceSet->end() )
4785 if ( elemSet->find( e ) != elemSet->end() )
4789 if ( nbSharedNodes >= maxNbNodes ) {
4790 maxNbNodes = nbSharedNodes;
4794 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4796 if ( freeFaceList.size() > 1 )
4798 // could not choose one face, use another way
4799 // choose a face most close to the bary center of the opposite side
4800 gp_XYZ aBC( 0., 0., 0. );
4801 set <const SMDS_MeshNode*> addedNodes;
4802 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4803 eIt = elemSet2->begin();
4804 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4805 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4806 while ( nodeIt->more() ) { // loop on free face nodes
4807 const SMDS_MeshNode* n =
4808 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4809 if ( addedNodes.insert( n ).second )
4810 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4813 aBC /= addedNodes.size();
4814 double minDist = DBL_MAX;
4815 fIt = freeFaceList.begin();
4816 while ( fIt != freeFaceList.end() ) { // loop on free faces
4818 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4819 while ( nodeIt->more() ) { // loop on free face nodes
4820 const SMDS_MeshNode* n =
4821 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4822 gp_XYZ p( n->X(),n->Y(),n->Z() );
4823 dist += ( aBC - p ).SquareModulus();
4825 if ( dist < minDist ) {
4827 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4830 fIt = freeFaceList.erase( fIt++ );
4833 } // choose one of several free faces of a volume
4835 if ( freeFaceList.size() == 1 ) {
4836 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4837 faceSet->insert( aFreeFace );
4838 // complete a node set with nodes of a found free face
4839 // for ( iNode = 0; iNode < ; iNode++ )
4840 // nodeSet->insert( fNodes[ iNode ] );
4843 } // loop on volumes of a side
4845 // // complete a set of faces if new nodes in a nodeSet appeared
4846 // // ----------------------------------------------------------
4847 // if ( nodeSetSize != nodeSet->size() ) {
4848 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4849 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4850 // while ( fIt->more() ) { // loop on faces sharing a node
4851 // const SMDS_MeshElement* f = fIt->next();
4852 // if ( faceSet->find( f ) == faceSet->end() ) {
4853 // // check if all nodes are in nodeSet and
4854 // // complete setOfFaceNodeSet if they are
4855 // set <const SMDS_MeshNode*> faceNodeSet;
4856 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4857 // bool allInSet = true;
4858 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4859 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4860 // if ( nodeSet->find( n ) == nodeSet->end() )
4861 // allInSet = false;
4863 // faceNodeSet.insert( n );
4865 // if ( allInSet ) {
4866 // faceSet->insert( f );
4867 // setOfFaceNodeSet.insert( faceNodeSet );
4873 } // Create temporary faces, if there are volumes given
4876 if ( faceSet1.size() != faceSet2.size() ) {
4877 // delete temporary faces: they are in reverseElements of actual nodes
4878 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4879 while ( tmpFaceIt->more() )
4880 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4881 MESSAGE("Diff nb of faces");
4882 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4885 // ============================================================
4886 // 2. Find nodes to merge:
4887 // bind a node to remove to a node to put instead
4888 // ============================================================
4890 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4891 if ( theFirstNode1 != theFirstNode2 )
4892 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4893 if ( theSecondNode1 != theSecondNode2 )
4894 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4896 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4897 set< long > linkIdSet; // links to process
4898 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4900 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4901 list< TPairOfNodes > linkList[2];
4902 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4903 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4904 // loop on links in linkList; find faces by links and append links
4905 // of the found faces to linkList
4906 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4907 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4909 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4910 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4911 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4914 // by links, find faces in the face sets,
4915 // and find indices of link nodes in the found faces;
4916 // in a face set, there is only one or no face sharing a link
4917 // ---------------------------------------------------------------
4919 const SMDS_MeshElement* face[] = { 0, 0 };
4920 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4921 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4922 int iLinkNode[2][2];
4923 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4924 const SMDS_MeshNode* n1 = link[iSide].first;
4925 const SMDS_MeshNode* n2 = link[iSide].second;
4926 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4927 set< const SMDS_MeshElement* > fMap;
4928 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4929 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4930 SMDS_ElemIteratorPtr fIt = n->facesIterator();
4931 while ( fIt->more() ) { // loop on faces sharing a node
4932 const SMDS_MeshElement* f = fIt->next();
4933 if (faceSet->find( f ) != faceSet->end() && // f is in face set
4934 ! fMap.insert( f ).second ) // f encounters twice
4936 if ( face[ iSide ] ) {
4937 MESSAGE( "2 faces per link " );
4938 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4942 faceSet->erase( f );
4943 // get face nodes and find ones of a link
4945 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4946 while ( nIt->more() ) {
4947 const SMDS_MeshNode* n =
4948 static_cast<const SMDS_MeshNode*>( nIt->next() );
4950 iLinkNode[ iSide ][ 0 ] = iNode;
4952 iLinkNode[ iSide ][ 1 ] = iNode;
4953 else if ( notLinkNodes[ iSide ][ 0 ] )
4954 notLinkNodes[ iSide ][ 1 ] = n;
4956 notLinkNodes[ iSide ][ 0 ] = n;
4957 faceNodes[ iSide ][ iNode++ ] = n;
4959 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4964 // check similarity of elements of the sides
4965 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4966 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4967 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4968 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4970 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4971 break; // do not return because it s necessary to remove tmp faces
4974 // set nodes to merge
4975 // -------------------
4977 if ( face[0] && face[1] )
4979 int nbNodes = face[0]->NbNodes();
4980 if ( nbNodes != face[1]->NbNodes() ) {
4981 MESSAGE("Diff nb of face nodes");
4982 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4983 break; // do not return because it s necessary to remove tmp faces
4985 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4987 nReplaceMap.insert( TNodeNodeMap::value_type
4988 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4990 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4991 // analyse link orientation in faces
4992 int i1 = iLinkNode[ iSide ][ 0 ];
4993 int i2 = iLinkNode[ iSide ][ 1 ];
4994 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4995 // if notLinkNodes are the first and the last ones, then
4996 // their order does not correspond to the link orientation
4997 if (( i1 == 1 && i2 == 2 ) ||
4998 ( i1 == 2 && i2 == 1 ))
4999 reverse[ iSide ] = !reverse[ iSide ];
5001 if ( reverse[0] == reverse[1] ) {
5002 nReplaceMap.insert( TNodeNodeMap::value_type
5003 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
5004 nReplaceMap.insert( TNodeNodeMap::value_type
5005 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
5008 nReplaceMap.insert( TNodeNodeMap::value_type
5009 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
5010 nReplaceMap.insert( TNodeNodeMap::value_type
5011 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
5015 // add other links of the faces to linkList
5016 // -----------------------------------------
5018 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
5019 for ( iNode = 0; iNode < nbNodes; iNode++ )
5021 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
5022 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
5023 if ( !iter_isnew.second ) { // already in a set: no need to process
5024 linkIdSet.erase( iter_isnew.first );
5026 else // new in set == encountered for the first time: add
5028 const SMDS_MeshNode* n1 = nodes[ iNode ];
5029 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
5030 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
5031 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
5035 } // loop on link lists
5037 if ( aResult == SEW_OK &&
5038 ( linkIt[0] != linkList[0].end() ||
5039 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
5040 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
5041 " " << (faceSetPtr[1]->empty()));
5042 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5045 // ====================================================================
5046 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
5047 // ====================================================================
5049 // delete temporary faces: they are in reverseElements of actual nodes
5050 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
5051 while ( tmpFaceIt->more() )
5052 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
5054 if ( aResult != SEW_OK)
5057 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
5058 // loop on nodes replacement map
5059 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
5060 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
5061 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
5063 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
5064 nodeIDsToRemove.push_back( nToRemove->GetID() );
5065 // loop on elements sharing nToRemove
5066 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
5067 while ( invElemIt->more() ) {
5068 const SMDS_MeshElement* e = invElemIt->next();
5069 // get a new suite of nodes: make replacement
5070 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
5071 const SMDS_MeshNode* nodes[ 8 ];
5072 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5073 while ( nIt->more() ) {
5074 const SMDS_MeshNode* n =
5075 static_cast<const SMDS_MeshNode*>( nIt->next() );
5076 nnIt = nReplaceMap.find( n );
5077 if ( nnIt != nReplaceMap.end() ) {
5083 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5084 // elemIDsToRemove.push_back( e->GetID() );
5087 aMesh->ChangeElementNodes( e, nodes, nbNodes );
5091 Remove( nodeIDsToRemove, true );