Salome HOME
PAL8330. In sweepElement(): fix volume orientation
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.cxx
1 //  SMESH SMESH : idl implementation based on 'SMESH' unit's classes
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
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. 
10 // 
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. 
15 // 
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 
19 // 
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
21 //
22 //
23 //
24 // File      : SMESH_MeshEditor.cxx
25 // Created   : Mon Apr 12 16:10:22 2004
26 // Author    : Edward AGAPOV (eap)
27
28
29 #include "SMESH_MeshEditor.hxx"
30
31 #include "SMESH_ControlsDef.hxx"
32
33 #include "SMDS_FaceOfNodes.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESH_subMesh.hxx"
38 #include "SMESH_ControlsDef.hxx"
39
40 #include "utilities.h"
41
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_ListOfShape.hxx>
44 #include <math.h>
45 #include <gp_Dir.hxx>
46 #include <gp_Vec.hxx>
47 #include <gp_Ax1.hxx>
48 #include <gp_Trsf.hxx>
49 #include <gp_Lin.hxx>
50 #include <gp_XYZ.hxx>
51 #include <gp.hxx>
52 #include <gp_Pln.hxx>
53 #include <BRep_Tool.hxx>
54 #include <SMDS_EdgePosition.hxx>
55 #include <Geom_Curve.hxx>
56
57
58 #include <map>
59
60 #include "utilities.h"
61
62 using namespace std;
63 using namespace SMESH::Controls;
64
65 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*>              TNodeNodeMap;
66 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> >    TElemOfNodeListMap;
67 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
68 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> >       TNodeOfNodeListMap;
69 typedef TNodeOfNodeListMap::iterator                                 TNodeOfNodeListMapItr;
70 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
71
72 //=======================================================================
73 //function : SMESH_MeshEditor
74 //purpose  : 
75 //=======================================================================
76
77 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
78 myMesh( theMesh )
79 {
80 }
81
82 //=======================================================================
83 //function : Remove
84 //purpose  : Remove a node or an element.
85 //           Modify a compute state of sub-meshes which become empty
86 //=======================================================================
87
88 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
89                                const bool         isNodes )
90 {
91
92   SMESHDS_Mesh* aMesh = GetMeshDS();
93   set< SMESH_subMesh *> smmap;
94   
95   list<int>::const_iterator it = theIDs.begin();
96   for ( ; it != theIDs.end(); it++ )
97   {
98     const SMDS_MeshElement * elem;
99     if ( isNodes )
100       elem = aMesh->FindNode( *it );
101     else
102       elem = aMesh->FindElement( *it );
103     if ( !elem )
104       continue;
105
106     // Find sub-meshes to notify about modification
107     SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
108     while ( nodeIt->more() )
109     {
110       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
111       const SMDS_PositionPtr& aPosition = node->GetPosition();
112       if ( aPosition.get() ) {
113         int aShapeID = aPosition->GetShapeId();
114         if ( aShapeID ) {
115           TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
116           SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
117           if ( sm )
118             smmap.insert( sm );
119         }
120       }
121     }
122
123     // Do remove
124     if ( isNodes )
125       aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
126     else
127       aMesh->RemoveElement( elem );
128   }
129
130   // Notify sub-meshes about modification
131   if ( !smmap.empty() ) {
132     set< SMESH_subMesh *>::iterator smIt;
133     for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
134       (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
135   }
136   return true;
137 }
138
139 //=======================================================================
140 //function : FindShape
141 //purpose  : Return an index of the shape theElem is on
142 //           or zero if a shape not found
143 //=======================================================================
144
145 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
146 {
147   SMESHDS_Mesh * aMesh = GetMeshDS();
148   if ( aMesh->ShapeToMesh().IsNull() )
149     return 0;
150
151   if ( theElem->GetType() == SMDSAbs_Node )
152   {
153     const SMDS_PositionPtr& aPosition =
154       static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
155     if ( aPosition.get() )
156       return aPosition->GetShapeId();
157     else
158       return 0;
159   }
160
161   TopoDS_Shape aShape; // the shape a node is on
162   SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
163   while ( nodeIt->more() )
164   {
165     const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
166     const SMDS_PositionPtr& aPosition = node->GetPosition();
167     if ( aPosition.get() ) {
168         int aShapeID = aPosition->GetShapeId();
169         SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
170         if ( sm )
171         {
172           if ( sm->Contains( theElem ))
173             return aShapeID;
174           if ( aShape.IsNull() )
175             aShape = aMesh->IndexToShape( aShapeID );
176         }
177         else
178         {
179           //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
180         }
181       }
182   }
183
184   // None of nodes is on a proper shape,
185   // find the shape among ancestors of aShape on which a node is
186   if ( aShape.IsNull() ) {
187     //MESSAGE ("::FindShape() - NONE node is on shape")
188     return 0;
189   }
190   TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
191   for ( ; ancIt.More(); ancIt.Next() )
192   {
193       SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
194       if ( sm && sm->Contains( theElem ))
195         return aMesh->ShapeToIndex( ancIt.Value() );
196   }
197
198   //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
199   return 0;
200 }
201
202 //=======================================================================
203 //function : InverseDiag
204 //purpose  : Replace two neighbour triangles with ones built on the same 4 nodes
205 //           but having other common link.
206 //           Return False if args are improper
207 //=======================================================================
208
209 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
210                                     const SMDS_MeshElement * theTria2 )
211 {
212   if (!theTria1 || !theTria2)
213     return false;
214   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
215   if (!F1) return false;
216   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
217   if (!F2) return false;
218
219   //  1 +--+ A  theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
220   //    | /|    theTria2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |  
221   //    |/ |                                         | \|  
222   //  B +--+ 2                                     B +--+ 2
223
224   // put nodes in array and find out indices of the same ones
225   const SMDS_MeshNode* aNodes [6];
226   int sameInd [] = { 0, 0, 0, 0, 0, 0 };
227   int i = 0;
228   SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
229   while ( it->more() )
230   {
231     aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
232
233     if ( i > 2 ) // theTria2
234       // find same node of theTria1
235       for ( int j = 0; j < 3; j++ )
236         if ( aNodes[ i ] == aNodes[ j ]) {
237           sameInd[ j ] = i;
238           sameInd[ i ] = j;
239           break;
240         }
241     // next
242     i++;
243     if ( i == 3 ) {
244       if ( it->more() )
245         return false; // theTria1 is not a triangle
246       it = theTria2->nodesIterator();
247     }
248     if ( i == 6 && it->more() )
249       return false; // theTria2 is not a triangle
250   }
251
252   // find indices of 1,2 and of A,B in theTria1
253   int iA = 0, iB = 0, i1 = 0, i2 = 0;
254   for ( i = 0; i < 6; i++ )
255   {
256     if ( sameInd [ i ] == 0 )
257       if ( i < 3 ) i1 = i;
258       else         i2 = i;
259     else if (i < 3)
260       if ( iA ) iB = i;
261       else      iA = i;
262   }
263   // nodes 1 and 2 should not be the same
264   if ( aNodes[ i1 ] == aNodes[ i2 ] )
265     return false;
266
267
268   // theTria1: A->2
269   aNodes[ iA ] = aNodes[ i2 ];
270   // theTria2: B->1
271   aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
272
273   //MESSAGE( theTria1 << theTria2 );
274
275   GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
276   GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
277
278   //MESSAGE( theTria1 << theTria2 );
279
280   return true;
281 }
282
283 //=======================================================================
284 //function : findTriangles
285 //purpose  : find triangles sharing theNode1-theNode2 link
286 //=======================================================================
287
288 static bool findTriangles(const SMDS_MeshNode *    theNode1,
289                           const SMDS_MeshNode *    theNode2,
290                           const SMDS_MeshElement*& theTria1,
291                           const SMDS_MeshElement*& theTria2)
292 {
293   if ( !theNode1 || !theNode2 ) return false;
294
295   theTria1 = theTria2 = 0;
296
297   set< const SMDS_MeshElement* > emap;
298   SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
299   while (it->more()) {
300     const SMDS_MeshElement* elem = it->next();
301     if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
302       emap.insert( elem );
303   }
304   it = theNode2->GetInverseElementIterator();
305   while (it->more()) {
306     const SMDS_MeshElement* elem = it->next();
307     if ( elem->GetType() == SMDSAbs_Face &&
308          emap.find( elem ) != emap.end() )
309       if ( theTria1 ) {
310         theTria2 = elem;
311         break;
312       } else {
313         theTria1 = elem;
314       }
315   }
316   return ( theTria1 && theTria2 );
317 }
318
319 //=======================================================================
320 //function : InverseDiag
321 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
322 //           with ones built on the same 4 nodes but having other common link.
323 //           Return false if proper faces not found
324 //=======================================================================
325
326 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
327                                     const SMDS_MeshNode * theNode2)
328 {
329   MESSAGE( "::InverseDiag()" );
330
331   const SMDS_MeshElement *tr1, *tr2;
332   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
333     return false;
334
335   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
336   if (!F1) return false;
337   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
338   if (!F2) return false;
339
340   //  1 +--+ A  tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
341   //    | /|    tr2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |  
342   //    |/ |                                    | \|  
343   //  B +--+ 2                                B +--+ 2
344
345   // put nodes in array
346   // and find indices of 1,2 and of A in tr1 and of B in tr2
347   int i, iA1 = 0, i1 = 0;
348   const SMDS_MeshNode* aNodes1 [3];
349   SMDS_ElemIteratorPtr it;
350   for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
351     aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
352     if ( aNodes1[ i ] == theNode1 )
353       iA1 = i; // node A in tr1
354     else if ( aNodes1[ i ] != theNode2 )
355       i1 = i;  // node 1
356   }
357   int iB2 = 0, i2 = 0;
358   const SMDS_MeshNode* aNodes2 [3];
359   for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
360     aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
361     if ( aNodes2[ i ] == theNode2 )
362       iB2 = i; // node B in tr2
363     else if ( aNodes2[ i ] != theNode1 )
364       i2 = i;  // node 2
365   }
366
367   // nodes 1 and 2 should not be the same
368   if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
369     return false;
370
371   // tr1: A->2
372   aNodes1[ iA1 ] = aNodes2[ i2 ];
373   // tr2: B->1
374   aNodes2[ iB2 ] = aNodes1[ i1 ];
375
376   //MESSAGE( tr1 << tr2 );
377
378   GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
379   GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
380
381   //MESSAGE( tr1 << tr2 );
382
383   return true;
384   
385 }
386
387 //=======================================================================
388 //function : getQuadrangleNodes
389 //purpose  : fill theQuadNodes - nodes of a quadrangle resulting from
390 //           fusion of triangles tr1 and tr2 having shared link on
391 //           theNode1 and theNode2
392 //=======================================================================
393
394 bool getQuadrangleNodes(const SMDS_MeshNode *    theQuadNodes [],
395                         const SMDS_MeshNode *    theNode1,
396                         const SMDS_MeshNode *    theNode2,
397                         const SMDS_MeshElement * tr1,
398                         const SMDS_MeshElement * tr2 )
399 {
400   // find the 4-th node to insert into tr1
401   const SMDS_MeshNode* n4 = 0;
402   SMDS_ElemIteratorPtr it = tr2->nodesIterator();
403   while ( !n4 && it->more() )
404   {
405     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
406     bool isDiag = ( n == theNode1 || n == theNode2 );
407     if ( !isDiag )
408       n4 = n;
409   }
410   // Make an array of nodes to be in a quadrangle
411   int iNode = 0, iFirstDiag = -1;
412   it = tr1->nodesIterator();
413   while ( it->more() )
414   {
415     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
416     bool isDiag = ( n == theNode1 || n == theNode2 );
417     if ( isDiag )
418     {
419       if ( iFirstDiag < 0 )
420         iFirstDiag = iNode;
421       else if ( iNode - iFirstDiag == 1 )
422         theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
423     }
424     else if ( n == n4 )
425     {
426       return false; // tr1 and tr2 should not have all the same nodes
427     }
428     theQuadNodes[ iNode++ ] = n;
429   }
430   if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
431     theQuadNodes[ iNode ] = n4;
432
433   return true;
434 }
435
436 //=======================================================================
437 //function : DeleteDiag
438 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
439 //           with a quadrangle built on the same 4 nodes.
440 //           Return false if proper faces not found
441 //=======================================================================
442
443 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
444                                    const SMDS_MeshNode * theNode2)
445 {
446   MESSAGE( "::DeleteDiag()" );
447
448   const SMDS_MeshElement *tr1, *tr2;
449   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
450     return false;
451
452   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
453   if (!F1) return false;
454   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
455   if (!F2) return false;
456
457   const SMDS_MeshNode* aNodes [ 4 ];
458   if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
459     return false;
460
461   //MESSAGE( endl << tr1 << tr2 );
462
463   GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
464   GetMeshDS()->RemoveElement( tr2 );
465
466   //MESSAGE( endl << tr1 );
467
468   return true;
469 }
470
471 //=======================================================================
472 //function : Reorient
473 //purpose  : Reverse theElement orientation
474 //=======================================================================
475
476 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
477 {
478   if (!theElem)
479     return false;
480   SMDS_ElemIteratorPtr it = theElem->nodesIterator();
481   if ( !it || !it->more() )
482     return false;
483
484   switch ( theElem->GetType() ) {
485     
486   case SMDSAbs_Edge:
487   case SMDSAbs_Face:
488   {
489     int i = theElem->NbNodes();
490     vector<const SMDS_MeshNode*> aNodes( i );
491     while ( it->more() )
492       aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
493     return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
494   }
495   case SMDSAbs_Volume:
496   {
497     SMDS_VolumeTool vTool;
498     if ( !vTool.Set( theElem ))
499       return false;
500     vTool.Inverse();
501     return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
502   }
503   default:;
504   }
505
506   return false;
507 }
508
509 //=======================================================================
510 //function : getBadRate
511 //purpose  : 
512 //=======================================================================
513
514 static double getBadRate (const SMDS_MeshElement*               theElem,
515                           SMESH::Controls::NumericalFunctorPtr& theCrit)
516 {
517   SMESH::Controls::TSequenceOfXYZ P;
518   if ( !theElem || !theCrit->GetPoints( theElem, P ))
519     return 1e100;
520   return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
521 }
522   
523 //=======================================================================
524 //function : QuadToTri
525 //purpose  : Cut quadrangles into triangles.
526 //           theCrit is used to select a diagonal to cut
527 //=======================================================================
528
529 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> &       theElems,
530                                   SMESH::Controls::NumericalFunctorPtr theCrit)
531 {
532   MESSAGE( "::QuadToTri()" );
533
534   if ( !theCrit.get() )
535     return false;
536
537   SMESHDS_Mesh * aMesh = GetMeshDS();
538
539   set< const SMDS_MeshElement * >::iterator itElem;
540   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
541   {
542     const SMDS_MeshElement* elem = (*itElem);
543     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
544       continue;
545
546     // retrieve element nodes
547     const SMDS_MeshNode* aNodes [4];
548     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
549     int i = 0;
550     while ( itN->more() )
551       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
552
553     // compare two sets of possible triangles
554     double aBadRate1, aBadRate2; // to what extent a set is bad
555     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
556     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
557     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
558       
559     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
560     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
561     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
562
563     int aShapeId = FindShape( elem );
564     //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
565       //      << " ShapeID = " << aShapeId << endl << elem );
566     
567     if ( aBadRate1 <= aBadRate2 ) {
568       // tr1 + tr2 is better
569       aMesh->ChangeElementNodes( elem, aNodes, 3 );
570       //MESSAGE( endl << elem );
571
572       elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
573     }
574     else {
575       // tr3 + tr4 is better
576       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
577       //MESSAGE( endl << elem );
578
579       elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
580     }
581     //MESSAGE( endl << elem );
582
583     // put a new triangle on the same shape
584     if ( aShapeId )
585       aMesh->SetMeshElementOnShape( elem, aShapeId );
586   }
587
588   return true;
589 }
590
591 //=======================================================================
592 //function : AddToSameGroups
593 //purpose  : add elemToAdd to the groups the elemInGroups belongs to
594 //=======================================================================
595
596 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
597                                         const SMDS_MeshElement* elemInGroups,
598                                         SMESHDS_Mesh *          aMesh)
599 {
600   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
601   set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
602   for ( ; grIt != groups.end(); grIt++ ) {
603     SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
604     if ( group && group->SMDSGroup().Contains( elemInGroups ))
605       group->SMDSGroup().Add( elemToAdd );
606   }
607 }
608
609 //=======================================================================
610 //function : QuadToTri
611 //purpose  : Cut quadrangles into triangles.
612 //           theCrit is used to select a diagonal to cut
613 //=======================================================================
614
615 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
616                                   const bool                          the13Diag)
617 {
618   MESSAGE( "::QuadToTri()" );
619
620   SMESHDS_Mesh * aMesh = GetMeshDS();
621
622   set< const SMDS_MeshElement * >::iterator itElem;
623   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
624   {
625     const SMDS_MeshElement* elem = (*itElem);
626     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
627       continue;
628
629     // retrieve element nodes
630     const SMDS_MeshNode* aNodes [4];
631     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
632     int i = 0;
633     while ( itN->more() )
634       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
635
636     int aShapeId = FindShape( elem );
637     const SMDS_MeshElement* newElem = 0;
638     if ( the13Diag )
639     {
640       aMesh->ChangeElementNodes( elem, aNodes, 3 );
641       newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
642     }
643     else
644     {
645       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
646       newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
647     }
648
649     // put a new triangle on the same shape and add to the same groups
650
651     if ( aShapeId )
652       aMesh->SetMeshElementOnShape( newElem, aShapeId );
653
654     AddToSameGroups( newElem, elem, aMesh );
655   }
656
657   return true;
658 }
659
660 //=======================================================================
661 //function : getAngle
662 //purpose  : 
663 //=======================================================================
664
665 double getAngle(const SMDS_MeshElement * tr1,
666                 const SMDS_MeshElement * tr2,
667                 const SMDS_MeshNode *    n1,
668                 const SMDS_MeshNode *    n2)
669 {
670   double angle = 2*PI; // bad angle
671
672   // get normals
673   SMESH::Controls::TSequenceOfXYZ P1, P2;
674   if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
675        !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
676     return angle;
677   gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
678   if ( N1.SquareMagnitude() <= gp::Resolution() )
679     return angle;
680   gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
681   if ( N2.SquareMagnitude() <= gp::Resolution() )
682     return angle;
683   
684   // find the first diagonal node n1 in the triangles:
685   // take in account a diagonal link orientation
686   const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
687   for ( int t = 0; t < 2; t++ )
688   {
689     SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
690     int i = 0, iDiag = -1;
691     while ( it->more()) {
692       const SMDS_MeshElement *n = it->next();
693       if ( n == n1 || n == n2 )
694         if ( iDiag < 0)
695           iDiag = i;
696         else {
697           if ( i - iDiag == 1 )
698             nFirst[ t ] = ( n == n1 ? n2 : n1 );
699           else
700             nFirst[ t ] = n;
701           break;
702         }
703       i++;
704     }
705   }
706   if ( nFirst[ 0 ] == nFirst[ 1 ] )
707     N2.Reverse();
708
709   angle = N1.Angle( N2 );
710   //SCRUTE( angle );
711   return angle;
712 }
713
714 // =================================================
715 // class generating a unique ID for a pair of nodes
716 // and able to return nodes by that ID
717 // =================================================
718
719 class LinkID_Gen {
720  public:
721
722   LinkID_Gen( const SMESHDS_Mesh* theMesh )
723     :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
724   {}
725
726   long GetLinkID (const SMDS_MeshNode * n1,
727                   const SMDS_MeshNode * n2) const
728   {
729     return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
730   }
731
732   bool GetNodes (const long             theLinkID,
733                  const SMDS_MeshNode* & theNode1,
734                  const SMDS_MeshNode* & theNode2) const
735   {
736     theNode1 = myMesh->FindNode( theLinkID / myMaxID );
737     if ( !theNode1 ) return false;
738     theNode2 = myMesh->FindNode( theLinkID % myMaxID );
739     if ( !theNode2 ) return false;
740     return true;
741   }
742
743  private:
744   LinkID_Gen();
745   const SMESHDS_Mesh* myMesh;
746   long                myMaxID;
747 };
748
749 //=======================================================================
750 //function : TriToQuad
751 //purpose  : Fuse neighbour triangles into quadrangles.
752 //           theCrit is used to select a neighbour to fuse with.
753 //           theMaxAngle is a max angle between element normals at which
754 //           fusion is still performed.
755 //=======================================================================
756
757 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> &       theElems,
758                                   SMESH::Controls::NumericalFunctorPtr theCrit,
759                                   const double                         theMaxAngle)
760 {
761   MESSAGE( "::TriToQuad()" );
762
763   if ( !theCrit.get() )
764     return false;
765
766   SMESHDS_Mesh * aMesh = GetMeshDS();
767   LinkID_Gen aLinkID_Gen( aMesh );
768
769
770   // Prepare data for algo: build
771   // 1. map of elements with their linkIDs
772   // 2. map of linkIDs with their elements
773
774   map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
775   map< long, list< const SMDS_MeshElement* > >::iterator itLE;
776   map< const SMDS_MeshElement*, set< long > >  mapEl_setLi;
777   map< const SMDS_MeshElement*, set< long > >::iterator itEL;
778
779   set<const SMDS_MeshElement*>::iterator itElem;
780   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
781   {
782     const SMDS_MeshElement* elem = (*itElem);
783     if ( !elem || elem->NbNodes() != 3 )
784       continue;
785
786     // retrieve element nodes
787     const SMDS_MeshNode* aNodes [4];
788     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
789     int i = 0;
790     while ( itN->more() )
791       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
792     ASSERT( i == 3 );
793     aNodes[ 3 ] = aNodes[ 0 ];
794
795     // fill maps
796     for ( i = 0; i < 3; i++ )
797     {
798       long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
799       // check if elements sharing a link can be fused
800       itLE = mapLi_listEl.find( linkID );
801       if ( itLE != mapLi_listEl.end() )
802       {
803         if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link 
804           continue;
805         const SMDS_MeshElement* elem2 = (*itLE).second.front();
806 //         if ( FindShape( elem ) != FindShape( elem2 ))
807 //           continue; // do not fuse triangles laying on different shapes
808         if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
809           continue; // avoid making badly shaped quads
810         (*itLE).second.push_back( elem );
811       }
812       else
813         mapLi_listEl[ linkID ].push_back( elem );
814       mapEl_setLi [ elem ].insert( linkID );
815     }
816   }
817   // Clean the maps from the links shared by a sole element, ie
818   // links to which only one element is bound in mapLi_listEl
819
820   for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
821   {
822     int nbElems = (*itLE).second.size();
823     if ( nbElems < 2  ) {
824       const SMDS_MeshElement* elem = (*itLE).second.front();
825       long link = (*itLE).first;
826       mapEl_setLi[ elem ].erase( link );
827       if ( mapEl_setLi[ elem ].empty() )
828         mapEl_setLi.erase( elem );
829     }
830   }
831
832   // Algo: fuse triangles into quadrangles
833   
834   while ( ! mapEl_setLi.empty() )
835   {
836     // Look for the start element:
837     // the element having the least nb of shared links
838
839     const SMDS_MeshElement* startElem = 0;
840     int minNbLinks = 4;
841     for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
842     {
843       int nbLinks = (*itEL).second.size();
844       if ( nbLinks < minNbLinks )
845       {
846         startElem = (*itEL).first;
847         minNbLinks = nbLinks;
848         if ( minNbLinks == 1 )
849           break;
850       }
851     }
852
853     // search elements to fuse starting from startElem or links of elements
854     // fused earlyer - startLinks
855     list< long > startLinks;
856     while ( startElem || !startLinks.empty() )
857     {
858       while ( !startElem && !startLinks.empty() )
859       {
860         // Get an element to start, by a link
861         long linkId = startLinks.front();
862         startLinks.pop_front();
863         itLE = mapLi_listEl.find( linkId );
864         if ( itLE != mapLi_listEl.end() )
865         {
866           list< const SMDS_MeshElement* > & listElem = (*itLE).second;
867           list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
868           for ( ; itE != listElem.end() ; itE++ )
869             if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
870               startElem = (*itE);
871           mapLi_listEl.erase( itLE );
872         }
873       }
874
875       if ( startElem )
876       {
877         // Get candidates to be fused
878
879         const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
880         long link12, link13;
881         startElem = 0;
882         ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
883         set< long >& setLi = mapEl_setLi[ tr1 ];
884         ASSERT( !setLi.empty() );
885         set< long >::iterator itLi;
886         for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
887         {
888           long linkID = (*itLi);
889           itLE = mapLi_listEl.find( linkID );
890           if ( itLE == mapLi_listEl.end() )
891             continue;
892           const SMDS_MeshElement* elem = (*itLE).second.front();
893           if ( elem == tr1 )
894             elem = (*itLE).second.back();
895           mapLi_listEl.erase( itLE );
896           if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
897             continue;
898           if ( tr2 )
899           {
900             tr3 = elem;
901             link13 = linkID;
902           }
903           else
904           {
905             tr2 = elem;
906             link12 = linkID;
907           }
908
909           // add other links of elem to list of links to re-start from
910           set< long >& links = mapEl_setLi[ elem ];
911           set< long >::iterator it;
912           for ( it = links.begin(); it != links.end(); it++ )
913           {
914             long linkID2 = (*it);
915             if ( linkID2 != linkID )
916               startLinks.push_back( linkID2 );
917           }
918         }
919
920         // Get nodes of possible quadrangles
921
922         const SMDS_MeshNode *n12 [4], *n13 [4];
923         bool Ok12 = false, Ok13 = false;
924         const SMDS_MeshNode *linkNode1, *linkNode2;
925         if ( tr2 &&
926              aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
927              getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
928           Ok12 = true;
929         if ( tr3 &&
930              aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
931              getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
932           Ok13 = true;
933
934         // Choose a pair to fuse
935
936         if ( Ok12 && Ok13 )
937         {
938           SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
939           SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
940           double aBadRate12 = getBadRate( &quad12, theCrit );
941           double aBadRate13 = getBadRate( &quad13, theCrit );
942           if (  aBadRate13 < aBadRate12 )
943             Ok12 = false;
944           else
945             Ok13 = false;
946         }
947
948
949         // Make quadrangles
950         // and remove fused elems and removed links from the maps
951
952         mapEl_setLi.erase( tr1 );
953         if ( Ok12 )
954         {
955           mapEl_setLi.erase( tr2 );
956           mapLi_listEl.erase( link12 );
957           aMesh->ChangeElementNodes( tr1, n12, 4 );
958           aMesh->RemoveElement( tr2 );
959         }
960         else if ( Ok13 )
961         {
962           mapEl_setLi.erase( tr3 );
963           mapLi_listEl.erase( link13 );
964           aMesh->ChangeElementNodes( tr1, n13, 4 );
965           aMesh->RemoveElement( tr3 );
966         }
967
968         // Next element to fuse: the rejected one
969         if ( tr3 )
970           startElem = Ok12 ? tr3 : tr2;
971
972       } // if ( startElem )
973     } // while ( startElem || !startLinks.empty() )
974   } // while ( ! mapEl_setLi.empty() )
975     
976   return true;
977 }
978
979
980 #define DUMPSO(txt) \
981 //  cout << txt << endl;
982 //=============================================================================
983 /*!
984  *
985  */
986 //=============================================================================
987 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
988 {
989   if ( i1 == i2 )
990     return;
991   int tmp = idNodes[ i1 ];
992   idNodes[ i1 ] = idNodes[ i2 ];
993   idNodes[ i2 ] = tmp;
994   gp_Pnt Ptmp = P[ i1 ];
995   P[ i1 ] = P[ i2 ];
996   P[ i2 ] = Ptmp;
997   DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
998 }
999
1000 //=======================================================================
1001 //function : SortQuadNodes
1002 //purpose  : Set 4 nodes of a quadrangle face in a good order.
1003 //           Swap 1<->2 or 2<->3 nodes and correspondingly return
1004 //           1 or 2 else 0.
1005 //=======================================================================
1006
1007 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1008                                      int               idNodes[] )
1009 {
1010   gp_Pnt P[4];
1011   int i;
1012   for ( i = 0; i < 4; i++ ) {
1013     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1014     if ( !n ) return 0;
1015     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1016   }
1017
1018   gp_Vec V1(P[0], P[1]);
1019   gp_Vec V2(P[0], P[2]);
1020   gp_Vec V3(P[0], P[3]);
1021
1022   gp_Vec Cross1 = V1 ^ V2;
1023   gp_Vec Cross2 = V2 ^ V3;
1024
1025   i = 0;
1026   if (Cross1.Dot(Cross2) < 0)
1027   {
1028     Cross1 = V2 ^ V1;
1029     Cross2 = V1 ^ V3;
1030
1031     if (Cross1.Dot(Cross2) < 0)
1032       i = 2;
1033     else
1034       i = 1;
1035     swap ( i, i + 1, idNodes, P );
1036
1037 //     for ( int ii = 0; ii < 4; ii++ ) {
1038 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1039 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1040 //     }
1041   }
1042   return i;
1043 }
1044
1045 //=======================================================================
1046 //function : SortHexaNodes
1047 //purpose  : Set 8 nodes of a hexahedron in a good order.
1048 //           Return success status
1049 //=======================================================================
1050
1051 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1052                                       int               idNodes[] )
1053 {
1054   gp_Pnt P[8];
1055   int i;
1056   DUMPSO( "INPUT: ========================================");
1057   for ( i = 0; i < 8; i++ ) {
1058     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1059     if ( !n ) return false;
1060     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1061     DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1062   }
1063   DUMPSO( "========================================");
1064
1065   
1066   set<int> faceNodes;  // ids of bottom face nodes, to be found
1067   set<int> checkedId1; // ids of tried 2-nd nodes
1068   Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1069   const Standard_Real tol = 1.e-6;   // tolerance to find nodes in plane
1070   int iMin, iLoop1 = 0;
1071
1072   // Loop to try the 2-nd nodes
1073
1074   while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1075   {
1076     // Find not checked 2-nd node
1077     for ( i = 1; i < 8; i++ )
1078       if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1079         int id1 = idNodes[i];
1080         swap ( 1, i, idNodes, P );
1081         checkedId1.insert ( id1 );
1082         break;
1083       }
1084   
1085     // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1086     // ie that all but meybe one (id3 which is on the same face) nodes
1087     // lay on the same side from the triangle plane.
1088
1089     bool manyInPlane = false; // more than 4 nodes lay in plane
1090     int iLoop2 = 0;
1091     while ( ++iLoop2 < 6 ) {
1092
1093       // get 1-2-3 plane coeffs
1094       Standard_Real A, B, C, D;
1095       gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1096       if ( N.SquareMagnitude() > gp::Resolution() )
1097       {
1098         gp_Pln pln ( P[0], N );
1099         pln.Coefficients( A, B, C, D );
1100
1101         // find the node (iMin) closest to pln
1102         Standard_Real dist[ 8 ], minDist = DBL_MAX;
1103         set<int> idInPln;
1104         for ( i = 3; i < 8; i++ ) {
1105           dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1106           if ( fabs( dist[i] ) < minDist ) {
1107             minDist = fabs( dist[i] );
1108             iMin = i;
1109           }
1110           if ( fabs( dist[i] ) <= tol )
1111             idInPln.insert( idNodes[i] );
1112         }
1113
1114         // there should not be more than 4 nodes in bottom plane
1115         if ( idInPln.size() > 1 )
1116         {
1117           DUMPSO( "### idInPln.size() = " << idInPln.size());
1118           // idInPlane does not contain the first 3 nodes
1119           if ( manyInPlane || idInPln.size() == 5)
1120             return false; // all nodes in one plane
1121           manyInPlane = true;
1122
1123           // set the 1-st node to be not in plane
1124           for ( i = 3; i < 8; i++ ) {
1125             if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1126               DUMPSO( "### Reset 0-th node");
1127               swap( 0, i, idNodes, P );
1128               break;
1129             }
1130           }
1131
1132           // reset to re-check second nodes
1133           leastDist = DBL_MAX;
1134           faceNodes.clear();
1135           checkedId1.clear();
1136           iLoop1 = 0;
1137           break; // from iLoop2;
1138         }
1139
1140         // check that the other 4 nodes are on the same side
1141         bool sameSide = true;
1142         bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1143         for ( i = 3; sameSide && i < 8; i++ ) {
1144           if ( i != iMin )
1145             sameSide = ( isNeg == dist[i] <= 0.);
1146         }
1147
1148         // keep best solution
1149         if ( sameSide && minDist < leastDist ) {
1150           leastDist = minDist;
1151           faceNodes.clear();
1152           faceNodes.insert( idNodes[ 1 ] );
1153           faceNodes.insert( idNodes[ 2 ] );
1154           faceNodes.insert( idNodes[ iMin ] );
1155           DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1156             << " leastDist = " << leastDist);
1157           if ( leastDist <= DBL_MIN )
1158             break;
1159         }
1160       }
1161
1162       // set next 3-d node to check
1163       int iNext = 2 + iLoop2;
1164       if ( iNext < 8 ) {
1165         DUMPSO( "Try 2-nd");
1166         swap ( 2, iNext, idNodes, P );
1167       }
1168     } // while ( iLoop2 < 6 )
1169   } // iLoop1
1170
1171   if ( faceNodes.empty() ) return false;
1172
1173   // Put the faceNodes in proper places
1174   for ( i = 4; i < 8; i++ ) {
1175     if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1176       // find a place to put
1177       int iTo = 1;
1178       while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1179         iTo++;
1180       DUMPSO( "Set faceNodes");
1181       swap ( iTo, i, idNodes, P );
1182     }
1183   }
1184
1185     
1186   // Set nodes of the found bottom face in good order
1187   DUMPSO( " Found bottom face: ");
1188   i = SortQuadNodes( theMesh, idNodes );
1189   if ( i ) {
1190     gp_Pnt Ptmp = P[ i ];
1191     P[ i ] = P[ i+1 ];
1192     P[ i+1 ] = Ptmp;
1193   }
1194 //   else
1195 //     for ( int ii = 0; ii < 4; ii++ ) {
1196 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1197 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1198 //    }
1199
1200   // Gravity center of the top and bottom faces
1201   gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1202   gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1203
1204   // Get direction from the bottom to the top face
1205   gp_Vec upDir ( aGCb, aGCt );
1206   Standard_Real upDirSize = upDir.Magnitude();
1207   if ( upDirSize <= gp::Resolution() ) return false;
1208   upDir / upDirSize;
1209   
1210   // Assure that the bottom face normal points up
1211   gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1212   Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1213   if ( Nb.Dot( upDir ) < 0 ) {
1214     DUMPSO( "Reverse bottom face");
1215     swap( 1, 3, idNodes, P );
1216   }
1217
1218   // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1219   Standard_Real minDist = DBL_MAX;
1220   for ( i = 4; i < 8; i++ ) {
1221     // projection of P[i] to the plane defined by P[0] and upDir
1222     gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1223     Standard_Real sqDist = P[0].SquareDistance( Pp );
1224     if ( sqDist < minDist ) {
1225       minDist = sqDist;
1226       iMin = i;
1227     }
1228   }
1229   DUMPSO( "Set 4-th");
1230   swap ( 4, iMin, idNodes, P );
1231
1232   // Set nodes of the top face in good order
1233   DUMPSO( "Sort top face");
1234   i = SortQuadNodes( theMesh, &idNodes[4] );
1235   if ( i ) {
1236     i += 4;
1237     gp_Pnt Ptmp = P[ i ];
1238     P[ i ] = P[ i+1 ];
1239     P[ i+1 ] = Ptmp;
1240   }
1241
1242   // Assure that direction of the top face normal is from the bottom face
1243   gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1244   Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1245   if ( Nt.Dot( upDir ) < 0 ) {
1246     DUMPSO( "Reverse top face");
1247     swap( 5, 7, idNodes, P );
1248   }
1249
1250 //   DUMPSO( "OUTPUT: ========================================");
1251 //   for ( i = 0; i < 8; i++ ) {
1252 //     float *p = ugrid->GetPoint(idNodes[i]);
1253 //     DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1254 //   }
1255
1256   return true;
1257 }
1258
1259 //=======================================================================
1260 //function : laplacianSmooth
1261 //purpose  : pulls theNode toward the center of surrounding nodes directly
1262 //           connected to that node along an element edge
1263 //=======================================================================
1264
1265 void laplacianSmooth(SMESHDS_Mesh *                       theMesh,
1266                      const SMDS_MeshNode*                 theNode,
1267                      const set<const SMDS_MeshElement*> & theElems,
1268                      const set<const SMDS_MeshNode*> &    theFixedNodes)
1269 {
1270   // find surrounding nodes
1271   set< const SMDS_MeshNode* > nodeSet;
1272   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1273   while ( elemIt->more() )
1274   {
1275     const SMDS_MeshElement* elem = elemIt->next();
1276     if ( theElems.find( elem ) == theElems.end() )
1277       continue;
1278
1279     int i = 0, iNode = 0;
1280     const SMDS_MeshNode* aNodes [4];
1281     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1282     while ( itN->more() )
1283     {
1284       aNodes[ i ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1285       if ( aNodes[ i ] == theNode )
1286         iNode = i;
1287       else
1288         nodeSet.insert( aNodes[ i ] );
1289       i++;
1290     }
1291     if ( elem->NbNodes() == 4 ) { // remove an opposite node
1292       iNode += ( iNode < 2 ) ? 2 : -2;
1293       nodeSet.erase( aNodes[ iNode ]);
1294     }
1295   }
1296
1297   // compute new coodrs
1298   double coord[] = { 0., 0., 0. };
1299   set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1300   for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1301     const SMDS_MeshNode* node = (*nodeSetIt);
1302     coord[0] += node->X();
1303     coord[1] += node->Y();
1304     coord[2] += node->Z();
1305   }
1306   double nbNodes = nodeSet.size();
1307   theMesh->MoveNode (theNode,
1308                      coord[0]/nbNodes,
1309                      coord[1]/nbNodes,
1310                      coord[2]/nbNodes);
1311 }
1312
1313 //=======================================================================
1314 //function : centroidalSmooth
1315 //purpose  : pulls theNode toward the element-area-weighted centroid of the
1316 //           surrounding elements
1317 //=======================================================================
1318
1319 void centroidalSmooth(SMESHDS_Mesh *                       theMesh,
1320                       const SMDS_MeshNode*                 theNode,
1321                       const set<const SMDS_MeshElement*> & theElems,
1322                       const set<const SMDS_MeshNode*> &    theFixedNodes)
1323 {
1324   gp_XYZ aNewXYZ(0.,0.,0.);
1325   SMESH::Controls::Area anAreaFunc;
1326   double totalArea = 0.;
1327   int nbElems = 0;
1328
1329   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1330   while ( elemIt->more() )
1331   {
1332     const SMDS_MeshElement* elem = elemIt->next();
1333     if ( theElems.find( elem ) == theElems.end() )
1334       continue;
1335
1336     nbElems++;
1337
1338     gp_XYZ elemCenter(0.,0.,0.);
1339     SMESH::Controls::TSequenceOfXYZ aNodePoints;
1340     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1341     while ( itN->more() )
1342     {
1343       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1344       gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1345       aNodePoints.push_back( aP );
1346       elemCenter += aP;
1347     }
1348     double elemArea = anAreaFunc.GetValue( aNodePoints );
1349     totalArea += elemArea;
1350     elemCenter /= elem->NbNodes();
1351     aNewXYZ += elemCenter * elemArea;
1352   }
1353   aNewXYZ /= totalArea;
1354   theMesh->MoveNode (theNode,
1355                      aNewXYZ.X(),
1356                      aNewXYZ.Y(),
1357                      aNewXYZ.Z());
1358 }
1359
1360 //=======================================================================
1361 //function : Smooth
1362 //purpose  : Smooth theElements during theNbIterations or until a worst
1363 //           element has aspect ratio <= theTgtAspectRatio.
1364 //           Aspect Ratio varies in range [1.0, inf].
1365 //           If theElements is empty, the whole mesh is smoothed.
1366 //           theFixedNodes contains additionally fixed nodes. Nodes built
1367 //           on edges and boundary nodes are always fixed.
1368 //=======================================================================
1369
1370 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1371                                set<const SMDS_MeshNode*> &    theFixedNodes,
1372                                const SmoothMethod             theSmoothMethod,
1373                                const int                      theNbIterations,
1374                                double                         theTgtAspectRatio)
1375 {
1376   MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1377
1378   SMESHDS_Mesh* aMesh = GetMeshDS();
1379   if ( theElems.empty() ) {
1380     // add all faces
1381     SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1382     while ( fIt->more() )
1383       theElems.insert( fIt->next() );
1384   }
1385
1386   set<const SMDS_MeshNode*> setMovableNodes;
1387
1388   // Fill setMovableNodes
1389
1390   map< const SMDS_MeshNode*, int > mapNodeNbFaces;
1391   set< const SMDS_MeshElement* >::iterator itElem;
1392   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1393   {
1394     const SMDS_MeshElement* elem = (*itElem);
1395     if ( !elem || elem->GetType() != SMDSAbs_Face )
1396       continue;
1397
1398     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1399     while ( itN->more() ) {
1400       const SMDS_MeshNode* node =
1401         static_cast<const SMDS_MeshNode*>( itN->next() );
1402
1403       if ( theFixedNodes.find( node ) != theFixedNodes.end() )
1404         continue;
1405
1406       // if node is on edge => it is fixed
1407       SMDS_PositionPtr aPositionPtr = node->GetPosition();
1408       if ( aPositionPtr.get() &&
1409           (aPositionPtr->GetTypeOfPosition() == SMDS_TOP_EDGE ||
1410            aPositionPtr->GetTypeOfPosition() == SMDS_TOP_VERTEX)) {
1411         theFixedNodes.insert( node );
1412         continue;
1413       }
1414       // fill mapNodeNbFaces in order to detect fixed boundary nodes
1415       map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1416         mapNodeNbFaces.find ( node );
1417       if ( nodeNbFacesIt == mapNodeNbFaces.end() )
1418         mapNodeNbFaces.insert( map<const SMDS_MeshNode*,int>::value_type( node, 1 ));
1419       else
1420         (*nodeNbFacesIt).second++;
1421     }
1422   }
1423   // put not fixed nodes in setMovableNodes
1424   map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1425     mapNodeNbFaces.begin();
1426   for ( ; nodeNbFacesIt != mapNodeNbFaces.end(); nodeNbFacesIt++ ) {
1427     const SMDS_MeshNode* node = (*nodeNbFacesIt).first;
1428     // a node is on free boundary if it is shared by 1-2 faces
1429     if ( (*nodeNbFacesIt).second > 2 )
1430       setMovableNodes.insert( node );
1431     else
1432       theFixedNodes.insert( node );
1433   }
1434
1435   // SMOOTHING //
1436
1437   if ( theTgtAspectRatio < 1.0 )
1438     theTgtAspectRatio = 1.0;
1439
1440   SMESH::Controls::AspectRatio aQualityFunc;
1441
1442   for ( int it = 0; it < theNbIterations; it++ )
1443   {
1444     Standard_Real maxDisplacement = 0.;
1445     set<const SMDS_MeshNode*>::iterator movableNodesIt
1446       = setMovableNodes.begin();
1447     for ( ; movableNodesIt != setMovableNodes.end(); movableNodesIt++ )
1448     {
1449       const SMDS_MeshNode* node = (*movableNodesIt);
1450       gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1451
1452       // smooth
1453       if ( theSmoothMethod == LAPLACIAN )
1454         laplacianSmooth( aMesh, node, theElems, theFixedNodes );
1455       else
1456         centroidalSmooth( aMesh, node, theElems, theFixedNodes );
1457
1458       // displacement
1459       gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1460       Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1461       if ( aDispl > maxDisplacement )
1462         maxDisplacement = aDispl;
1463     }
1464     // no node movement => exit
1465     if ( maxDisplacement < 1.e-16 ) {
1466       MESSAGE("-- no node movement -- maxDisplacement: " << maxDisplacement << " it "<< it);
1467       break;
1468     }
1469
1470     // check elements quality
1471     double maxRatio  = 0;
1472     for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1473     {
1474       const SMDS_MeshElement* elem = (*itElem);
1475       if ( !elem || elem->GetType() != SMDSAbs_Face )
1476         continue;
1477       SMESH::Controls::TSequenceOfXYZ aPoints;
1478       if ( aQualityFunc.GetPoints( elem, aPoints )) {
1479         double aValue = aQualityFunc.GetValue( aPoints );
1480         if ( aValue > maxRatio )
1481           maxRatio = aValue;
1482       }
1483     }
1484     if ( maxRatio <= theTgtAspectRatio ) {
1485       MESSAGE("-- quality achived -- maxRatio " << maxRatio << " it "<< it);
1486       break;
1487     }
1488     if (it+1 == theNbIterations) {
1489       MESSAGE("-- Iteration limit exceeded --");
1490     }
1491   }
1492 }
1493
1494 //=======================================================================
1495 //function : isReverse
1496 //purpose  : Return true if normal of prevNodes is not co-directied with
1497 //           gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1498 //           iNotSame is where prevNodes and nextNodes are different
1499 //=======================================================================
1500
1501 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1502                       const SMDS_MeshNode* nextNodes[],
1503                       const int            nbNodes,
1504                       const int            iNotSame)
1505 {
1506   int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1507   int iAfterNotSame  = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1508
1509   const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1510   const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1511   const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1512   const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1513
1514   gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1515   gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1516   gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1517   gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1518
1519   gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1520
1521   return (vA ^ vB) * vN < 0.0;
1522 }
1523
1524 //=======================================================================
1525 //function : sweepElement
1526 //purpose  :
1527 //=======================================================================
1528
1529 static void sweepElement(SMESHDS_Mesh*                         aMesh,
1530                          const SMDS_MeshElement*               elem,
1531                          const vector<TNodeOfNodeListMapItr> & newNodesItVec,
1532                          list<const SMDS_MeshElement*>&        newElems)
1533 {
1534   // Loop on elem nodes:
1535   // find new nodes and detect same nodes indices
1536   int nbNodes = elem->NbNodes();
1537   list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
1538   const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
1539   int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
1540
1541   for ( iNode = 0; iNode < nbNodes; iNode++ )
1542   {
1543     TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
1544     const SMDS_MeshNode*                 node         = nnIt->first;
1545     const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
1546     if ( listNewNodes.empty() )
1547       return;
1548
1549     itNN[ iNode ] = listNewNodes.begin();
1550     prevNod[ iNode ] = node;
1551     nextNod[ iNode ] = listNewNodes.front();
1552     if ( prevNod[ iNode ] != nextNod [ iNode ])
1553       iNotSameNode = iNode;
1554     else {
1555       iSameNode = iNode;
1556       nbSame++;
1557     }
1558   }
1559   if ( nbSame == nbNodes || nbSame > 2) {
1560     MESSAGE( " Too many same nodes of element " << elem->GetID() );
1561     return;
1562   }
1563
1564   int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
1565   if ( nbSame > 0 ) {
1566     iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
1567     iAfterSame  = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
1568     iOpposSame  = ( iSameNode - 2 < 0  ? iSameNode + 2 : iSameNode - 2 );
1569   }
1570
1571   // check element orientation
1572   int i0 = 0, i2 = 2;
1573   if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
1574     //MESSAGE("Reversed elem " << elem );
1575     i0 = 2;
1576     i2 = 0;
1577     if ( nbSame > 0 ) {
1578       int iAB = iAfterSame + iBeforeSame;
1579       iBeforeSame = iAB - iBeforeSame;
1580       iAfterSame  = iAB - iAfterSame;
1581     }
1582   }
1583
1584   // make new elements
1585   int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
1586   for (iStep = 0; iStep < nbSteps; iStep++ )
1587   {
1588     // get next nodes
1589     for ( iNode = 0; iNode < nbNodes; iNode++ ) {
1590       nextNod[ iNode ] = *itNN[ iNode ];
1591       itNN[ iNode ]++;
1592     }
1593     SMDS_MeshElement* aNewElem = 0;
1594     switch ( nbNodes )
1595     {
1596     case 1: { // NODE
1597       if ( nbSame == 0 )
1598         aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
1599       break;
1600     }
1601     case 2: { // EDGE
1602
1603       if ( nbSame == 0 )
1604         aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
1605                                   nextNod[ 1 ], nextNod[ 0 ] );
1606       else
1607         aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
1608                                   nextNod[ iNotSameNode ] );
1609       break;
1610     }
1611     case 3: { // TRIANGLE
1612
1613       if ( nbSame == 0 )       // --- pentahedron
1614         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1615                                      nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
1616
1617       else if ( nbSame == 1 )  // --- pyramid
1618         aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
1619                                      nextNod[ iAfterSame ],  nextNod[ iBeforeSame ],
1620                                      nextNod[ iSameNode ]);
1621
1622       else // 2 same nodes:      --- tetrahedron
1623         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1624                                      nextNod[ iNotSameNode ]);
1625       break;
1626     }
1627     case 4: { // QUADRANGLE
1628
1629       if ( nbSame == 0 )       // --- hexahedron
1630         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
1631                                      nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
1632
1633       else if ( nbSame == 1 )  // --- pyramid + pentahedron
1634       {
1635         aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
1636                                      nextNod[ iAfterSame ],  nextNod[ iBeforeSame ],
1637                                      nextNod[ iSameNode ]);
1638         newElems.push_back( aNewElem );
1639         aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ],  prevNod[ iOpposSame ],
1640                                      prevNod[ iBeforeSame ], nextNod[ iAfterSame ],
1641                                      nextNod[ iOpposSame ],  nextNod[ iBeforeSame ] );
1642       }
1643       else if ( nbSame == 2 )  // pentahedron
1644       {
1645         if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
1646           // iBeforeSame is same too
1647           aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
1648                                        nextNod[ iOpposSame ],  prevNod[ iSameNode ],
1649                                        prevNod[ iAfterSame ],  nextNod[ iAfterSame ]);
1650         else
1651           // iAfterSame is same too
1652           aNewElem = aMesh->AddVolume (prevNod[ iSameNode ],   prevNod[ iBeforeSame ],
1653                                        nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
1654                                        prevNod[ iOpposSame ],  nextNod[ iOpposSame ]);
1655       }
1656       break;
1657     }
1658     default:
1659       return;
1660     }
1661     if ( aNewElem )
1662       newElems.push_back( aNewElem );
1663
1664     // set new prev nodes
1665     for ( iNode = 0; iNode < nbNodes; iNode++ )
1666       prevNod[ iNode ] = nextNod[ iNode ];
1667
1668   } // for steps
1669 }
1670
1671 //=======================================================================
1672 //function : makeWalls
1673 //purpose  : create 1D and 2D elements around swept elements
1674 //=======================================================================
1675
1676 static void makeWalls (SMESHDS_Mesh*                 aMesh,
1677                        TNodeOfNodeListMap &          mapNewNodes,
1678                        TElemOfElemListMap &          newElemsMap,
1679                        TElemOfVecOfNnlmiMap &        elemNewNodesMap,
1680                        set<const SMDS_MeshElement*>& elemSet)
1681 {
1682   ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
1683
1684   // Find nodes belonging to only one initial element - sweep them to get edges.
1685
1686   TNodeOfNodeListMapItr nList = mapNewNodes.begin();
1687   for ( ; nList != mapNewNodes.end(); nList++ )
1688   {
1689     const SMDS_MeshNode* node =
1690       static_cast<const SMDS_MeshNode*>( nList->first );
1691     SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1692     int nbInitElems = 0;
1693     while ( eIt->more() && nbInitElems < 2 )
1694       if ( elemSet.find( eIt->next() ) != elemSet.end() )
1695         nbInitElems++;
1696     if ( nbInitElems < 2 ) {
1697       vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
1698       list<const SMDS_MeshElement*> newEdges;
1699       sweepElement( aMesh, node, newNodesItVec, newEdges );
1700     }
1701   }
1702
1703   // Make a ceiling for each element ie an equal element of last new nodes.
1704   // Find free links of faces - make edges and sweep them into faces.
1705   
1706   TElemOfElemListMap::iterator   itElem      = newElemsMap.begin();
1707   TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
1708   for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
1709   {
1710     const SMDS_MeshElement* elem = itElem->first;
1711     vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
1712
1713     if ( elem->GetType() == SMDSAbs_Edge )
1714     {
1715       // create a ceiling edge
1716       aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
1717                      vecNewNodes[ 1 ]->second.back() );
1718     }
1719     if ( elem->GetType() != SMDSAbs_Face )
1720       continue;
1721
1722     bool hasFreeLinks = false;
1723
1724     set<const SMDS_MeshElement*> avoidSet;
1725     avoidSet.insert( elem );
1726
1727     // loop on a face nodes
1728     set<const SMDS_MeshNode*> aFaceLastNodes;
1729     int iNode, nbNodes = vecNewNodes.size();
1730     for ( iNode = 0; iNode < nbNodes; iNode++ )
1731     {
1732       aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
1733       // look for free links of a face
1734       int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1735       const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
1736       const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
1737       // check if a link is free
1738       if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
1739       {
1740         hasFreeLinks = true;
1741         // make an edge and a ceiling for a new edge
1742         if ( !aMesh->FindEdge( n1, n2 ))
1743           aMesh->AddEdge( n1, n2 );
1744         n1 = vecNewNodes[ iNode ]->second.back();
1745         n2 = vecNewNodes[ iNext ]->second.back();
1746         if ( !aMesh->FindEdge( n1, n2 ))
1747           aMesh->AddEdge( n1, n2 );
1748       }
1749     }
1750     // sweep free links into faces
1751
1752     if ( hasFreeLinks )
1753     {
1754       list<const SMDS_MeshElement*> & newVolumes = itElem->second;
1755       int iStep, nbSteps = vecNewNodes[0]->second.size();
1756       int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
1757
1758       set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
1759       for ( iNode = 0; iNode < nbNodes; iNode++ )
1760         initNodeSet.insert( vecNewNodes[ iNode ]->first );
1761
1762       for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
1763       {
1764         list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
1765         iVol = 0;
1766         while ( iVol++ < volNb ) v++;
1767         // find indices of free faces of a volume
1768         list< int > fInd;
1769         SMDS_VolumeTool vTool( *v );
1770         int iF, nbF = vTool.NbFaces();
1771         for ( iF = 0; iF < nbF; iF ++ )
1772           if (vTool.IsFreeFace( iF ) &&
1773               vTool.GetFaceNodes( iF, faceNodeSet ) &&
1774               initNodeSet != faceNodeSet) // except an initial face
1775             fInd.push_back( iF );
1776         if ( fInd.empty() )
1777           continue;
1778
1779         // create faces for all steps
1780         for ( iStep = 0; iStep < nbSteps; iStep++ )
1781         {
1782           vTool.Set( *v );
1783           vTool.SetExternalNormal();
1784           list< int >::iterator ind = fInd.begin();
1785           for ( ; ind != fInd.end(); ind++ )
1786           {
1787             const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
1788             switch ( vTool.NbFaceNodes( *ind ) ) {
1789             case 3:
1790               aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
1791             case 4:
1792               aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
1793             }
1794           }
1795           // go to the next volume
1796           iVol = 0;
1797           while ( iVol++ < nbVolumesByStep ) v++;
1798         }
1799       }
1800     } // sweep free links into faces
1801
1802     // make a ceiling face with a normal external to a volume
1803       
1804     SMDS_VolumeTool lastVol( itElem->second.back() );
1805     int iF = lastVol.GetFaceIndex( aFaceLastNodes );
1806     if ( iF >= 0 )
1807     {
1808       lastVol.SetExternalNormal();
1809       const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
1810       switch ( lastVol.NbFaceNodes( iF ) ) {
1811       case 3:
1812         if (!hasFreeLinks ||
1813             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
1814           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
1815         break;
1816       case 4:
1817         if (!hasFreeLinks ||
1818             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
1819           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
1820         break;
1821       }
1822     }
1823
1824   } // loop on swept elements
1825 }
1826
1827 //=======================================================================
1828 //function : RotationSweep
1829 //purpose  : 
1830 //=======================================================================
1831
1832 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
1833                                      const gp_Ax1&                  theAxis,
1834                                      const double                   theAngle,
1835                                      const int                      theNbSteps,
1836                                      const double                   theTol)
1837 {
1838   MESSAGE( "RotationSweep()");
1839   gp_Trsf aTrsf;
1840   aTrsf.SetRotation( theAxis, theAngle );
1841
1842   gp_Lin aLine( theAxis );
1843   double aSqTol = theTol * theTol;
1844
1845   SMESHDS_Mesh* aMesh = GetMeshDS();
1846
1847   TNodeOfNodeListMap mapNewNodes;
1848   TElemOfVecOfNnlmiMap mapElemNewNodes;
1849   TElemOfElemListMap newElemsMap;
1850
1851   // loop on theElems
1852   set< const SMDS_MeshElement* >::iterator itElem;
1853   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1854   {
1855     const SMDS_MeshElement* elem = (*itElem);
1856     if ( !elem )
1857       continue;
1858     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
1859     newNodesItVec.reserve( elem->NbNodes() );
1860
1861     // loop on elem nodes
1862     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1863     while ( itN->more() ) {
1864
1865       // check if a node has been already sweeped
1866       const SMDS_MeshNode* node =
1867         static_cast<const SMDS_MeshNode*>( itN->next() );
1868       TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
1869       if ( nIt == mapNewNodes.end() )
1870       {
1871         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
1872         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
1873
1874         // make new nodes
1875         gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
1876         double coord[3];
1877         aXYZ.Coord( coord[0], coord[1], coord[2] );
1878         bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
1879         const SMDS_MeshNode * newNode = node;
1880         for ( int i = 0; i < theNbSteps; i++ ) {
1881           if ( !isOnAxis ) {
1882             aTrsf.Transforms( coord[0], coord[1], coord[2] );
1883             newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1884           }
1885           listNewNodes.push_back( newNode );
1886         }
1887       }
1888       newNodesItVec.push_back( nIt );
1889     }
1890     // make new elements
1891     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
1892   }
1893
1894   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
1895
1896 }
1897 //=======================================================================
1898 //function : ExtrusionSweep
1899 //purpose  : 
1900 //=======================================================================
1901
1902 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
1903                                       const gp_Vec&                  theStep,
1904                                       const int                      theNbSteps)
1905 {
1906   gp_Trsf aTrsf;
1907   aTrsf.SetTranslation( theStep );
1908
1909   SMESHDS_Mesh* aMesh = GetMeshDS();
1910
1911   TNodeOfNodeListMap mapNewNodes;
1912   TElemOfVecOfNnlmiMap mapElemNewNodes;
1913   TElemOfElemListMap newElemsMap;
1914
1915   // loop on theElems
1916   set< const SMDS_MeshElement* >::iterator itElem;
1917   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1918   {
1919     // check element type
1920     const SMDS_MeshElement* elem = (*itElem);
1921     if ( !elem )
1922       continue;
1923
1924     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
1925     newNodesItVec.reserve( elem->NbNodes() );
1926
1927     // loop on elem nodes
1928     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1929     while ( itN->more() ) {
1930
1931       // check if a node has been already sweeped
1932       const SMDS_MeshNode* node =
1933         static_cast<const SMDS_MeshNode*>( itN->next() );
1934       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
1935       if ( nIt == mapNewNodes.end() )
1936       {
1937         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
1938         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
1939
1940         // make new nodes
1941         double coord[] = { node->X(), node->Y(), node->Z() };
1942         for ( int i = 0; i < theNbSteps; i++ ) {
1943           aTrsf.Transforms( coord[0], coord[1], coord[2] );
1944           const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1945           listNewNodes.push_back( newNode );
1946         }
1947       }
1948       newNodesItVec.push_back( nIt );
1949     }
1950     // make new elements
1951     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
1952   }
1953   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
1954 }
1955
1956 //=======================================================================
1957 //class    : SMESH_MeshEditor_PathPoint
1958 //purpose  : auxiliary class 
1959 //=======================================================================
1960 class SMESH_MeshEditor_PathPoint {
1961 public:
1962   SMESH_MeshEditor_PathPoint() {
1963     myPnt.SetCoord(99., 99., 99.);
1964     myTgt.SetCoord(1.,0.,0.);
1965     myAngle=0.;
1966     myPrm=0.;
1967   }
1968   void SetPnt(const gp_Pnt& aP3D){
1969     myPnt=aP3D;
1970   }
1971   void SetTangent(const gp_Dir& aTgt){
1972     myTgt=aTgt;
1973   }
1974   void SetAngle(const double& aBeta){
1975     myAngle=aBeta;
1976   }
1977   void SetParameter(const double& aPrm){
1978     myPrm=aPrm;
1979   }
1980   const gp_Pnt& Pnt()const{
1981     return myPnt;
1982   }
1983   const gp_Dir& Tangent()const{
1984     return myTgt;
1985   }
1986   double Angle()const{
1987     return myAngle;
1988   }
1989   double Parameter()const{
1990     return myPrm;
1991   }
1992
1993 protected:
1994   gp_Pnt myPnt;
1995   gp_Dir myTgt;
1996   double myAngle;
1997   double myPrm;
1998 };
1999
2000 //=======================================================================
2001 //function : ExtrusionAlongTrack
2002 //purpose  : 
2003 //=======================================================================
2004 SMESH_MeshEditor::Extrusion_Error 
2005   SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2006                                          SMESH_subMesh* theTrack,
2007                                          const SMDS_MeshNode* theN1,
2008                                          const bool theHasAngles,
2009                                          std::list<double>& theAngles,
2010                                          const bool theHasRefPoint,
2011                                          const gp_Pnt& theRefPoint)
2012 {
2013   MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2014   int j, aNbTP, aNbE, aNb;
2015   double aT1, aT2, aT, aAngle, aX, aY, aZ;
2016   std::list<double> aPrms;
2017   std::list<double>::iterator aItD;
2018   std::set< const SMDS_MeshElement* >::iterator itElem;
2019
2020   Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2021   gp_Pnt aP3D, aV0;
2022   gp_Vec aVec;
2023   gp_XYZ aGC;
2024   Handle(Geom_Curve) aC3D;
2025   TopoDS_Edge aTrackEdge;
2026   TopoDS_Vertex aV1, aV2;
2027
2028   SMDS_ElemIteratorPtr aItE;
2029   SMDS_NodeIteratorPtr aItN;
2030   SMDSAbs_ElementType aTypeE;
2031
2032   TNodeOfNodeListMap mapNewNodes;
2033   TElemOfVecOfNnlmiMap mapElemNewNodes;
2034   TElemOfElemListMap newElemsMap;
2035
2036   aTolVec=1.e-7;
2037   aTolVec2=aTolVec*aTolVec;
2038
2039   // 1. Check data
2040   aNbE = theElements.size();
2041   // nothing to do
2042   if ( !aNbE )
2043     return EXTR_NO_ELEMENTS;
2044
2045   // 1.1 Track Pattern
2046   ASSERT( theTrack );
2047
2048   SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2049
2050   aItE = pSubMeshDS->GetElements();
2051   while ( aItE->more() ) {
2052     const SMDS_MeshElement* pE = aItE->next();
2053     aTypeE = pE->GetType();
2054     // Pattern must contain links only
2055     if ( aTypeE != SMDSAbs_Edge )
2056       return EXTR_PATH_NOT_EDGE;
2057   }
2058
2059   const TopoDS_Shape& aS = theTrack->GetSubShape();
2060   // Sub shape for the Pattern must be an Edge
2061   if ( aS.ShapeType() != TopAbs_EDGE )
2062     return EXTR_BAD_PATH_SHAPE;
2063
2064   aTrackEdge = TopoDS::Edge( aS );
2065   // the Edge must not be degenerated
2066   if ( BRep_Tool::Degenerated( aTrackEdge ) )
2067     return EXTR_BAD_PATH_SHAPE;
2068
2069   TopExp::Vertices( aTrackEdge, aV1, aV2 );
2070   aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2071   aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2072
2073   aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2074   const SMDS_MeshNode* aN1 = aItN->next();
2075
2076   aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2077   const SMDS_MeshNode* aN2 = aItN->next();
2078
2079   // starting node must be aN1 or aN2 
2080   if ( !( aN1 == theN1 || aN2 == theN1 ) )
2081     return EXTR_BAD_STARTING_NODE;
2082
2083   aNbTP = pSubMeshDS->NbNodes() + 2;
2084
2085   // 1.2. Angles
2086   vector<double> aAngles( aNbTP );
2087
2088   for ( j=0; j < aNbTP; ++j ) {
2089     aAngles[j] = 0.;
2090   }
2091   
2092   if ( theHasAngles ) {
2093     aItD = theAngles.begin();
2094     for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2095       aAngle = *aItD;
2096       aAngles[j] = aAngle;
2097     }
2098   }
2099
2100   // 2. Collect parameters on the track edge  
2101   aPrms.push_back( aT1 );
2102   aPrms.push_back( aT2 );
2103
2104   aItN = pSubMeshDS->GetNodes();
2105   while ( aItN->more() ) {
2106     const SMDS_MeshNode* pNode = aItN->next();
2107     const SMDS_EdgePosition* pEPos =
2108       static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2109     aT = pEPos->GetUParameter();
2110     aPrms.push_back( aT );
2111   }
2112
2113   // sort parameters
2114   aPrms.sort();
2115   if ( aN1 == theN1 ) {
2116     if ( aT1 > aT2 ) {
2117       aPrms.reverse();
2118     }
2119   }
2120   else {
2121     if ( aT2 > aT1 ) {
2122       aPrms.reverse();
2123     }
2124   }
2125
2126   // 3. Path Points
2127   SMESH_MeshEditor_PathPoint aPP;
2128   vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2129   //
2130   aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2131   //
2132   aItD = aPrms.begin();
2133   for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2134     aT = *aItD;
2135     aC3D->D1( aT, aP3D, aVec );
2136     aL2 = aVec.SquareMagnitude();
2137     if ( aL2 < aTolVec2 )
2138       return EXTR_CANT_GET_TANGENT;
2139
2140     gp_Dir aTgt( aVec );
2141     aAngle = aAngles[j];
2142
2143     aPP.SetPnt( aP3D );
2144     aPP.SetTangent( aTgt );
2145     aPP.SetAngle( aAngle );
2146     aPP.SetParameter( aT );
2147     aPPs[j]=aPP;
2148   }
2149
2150   // 3. Center of rotation aV0
2151   aV0 = theRefPoint;
2152   if ( !theHasRefPoint ) {
2153     aNb = 0;
2154     aGC.SetCoord( 0.,0.,0. );
2155
2156     itElem = theElements.begin();
2157     for ( ; itElem != theElements.end(); itElem++ ) {
2158       const SMDS_MeshElement* elem = (*itElem);
2159
2160       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2161       while ( itN->more() ) {
2162         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2163         aX = node->X();
2164         aY = node->Y();
2165         aZ = node->Z();
2166
2167         if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2168           list<const SMDS_MeshNode*> aLNx;
2169           mapNewNodes[node] = aLNx;
2170           //
2171           gp_XYZ aXYZ( aX, aY, aZ );
2172           aGC += aXYZ;
2173           ++aNb;
2174         }
2175       }
2176     }
2177     aGC /= aNb;
2178     aV0.SetXYZ( aGC );
2179   } // if (!theHasRefPoint) {
2180   mapNewNodes.clear();
2181
2182   // 4. Processing the elements
2183   SMESHDS_Mesh* aMesh = GetMeshDS();
2184
2185   for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2186     // check element type
2187     const SMDS_MeshElement* elem = (*itElem);
2188     aTypeE = elem->GetType();
2189     if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2190       continue;
2191
2192     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2193     newNodesItVec.reserve( elem->NbNodes() );
2194
2195     // loop on elem nodes
2196     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2197     while ( itN->more() ) {
2198
2199       // check if a node has been already processed
2200       const SMDS_MeshNode* node = 
2201         static_cast<const SMDS_MeshNode*>( itN->next() );
2202       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2203       if ( nIt == mapNewNodes.end() ) {
2204         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2205         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2206         
2207         // make new nodes
2208         aX = node->X();  aY = node->Y(); aZ = node->Z();
2209         
2210         Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2211         gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2212         gp_Ax1 anAx1, anAxT1T0;
2213         gp_Dir aDT1x, aDT0x, aDT1T0;
2214
2215         aTolAng=1.e-4;
2216
2217         aV0x = aV0;
2218         aPN0.SetCoord(aX, aY, aZ);
2219
2220         const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2221         aP0x = aPP0.Pnt();
2222         aDT0x= aPP0.Tangent();
2223
2224         for ( j = 1; j < aNbTP; ++j ) {
2225           const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2226           aP1x = aPP1.Pnt();
2227           aDT1x = aPP1.Tangent();
2228           aAngle1x = aPP1.Angle();
2229           
2230           gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0; 
2231           // Translation
2232           gp_Vec aV01x( aP0x, aP1x );
2233           aTrsf.SetTranslation( aV01x );
2234           
2235           // traslated point
2236           aV1x = aV0x.Transformed( aTrsf );
2237           aPN1 = aPN0.Transformed( aTrsf );
2238           
2239           // rotation 1 [ T1,T0 ]
2240           aAngleT1T0=-aDT1x.Angle( aDT0x );
2241           if (fabs(aAngleT1T0) > aTolAng) {
2242             aDT1T0=aDT1x^aDT0x;
2243             anAxT1T0.SetLocation( aV1x );
2244             anAxT1T0.SetDirection( aDT1T0 );
2245             aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2246             
2247             aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2248           }
2249
2250           // rotation 2
2251           if ( theHasAngles ) {
2252             anAx1.SetLocation( aV1x );
2253             anAx1.SetDirection( aDT1x );
2254             aTrsfRot.SetRotation( anAx1, aAngle1x );
2255             
2256             aPN1 = aPN1.Transformed( aTrsfRot );
2257           }
2258
2259           // make new node
2260           aX = aPN1.X();
2261           aY = aPN1.Y();
2262           aZ = aPN1.Z();
2263           const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2264           listNewNodes.push_back( newNode );
2265           
2266           aPN0 = aPN1;
2267           aP0x = aP1x;
2268           aV0x = aV1x;
2269           aDT0x = aDT1x;
2270         }
2271       }
2272       newNodesItVec.push_back( nIt );
2273     }
2274     // make new elements
2275     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2276   }
2277   
2278   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2279
2280   return EXTR_OK;
2281 }
2282
2283 //=======================================================================
2284 //function : Transform
2285 //purpose  : 
2286 //=======================================================================
2287
2288 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2289                                   const gp_Trsf&                 theTrsf,
2290                                   const bool                     theCopy)
2291 {
2292   bool needReverse;
2293   switch ( theTrsf.Form() ) {
2294   case gp_PntMirror:
2295   case gp_Ax2Mirror:
2296     needReverse = true;
2297     break;
2298   default:
2299     needReverse = false;
2300   }
2301
2302   SMESHDS_Mesh* aMesh = GetMeshDS();
2303
2304   // map old node to new one
2305   TNodeNodeMap nodeMap;
2306
2307   // elements sharing moved nodes; those of them which have all
2308   // nodes mirrored but are not in theElems are to be reversed
2309   set<const SMDS_MeshElement*> inverseElemSet;
2310
2311   // loop on theElems
2312   set< const SMDS_MeshElement* >::iterator itElem;
2313   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2314   {
2315     const SMDS_MeshElement* elem = (*itElem);
2316     if ( !elem )
2317       continue;
2318
2319     // loop on elem nodes
2320     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2321     while ( itN->more() ) {
2322
2323       // check if a node has been already transormed
2324       const SMDS_MeshNode* node =
2325         static_cast<const SMDS_MeshNode*>( itN->next() );
2326       if (nodeMap.find( node ) != nodeMap.end() )
2327         continue; 
2328
2329       double coord[3];
2330       coord[0] = node->X();
2331       coord[1] = node->Y();
2332       coord[2] = node->Z();
2333       theTrsf.Transforms( coord[0], coord[1], coord[2] );
2334       const SMDS_MeshNode * newNode = node;
2335       if ( theCopy )
2336         newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2337       else
2338         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2339       nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2340
2341       // keep inverse elements
2342       if ( !theCopy && needReverse ) {
2343         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2344         while ( invElemIt->more() )
2345           inverseElemSet.insert( invElemIt->next() );
2346       }
2347     }
2348   }
2349
2350   // either new elements are to be created
2351   // or a mirrored element are to be reversed
2352   if ( !theCopy && !needReverse)
2353     return;
2354
2355   if ( !inverseElemSet.empty()) {
2356     set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2357     for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2358       theElems.insert( *invElemIt );
2359   }
2360
2361   // replicate or reverse elements 
2362
2363   enum {
2364     REV_TETRA   = 0,  //  = nbNodes - 4
2365     REV_PYRAMID = 1,  //  = nbNodes - 4
2366     REV_PENTA   = 2,  //  = nbNodes - 4
2367     REV_FACE    = 3,
2368     REV_HEXA    = 4,  //  = nbNodes - 4
2369     FORWARD     = 5
2370     };
2371   int index[][8] = {
2372     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA  
2373     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
2374     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA  
2375     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE   
2376     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA   
2377     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD    
2378   };
2379
2380   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2381   {
2382     const SMDS_MeshElement* elem = (*itElem);
2383     if ( !elem || elem->GetType() == SMDSAbs_Node )
2384       continue;
2385
2386     int nbNodes = elem->NbNodes();
2387     int elemType = elem->GetType();
2388
2389     int* i = index[ FORWARD ];
2390     if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2391       if ( elemType == SMDSAbs_Face )
2392         i = index[ REV_FACE ];
2393       else
2394         i = index[ nbNodes - 4 ];
2395
2396     // find transformed nodes
2397     const SMDS_MeshNode* nodes[8];
2398     int iNode = 0;
2399     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2400     while ( itN->more() )
2401     {
2402       const SMDS_MeshNode* node =
2403         static_cast<const SMDS_MeshNode*>( itN->next() );
2404       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
2405       if ( nodeMapIt == nodeMap.end() )
2406         break; // not all nodes transformed
2407       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
2408     }
2409     if ( iNode != nbNodes )
2410       continue; // not all nodes transformed
2411
2412     if ( theCopy ) 
2413     {
2414       // add a new element
2415       switch ( elemType ) {
2416       case SMDSAbs_Edge:
2417         aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
2418         break;
2419       case SMDSAbs_Face:
2420         if ( nbNodes == 3 )
2421           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2422         else
2423           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
2424         break;
2425       case SMDSAbs_Volume:
2426         if ( nbNodes == 4 )
2427           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
2428         else if ( nbNodes == 8 )
2429           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2430                             nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
2431         else if ( nbNodes == 6 )
2432           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2433                             nodes[ 4 ], nodes[ 5 ]);
2434         else if ( nbNodes == 5 )
2435           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2436                             nodes[ 4 ]);
2437         break;
2438       default:;
2439       }
2440     }
2441     else
2442     {
2443       // reverse element as it was reversed by transformation
2444       if ( nbNodes > 2 )
2445         aMesh->ChangeElementNodes( elem, nodes, nbNodes );
2446     }
2447   }
2448 }
2449
2450 //=======================================================================
2451 //function : FindCoincidentNodes
2452 //purpose  : Return list of group of nodes close to each other within theTolerance
2453 //           Search among theNodes or in the whole mesh if theNodes is empty.
2454 //=======================================================================
2455
2456 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
2457                                             const double                theTolerance,
2458                                             TListOfListOfNodes &        theGroupsOfNodes)
2459 {
2460   double tol2 = theTolerance * theTolerance;
2461
2462   list<const SMDS_MeshNode*> nodes;
2463   if ( theNodes.empty() )
2464   { // get all nodes in the mesh
2465     SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
2466     while ( nIt->more() )
2467       nodes.push_back( nIt->next() );
2468   }
2469   else
2470   {
2471     nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
2472   }  
2473
2474   list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
2475   for ( ; it1 != nodes.end(); it1++ )
2476   {
2477     const SMDS_MeshNode* n1 = *it1;
2478     gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
2479
2480     list<const SMDS_MeshNode*> * groupPtr = 0;
2481     it2 = it1;
2482     for ( it2++; it2 != nodes.end(); it2++ )
2483     {
2484       const SMDS_MeshNode* n2 = *it2;
2485       gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
2486       if ( p1.SquareDistance( p2 ) <= tol2 )
2487       {
2488         if ( !groupPtr ) {
2489           theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
2490           groupPtr = & theGroupsOfNodes.back();
2491           groupPtr->push_back( n1 );
2492         }
2493         groupPtr->push_back( n2 );
2494         it2 = nodes.erase( it2 );
2495         it2--;
2496       }
2497     }
2498   }
2499 }
2500
2501 //=======================================================================
2502 //function : MergeNodes
2503 //purpose  : In each group, the cdr of nodes are substituted by the first one
2504 //           in all elements.
2505 //=======================================================================
2506
2507 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
2508 {
2509   SMESHDS_Mesh* aMesh = GetMeshDS();
2510
2511   TNodeNodeMap nodeNodeMap; // node to replace - new node
2512   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
2513   list< int > rmElemIds, rmNodeIds;
2514
2515   // Fill nodeNodeMap and elems
2516
2517   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
2518   for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
2519   {
2520     list<const SMDS_MeshNode*>& nodes = *grIt;
2521     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
2522     const SMDS_MeshNode* nToKeep = *nIt;
2523     for ( ; nIt != nodes.end(); nIt++ )
2524     {
2525       const SMDS_MeshNode* nToRemove = *nIt;
2526       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
2527       if ( nToRemove != nToKeep ) {
2528         rmNodeIds.push_back( nToRemove->GetID() );
2529         AddToSameGroups( nToKeep, nToRemove, aMesh );
2530       }
2531
2532       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
2533       while ( invElemIt->more() )
2534         elems.insert( invElemIt->next() );
2535     }
2536   }
2537   // Change element nodes or remove an element 
2538
2539   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
2540   for ( ; eIt != elems.end(); eIt++ )
2541   {
2542     const SMDS_MeshElement* elem = *eIt;
2543     int nbNodes = elem->NbNodes();
2544     int aShapeId = FindShape( elem );
2545
2546     set<const SMDS_MeshNode*> nodeSet;
2547     const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
2548     int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
2549
2550     // get new seq of nodes
2551     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2552     while ( itN->more() )
2553     {
2554       const SMDS_MeshNode* n =
2555         static_cast<const SMDS_MeshNode*>( itN->next() );
2556
2557       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
2558       if ( nnIt != nodeNodeMap.end() ) { // n sticks
2559         n = (*nnIt).second;
2560         iRepl[ nbRepl++ ] = iCur;
2561       }
2562       curNodes[ iCur ] = n;
2563       bool isUnique = nodeSet.insert( n ).second;
2564       if ( isUnique )
2565         uniqueNodes[ iUnique++ ] = n;
2566       iCur++;
2567     }
2568
2569     // Analyse element topology after replacement
2570
2571     bool isOk = true;
2572     int nbUniqueNodes = nodeSet.size();
2573     if ( nbNodes != nbUniqueNodes ) // some nodes stick
2574     {
2575       switch ( nbNodes ) {
2576       case 2: ///////////////////////////////////// EDGE
2577         isOk = false; break;
2578       case 3: ///////////////////////////////////// TRIANGLE
2579         isOk = false; break;
2580       case 4:
2581         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
2582           isOk = false;
2583         else { //////////////////////////////////// QUADRANGLE
2584           if ( nbUniqueNodes < 3 )
2585             isOk = false;
2586           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
2587             isOk = false; // opposite nodes stick
2588         }
2589         break;
2590       case 6: ///////////////////////////////////// PENTAHEDRON
2591         if ( nbUniqueNodes == 4 ) {
2592           // ---------------------------------> tetrahedron
2593           if (nbRepl == 3 &&
2594               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
2595             // all top nodes stick: reverse a bottom
2596             uniqueNodes[ 0 ] = curNodes [ 1 ];
2597             uniqueNodes[ 1 ] = curNodes [ 0 ];
2598           }
2599           else if (nbRepl == 3 &&
2600                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
2601             // all bottom nodes stick: set a top before
2602             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
2603             uniqueNodes[ 0 ] = curNodes [ 3 ];
2604             uniqueNodes[ 1 ] = curNodes [ 4 ];
2605             uniqueNodes[ 2 ] = curNodes [ 5 ];
2606           }
2607           else if (nbRepl == 4 &&
2608                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
2609             // a lateral face turns into a line: reverse a bottom
2610             uniqueNodes[ 0 ] = curNodes [ 1 ];
2611             uniqueNodes[ 1 ] = curNodes [ 0 ];
2612           }
2613           else
2614             isOk = false;
2615         }
2616         else if ( nbUniqueNodes == 5 ) {
2617           // PENTAHEDRON --------------------> 2 tetrahedrons
2618           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
2619             // a bottom node sticks with a linked top one
2620             // 1.
2621             SMDS_MeshElement* newElem = 
2622               aMesh->AddVolume(curNodes[ 3 ],
2623                                curNodes[ 4 ],
2624                                curNodes[ 5 ],
2625                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
2626             if ( aShapeId )
2627               aMesh->SetMeshElementOnShape( newElem, aShapeId );
2628             // 2. : reverse a bottom
2629             uniqueNodes[ 0 ] = curNodes [ 1 ];
2630             uniqueNodes[ 1 ] = curNodes [ 0 ];
2631             nbUniqueNodes = 4;
2632           }
2633           else
2634             isOk = false;
2635         }
2636         else
2637           isOk = false;
2638         break;
2639       case 8: { //////////////////////////////////// HEXAHEDRON
2640         isOk = false;
2641         SMDS_VolumeTool hexa (elem);
2642         hexa.SetExternalNormal();
2643         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
2644           //////////////////////// ---> tetrahedron
2645           for ( int iFace = 0; iFace < 6; iFace++ ) {
2646             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2647             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2648                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2649                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2650               // one face turns into a point ...
2651               int iOppFace = hexa.GetOppFaceIndex( iFace );
2652               ind = hexa.GetFaceNodesIndices( iOppFace );
2653               int nbStick = 0;
2654               iUnique = 2; // reverse a tetrahedron bottom
2655               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
2656                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2657                   nbStick++;
2658                 else if ( iUnique >= 0 )
2659                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2660               }
2661               if ( nbStick == 1 ) {
2662                 // ... and the opposite one - into a triangle.
2663                 // set a top node
2664                 ind = hexa.GetFaceNodesIndices( iFace );
2665                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
2666                 isOk = true;
2667               }
2668               break;
2669             }
2670           }
2671         }
2672         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
2673           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
2674           for ( int iFace = 0; iFace < 6; iFace++ ) {
2675             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2676             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2677                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2678                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2679               // one face turns into a point ...
2680               int iOppFace = hexa.GetOppFaceIndex( iFace );
2681               ind = hexa.GetFaceNodesIndices( iOppFace );
2682               int nbStick = 0;
2683               iUnique = 2;  // reverse a tetrahedron 1 bottom
2684               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
2685                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2686                   nbStick++;
2687                 else if ( iUnique >= 0 )
2688                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2689               }
2690               if ( nbStick == 0 ) {
2691                 // ... and the opposite one is a quadrangle
2692                 // set a top node
2693                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
2694                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
2695                 nbUniqueNodes = 4;
2696                 // tetrahedron 2
2697                 SMDS_MeshElement* newElem = 
2698                   aMesh->AddVolume(curNodes[ind[ 0 ]],
2699                                    curNodes[ind[ 3 ]],
2700                                    curNodes[ind[ 2 ]],
2701                                    curNodes[indTop[ 0 ]]);
2702                 if ( aShapeId )
2703                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
2704                 isOk = true;
2705               }
2706               break;
2707             }
2708           }
2709         }
2710         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
2711           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
2712           // find indices of quad and tri faces
2713           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
2714           for ( iFace = 0; iFace < 6; iFace++ ) {
2715             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2716             nodeSet.clear();
2717             for ( iCur = 0; iCur < 4; iCur++ )
2718               nodeSet.insert( curNodes[ind[ iCur ]] );
2719             nbUniqueNodes = nodeSet.size();
2720             if ( nbUniqueNodes == 3 )
2721               iTriFace[ nbTri++ ] = iFace;
2722             else if ( nbUniqueNodes == 4 )
2723               iQuadFace[ nbQuad++ ] = iFace;
2724           }
2725           if (nbQuad == 2 && nbTri == 4 &&
2726               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
2727             // 2 opposite quadrangles stuck with a diagonal;
2728             // sample groups of merged indices: (0-4)(2-6)
2729             // --------------------------------------------> 2 tetrahedrons
2730             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
2731             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
2732             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
2733             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
2734                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
2735               // stuck with 0-2 diagonal
2736               i0  = ind1[ 3 ];
2737               i1d = ind1[ 0 ];
2738               i2  = ind1[ 1 ];
2739               i3d = ind1[ 2 ];
2740               i0t = ind2[ 1 ];
2741               i2t = ind2[ 3 ];
2742             }
2743             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
2744                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
2745               // stuck with 1-3 diagonal
2746               i0  = ind1[ 0 ];
2747               i1d = ind1[ 1 ];
2748               i2  = ind1[ 2 ];
2749               i3d = ind1[ 3 ];
2750               i0t = ind2[ 0 ];
2751               i2t = ind2[ 1 ];
2752             }
2753             else {
2754               ASSERT(0);
2755             }
2756             // tetrahedron 1
2757             uniqueNodes[ 0 ] = curNodes [ i0 ];
2758             uniqueNodes[ 1 ] = curNodes [ i1d ];
2759             uniqueNodes[ 2 ] = curNodes [ i3d ];
2760             uniqueNodes[ 3 ] = curNodes [ i0t ];
2761             nbUniqueNodes = 4;
2762             // tetrahedron 2
2763             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
2764                                                          curNodes[ i2 ],
2765                                                          curNodes[ i3d ],
2766                                                          curNodes[ i2t ]);
2767             if ( aShapeId )
2768               aMesh->SetMeshElementOnShape( newElem, aShapeId );
2769             isOk = true;
2770           }
2771           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
2772                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
2773             // --------------------------------------------> prism
2774             // find 2 opposite triangles
2775             nbUniqueNodes = 6;
2776             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
2777               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
2778                 // find indices of kept and replaced nodes
2779                 // and fill unique nodes of 2 opposite triangles
2780                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
2781                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
2782                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
2783                 // fill unique nodes
2784                 iUnique = 0;
2785                 isOk = true;
2786                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
2787                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
2788                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
2789                   if ( n == nInit ) {
2790                     // iCur of a linked node of the opposite face (make normals co-directed):
2791                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
2792                     // check that correspondent corners of triangles are linked
2793                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
2794                       isOk = false;
2795                     else {
2796                       uniqueNodes[ iUnique ] = n;
2797                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
2798                       iUnique++;
2799                     }
2800                   }
2801                 }
2802                 break;
2803               }
2804             }
2805           }
2806         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
2807         break;
2808       } // HEXAHEDRON
2809
2810       default:
2811         isOk = false;
2812       } // switch ( nbNodes )
2813
2814     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
2815     
2816     if ( isOk )
2817       aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
2818     else
2819       rmElemIds.push_back( elem->GetID() );
2820
2821   } // loop on elements
2822
2823   // Remove equal nodes and bad elements
2824
2825   Remove( rmNodeIds, true );
2826   Remove( rmElemIds, false );
2827
2828 }
2829
2830 //=======================================================================
2831 //function : MergeEqualElements
2832 //purpose  : Remove all but one of elements built on the same nodes.
2833 //=======================================================================
2834
2835 void SMESH_MeshEditor::MergeEqualElements()
2836 {
2837   SMESHDS_Mesh* aMesh = GetMeshDS();
2838
2839   SMDS_EdgeIteratorPtr   eIt = aMesh->edgesIterator();
2840   SMDS_FaceIteratorPtr   fIt = aMesh->facesIterator();
2841   SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
2842
2843   list< int > rmElemIds; // IDs of elems to remove
2844
2845   for ( int iDim = 1; iDim <= 3; iDim++ ) {
2846
2847     set< set <const SMDS_MeshElement*> > setOfNodeSet;
2848
2849     while ( 1 ) {
2850       // get next element
2851       const SMDS_MeshElement* elem = 0;
2852       if ( iDim == 1 ) {
2853         if ( eIt->more() ) elem = eIt->next();
2854       } else if ( iDim == 2 ) {
2855         if ( fIt->more() ) elem = fIt->next();
2856       } else {
2857         if ( vIt->more() ) elem = vIt->next();
2858       }
2859       if ( !elem ) break;
2860
2861       // get elem nodes
2862       set <const SMDS_MeshElement*> nodeSet;
2863       SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
2864       while ( nodeIt->more() )
2865         nodeSet.insert( nodeIt->next() );
2866
2867       // check uniqueness
2868       bool isUnique = setOfNodeSet.insert( nodeSet ).second;
2869       if ( !isUnique )
2870         rmElemIds.push_back( elem->GetID() );
2871     }
2872   }
2873
2874   Remove( rmElemIds, false );
2875 }
2876
2877 //=======================================================================
2878 //function : FindFaceInSet
2879 //purpose  : Return a face having linked nodes n1 and n2 and which is
2880 //           - not in avoidSet,
2881 //           - in elemSet provided that !elemSet.empty()
2882 //=======================================================================
2883
2884 const SMDS_MeshElement*
2885   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*                n1,
2886                                   const SMDS_MeshNode*                n2,
2887                                   const set<const SMDS_MeshElement*>& elemSet,
2888                                   const set<const SMDS_MeshElement*>& avoidSet)
2889
2890 {
2891   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
2892   while ( invElemIt->more() ) { // loop on inverse elements of n1
2893     const SMDS_MeshElement* elem = invElemIt->next();
2894     if (elem->GetType() != SMDSAbs_Face ||
2895         avoidSet.find( elem ) != avoidSet.end() )
2896       continue;
2897     if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
2898       continue;
2899     // get face nodes and find index of n1
2900     int i1, nbN = elem->NbNodes(), iNode = 0;
2901     const SMDS_MeshNode* faceNodes[ nbN ], *n;
2902     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2903     while ( nIt->more() ) {
2904       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2905       if ( faceNodes[ iNode++ ] == n1 )
2906         i1 = iNode - 1;
2907     }
2908     // find a n2 linked to n1
2909     for ( iNode = 0; iNode < 2; iNode++ ) {
2910       if ( iNode ) // node before n1
2911         n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
2912       else         // node after n1
2913         n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
2914       if ( n == n2 )
2915         return elem;
2916     }
2917   }
2918   return 0;
2919 }
2920
2921 //=======================================================================
2922 //function : findAdjacentFace
2923 //purpose  : 
2924 //=======================================================================
2925
2926 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
2927                                                 const SMDS_MeshNode* n2,
2928                                                 const SMDS_MeshElement* elem)
2929 {
2930   set<const SMDS_MeshElement*> elemSet, avoidSet;
2931   if ( elem )
2932     avoidSet.insert ( elem );
2933   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
2934 }
2935   
2936 //=======================================================================
2937 //function : findFreeBorder
2938 //purpose  : 
2939 //=======================================================================
2940
2941 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
2942
2943 static bool findFreeBorder (const SMDS_MeshNode*                theFirstNode,
2944                             const SMDS_MeshNode*                theSecondNode,
2945                             const SMDS_MeshNode*                theLastNode,
2946                             list< const SMDS_MeshNode* > &      theNodes,
2947                             list< const SMDS_MeshElement* > &   theFaces)
2948 {
2949   if ( !theFirstNode || !theSecondNode )
2950     return false;
2951   // find border face between theFirstNode and theSecondNode
2952   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
2953   if ( !curElem )
2954     return false;
2955
2956   theFaces.push_back( curElem );
2957   theNodes.push_back( theFirstNode );
2958   theNodes.push_back( theSecondNode );
2959
2960   const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
2961   set < const SMDS_MeshElement* > foundElems;
2962   bool needTheLast = ( theLastNode != 0 );
2963
2964   while ( nStart != theLastNode )
2965   {
2966     if ( nStart == theFirstNode )
2967       return !needTheLast;
2968
2969     // find all free border faces sharing form nStart
2970
2971     list< const SMDS_MeshElement* > curElemList;
2972     list< const SMDS_MeshNode* > nStartList;
2973     SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
2974     while ( invElemIt->more() ) {
2975       const SMDS_MeshElement* e = invElemIt->next();
2976       if ( e == curElem || foundElems.insert( e ).second )
2977       {
2978         // get nodes
2979         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2980         int iNode = 0, nbNodes = e->NbNodes();
2981         while ( nIt->more() )
2982           nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2983         nodes[ iNode ] = nodes[ 0 ];
2984         // check 2 links
2985         for ( iNode = 0; iNode < nbNodes; iNode++ )
2986           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
2987                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
2988               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
2989           {
2990             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
2991             curElemList.push_back( e );
2992           }
2993       }
2994     }
2995     // analyse the found
2996
2997     int nbNewBorders = curElemList.size();
2998     if ( nbNewBorders == 0 ) {
2999       // no free border furthermore
3000       return !needTheLast;
3001     }
3002     else if ( nbNewBorders == 1 ) {
3003       // one more element found
3004       nIgnore = nStart;
3005       nStart = nStartList.front();
3006       curElem = curElemList.front();
3007       theFaces.push_back( curElem );
3008       theNodes.push_back( nStart );
3009     }
3010     else {
3011       // several continuations found
3012       list< const SMDS_MeshElement* >::iterator curElemIt;
3013       list< const SMDS_MeshNode* >::iterator nStartIt;
3014       // check if one of them reached the last node
3015       if ( needTheLast ) {
3016         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3017              curElemIt!= curElemList.end();
3018              curElemIt++, nStartIt++ )
3019           if ( *nStartIt == theLastNode ) {
3020             theFaces.push_back( *curElemIt );
3021             theNodes.push_back( *nStartIt );
3022             return true;
3023           }
3024       }
3025       // find the best free border by the continuations
3026       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
3027       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3028       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3029            curElemIt!= curElemList.end();
3030            curElemIt++, nStartIt++ )
3031       {
3032         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3033         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3034         // find one more free border
3035         if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3036           cNL->clear();
3037           cFL->clear();
3038         }
3039         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3040           // choice: clear a worse one
3041           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3042           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3043           contNodes[ iWorse ].clear();
3044           contFaces[ iWorse ].clear();
3045         }
3046       }
3047       if ( contNodes[0].empty() && contNodes[1].empty() )
3048         return false;
3049
3050       // append the best free border
3051       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3052       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3053       theNodes.pop_back(); // remove nIgnore
3054       theNodes.pop_back(); // remove nStart
3055       theFaces.pop_back(); // remove curElem
3056       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3057       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3058       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3059       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3060       return true;
3061
3062     } // several continuations found
3063   } // while ( nStart != theLastNode )
3064
3065   return true;
3066 }
3067
3068 //=======================================================================
3069 //function : CheckFreeBorderNodes
3070 //purpose  : Return true if the tree nodes are on a free border
3071 //=======================================================================
3072
3073 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3074                                             const SMDS_MeshNode* theNode2,
3075                                             const SMDS_MeshNode* theNode3)
3076 {
3077   list< const SMDS_MeshNode* > nodes;
3078   list< const SMDS_MeshElement* > faces;
3079   return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3080 }
3081
3082 //=======================================================================
3083 //function : SewFreeBorder
3084 //purpose  : 
3085 //=======================================================================
3086
3087 SMESH_MeshEditor::Sew_Error
3088   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3089                                    const SMDS_MeshNode* theBordSecondNode,
3090                                    const SMDS_MeshNode* theBordLastNode,
3091                                    const SMDS_MeshNode* theSideFirstNode,
3092                                    const SMDS_MeshNode* theSideSecondNode,
3093                                    const SMDS_MeshNode* theSideThirdNode,
3094                                    bool                 theSideIsFreeBorder)
3095 {
3096   MESSAGE("::SewFreeBorder()");
3097   Sew_Error aResult = SEW_OK;
3098
3099   // ====================================
3100   //    find side nodes and elements
3101   // ====================================
3102
3103   list< const SMDS_MeshNode* > nSide[ 2 ];
3104   list< const SMDS_MeshElement* > eSide[ 2 ];
3105   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3106   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3107
3108   // Free border 1
3109   // --------------
3110   if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3111                       nSide[0], eSide[0])) {
3112     MESSAGE(" Free Border 1 not found " );
3113     aResult = SEW_BORDER1_NOT_FOUND;
3114   }
3115   if (theSideIsFreeBorder)
3116   { 
3117     // Free border 2
3118     // --------------
3119     if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3120                         nSide[1], eSide[1])) {
3121       MESSAGE(" Free Border 2 not found " );
3122       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3123     }
3124   }
3125   if ( aResult != SEW_OK )
3126     return aResult;
3127
3128   if (!theSideIsFreeBorder)
3129   {
3130     // Side 2
3131     // --------------
3132
3133     // -------------------------------------------------------------------------
3134     // Algo:
3135     // 1. If nodes to merge are not coincident, move nodes of the free border
3136     //    from the coord sys defined by the direction from the first to last
3137     //    nodes of the border to the correspondent sys of the side 2
3138     // 2. On the side 2, find the links most co-directed with the correspondent
3139     //    links of the free border
3140     // -------------------------------------------------------------------------
3141
3142     // 1. Since sewing may brake if there are volumes to split on the side 2,
3143     //    we wont move nodes but just compute new coordinates for them
3144     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3145     TNodeXYZMap nBordXYZ;
3146     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3147     list< const SMDS_MeshNode* >::iterator nBordIt;
3148
3149     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3150     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3151     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3152     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3153     double tol2 = 1.e-8;
3154     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3155     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3156     {
3157       // Need node movement.
3158
3159       // find X and Z axes to create trsf
3160       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3161       gp_Vec X = Zs ^ Zb;
3162       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3163         // Zb || Zs
3164         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3165
3166       // coord systems
3167       gp_Ax3 toBordAx( Pb1, Zb, X );
3168       gp_Ax3 fromSideAx( Ps1, Zs, X );
3169       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
3170       // set trsf
3171       gp_Trsf toBordSys, fromSide2Sys;
3172       toBordSys.SetTransformation( toBordAx );
3173       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
3174       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
3175       
3176       // move
3177       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3178         const SMDS_MeshNode* n = *nBordIt;
3179         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
3180         toBordSys.Transforms( xyz );
3181         fromSide2Sys.Transforms( xyz );
3182         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
3183       }
3184     }
3185     else
3186     {
3187       // just insert nodes XYZ in the nBordXYZ map
3188       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3189         const SMDS_MeshNode* n = *nBordIt;
3190         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
3191       }
3192     }
3193
3194     // 2. On the side 2, find the links most co-directed with the correspondent
3195     //    links of the free border
3196
3197     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
3198     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
3199     sideNodes.push_back( theSideFirstNode );
3200
3201     bool hasVolumes = false;
3202     LinkID_Gen aLinkID_Gen( GetMeshDS() );
3203     set<long> foundSideLinkIDs, checkedLinkIDs;
3204     SMDS_VolumeTool volume;
3205     const SMDS_MeshNode* faceNodes[ 4 ];
3206
3207     const SMDS_MeshNode*    sideNode;
3208     const SMDS_MeshElement* sideElem;
3209     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
3210     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
3211     nBordIt = bordNodes.begin();
3212     nBordIt++;
3213     // border node position and border link direction to compare with
3214     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
3215     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
3216     // choose next side node by link direction or by closeness to
3217     // the current border node:
3218     bool searchByDir = ( *nBordIt != theBordLastNode );
3219     do {
3220       // find the next node on the Side 2
3221       sideNode = 0;
3222       double maxDot = -DBL_MAX, minDist = DBL_MAX;
3223       long linkID;
3224       checkedLinkIDs.clear();
3225       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
3226
3227       SMDS_ElemIteratorPtr invElemIt
3228         = prevSideNode->GetInverseElementIterator();
3229       while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
3230         const SMDS_MeshElement* elem = invElemIt->next();
3231         // prepare data for a loop on links, of a face or a volume
3232         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
3233         bool isVolume = volume.Set( elem );
3234         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
3235         if ( isVolume ) // --volume
3236           hasVolumes = true;
3237         else if ( nbNodes > 2 ) { // --face
3238           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
3239           SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3240           while ( nIt->more() ) {
3241             nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3242             if ( nodes[ iNode++ ] == prevSideNode )
3243               iPrevNode = iNode - 1;
3244           }
3245           // there are 2 links to check
3246           nbNodes = 2;
3247         }
3248         else // --edge
3249           continue;
3250         // loop on links, to be precise, on the second node of links
3251         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
3252           const SMDS_MeshNode* n = nodes[ iNode ];
3253           if ( isVolume ) {
3254             if ( !volume.IsLinked( n, prevSideNode ))
3255               continue;
3256           } else {
3257             if ( iNode ) // a node before prevSideNode
3258               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
3259             else         // a node after prevSideNode
3260               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
3261           }
3262           // check if this link was already used
3263           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
3264           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
3265           if (!isJustChecked &&
3266               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
3267             // test a link geometrically
3268             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
3269             bool linkIsBetter = false;
3270             double dot, dist;
3271             if ( searchByDir ) { // choose most co-directed link
3272               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
3273               linkIsBetter = ( dot > maxDot );
3274             }
3275             else { // choose link with the node closest to bordPos
3276               dist = ( nextXYZ - bordPos ).SquareModulus();
3277               linkIsBetter = ( dist < minDist );
3278             }
3279             if ( linkIsBetter ) {
3280               maxDot = dot;
3281               minDist = dist;
3282               linkID = iLink;
3283               sideNode = n;
3284               sideElem = elem;
3285             }
3286           }
3287         }
3288       } // loop on inverse elements of prevSideNode
3289
3290       if ( !sideNode ) {
3291         MESSAGE(" Cant find path by links of the Side 2 ");
3292         return SEW_BAD_SIDE_NODES;
3293       }
3294       sideNodes.push_back( sideNode );
3295       sideElems.push_back( sideElem );
3296       foundSideLinkIDs.insert ( linkID );
3297       prevSideNode = sideNode;
3298
3299       if ( *nBordIt == theBordLastNode )
3300         searchByDir = false;
3301       else {
3302         // find the next border link to compare with
3303         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
3304         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
3305         while ( *nBordIt != theBordLastNode && !searchByDir ) {
3306           prevBordNode = *nBordIt;
3307           nBordIt++;
3308           bordPos = nBordXYZ[ *nBordIt ];
3309           bordDir = bordPos - nBordXYZ[ prevBordNode ];
3310           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
3311         }
3312       }
3313     }
3314     while ( sideNode != theSideSecondNode );
3315
3316     if ( hasVolumes && sideNodes.size () != bordNodes.size() ) {
3317       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
3318       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
3319     }
3320   } // end nodes search on the side 2
3321
3322   // ============================
3323   // sew the border to the side 2
3324   // ============================
3325
3326   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
3327   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
3328
3329   TListOfListOfNodes nodeGroupsToMerge;
3330   if ( nbNodes[0] == nbNodes[1] ||
3331       ( theSideIsFreeBorder && !theSideThirdNode)) {
3332
3333     // all nodes are to be merged
3334
3335     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
3336          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
3337          nIt[0]++, nIt[1]++ )
3338     {
3339       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
3340       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep 
3341       nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
3342     }
3343   }
3344   else {
3345
3346     // insert new nodes into the border and the side to get equal nb of segments
3347
3348     // get normalized parameters of nodes on the borders
3349     double param[ 2 ][ maxNbNodes ];
3350     int iNode, iBord;
3351     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
3352       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
3353       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
3354       const SMDS_MeshNode* nPrev = *nIt;
3355       double bordLength = 0;
3356       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
3357         const SMDS_MeshNode* nCur = *nIt;
3358         gp_XYZ segment (nCur->X() - nPrev->X(),
3359                         nCur->Y() - nPrev->Y(),
3360                         nCur->Z() - nPrev->Z());
3361         double segmentLen = segment.Modulus();
3362         bordLength += segmentLen;
3363         param[ iBord ][ iNode ] = bordLength;
3364         nPrev = nCur;
3365       }
3366       // normalize within [0,1]
3367       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
3368         param[ iBord ][ iNode ] /= bordLength;
3369       }
3370     }
3371
3372     // loop on border segments
3373     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
3374     int i[ 2 ] = { 0, 0 };
3375     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
3376     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
3377
3378     TElemOfNodeListMap insertMap;
3379     TElemOfNodeListMap::iterator insertMapIt;
3380     // insertMap is
3381     // key:   elem to insert nodes into
3382     // value: 2 nodes to insert between + nodes to be inserted
3383     do {
3384       bool next[ 2 ] = { false, false };
3385
3386       // find min adjacent segment length after sewing
3387       double nextParam = 10., prevParam = 0;
3388       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
3389         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
3390           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
3391         if ( i[ iBord ] > 0 )
3392           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
3393       }
3394       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
3395       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
3396       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
3397           
3398       // choose to insert or to merge nodes
3399       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
3400       if ( Abs( du ) <= minSegLen * 0.2 ) {
3401         // merge
3402         // ------
3403         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
3404         const SMDS_MeshNode* n0 = *nIt[0];
3405         const SMDS_MeshNode* n1 = *nIt[1];
3406         nodeGroupsToMerge.back().push_back( n1 );
3407         nodeGroupsToMerge.back().push_back( n0 );
3408         // position of node of the border changes due to merge
3409         param[ 0 ][ i[0] ] += du;
3410         // move n1 for the sake of elem shape evaluation during insertion.
3411         // n1 will be removed by MergeNodes() anyway
3412         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
3413         next[0] = next[1] = true;
3414       }
3415       else {
3416         // insert
3417         // ------
3418         int intoBord = ( du < 0 ) ? 0 : 1;
3419         const SMDS_MeshElement* elem = *eIt[ intoBord ];
3420         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
3421         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
3422         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
3423         if ( intoBord == 1 ) {
3424           // move node of the border to be on a link of elem of the side
3425           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
3426           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
3427           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
3428           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
3429           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
3430         }
3431         insertMapIt = insertMap.find( elem );
3432         bool notFound = ( insertMapIt == insertMap.end() );
3433         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
3434         if ( otherLink ) {
3435           // insert into another link of the same element:
3436           // 1. perform insertion into the other link of the elem
3437           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
3438           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
3439           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
3440           InsertNodesIntoLink( elem, n12, n22, nodeList );
3441           // 2. perform insertion into the link of adjacent faces
3442           while (true) {
3443             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
3444             if ( adjElem )
3445               InsertNodesIntoLink( adjElem, n12, n22, nodeList );
3446             else
3447               break;
3448           }
3449           // 3. find an element appeared on n1 and n2 after the insertion
3450           insertMap.erase( elem );
3451           elem = findAdjacentFace( n1, n2, 0 );
3452         }
3453         if ( notFound || otherLink ) {
3454           // add element and nodes of the side into the insertMap
3455           insertMapIt = insertMap.insert
3456             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
3457           (*insertMapIt).second.push_back( n1 );
3458           (*insertMapIt).second.push_back( n2 );
3459         }
3460         // add node to be inserted into elem
3461         (*insertMapIt).second.push_back( nIns );
3462         next[ 1 - intoBord ] = true;
3463       }
3464
3465       // go to the next segment
3466       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
3467         if ( next[ iBord ] ) {
3468           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
3469             eIt[ iBord ]++;
3470           nPrev[ iBord ] = *nIt[ iBord ];
3471           nIt[ iBord ]++; i[ iBord ]++;
3472         }
3473       }
3474     }
3475     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
3476
3477     // perform insertion of nodes into elements
3478
3479     for (insertMapIt = insertMap.begin();
3480          insertMapIt != insertMap.end();
3481          insertMapIt++ )
3482     {
3483       const SMDS_MeshElement* elem = (*insertMapIt).first;
3484       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
3485       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
3486       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
3487
3488       InsertNodesIntoLink( elem, n1, n2, nodeList );
3489
3490       if ( !theSideIsFreeBorder ) {
3491         // look for and insert nodes into the faces adjacent to elem
3492         while (true) {
3493           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
3494           if ( adjElem )
3495             InsertNodesIntoLink( adjElem, n1, n2, nodeList );
3496           else
3497             break;
3498         }
3499       }
3500     }
3501
3502   } // end: insert new nodes
3503
3504   MergeNodes ( nodeGroupsToMerge );
3505
3506   return aResult;
3507 }
3508
3509 //=======================================================================
3510 //function : InsertNodesIntoLink
3511 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
3512 //           and theBetweenNode2 and split theElement
3513 //=======================================================================
3514
3515 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
3516                                            const SMDS_MeshNode*        theBetweenNode1,
3517                                            const SMDS_MeshNode*        theBetweenNode2,
3518                                            list<const SMDS_MeshNode*>& theNodesToInsert)
3519 {
3520   if ( theFace->GetType() != SMDSAbs_Face ) return;
3521
3522   // find indices of 2 link nodes and of the rest nodes
3523   int iNode = 0, il1, il2, i3, i4;
3524   il1 = il2 = i3 = i4 = -1;
3525   const SMDS_MeshNode* nodes[ 8 ];
3526   SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
3527   while ( nodeIt->more() ) {
3528     const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3529     if ( n == theBetweenNode1 )
3530       il1 = iNode;
3531     else if ( n == theBetweenNode2 )
3532       il2 = iNode;
3533     else if ( i3 < 0 )
3534       i3 = iNode;
3535     else
3536       i4 = iNode;
3537     nodes[ iNode++ ] = n;
3538   }
3539   if ( il1 < 0 || il2 < 0 || i3 < 0 )
3540     return ;
3541
3542   // arrange link nodes to go one after another regarding the face orientation
3543   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
3544   if ( reverse ) {
3545     iNode = il1;
3546     il1 = il2;
3547     il2 = iNode;
3548     theNodesToInsert.reverse();
3549   }
3550   // check that not link nodes of a quadrangles are in good order
3551   int nbFaceNodes = theFace->NbNodes();
3552   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
3553     iNode = i3;
3554     i3 = i4;
3555     i4 = iNode;
3556   } 
3557
3558   // put theNodesToInsert between theBetweenNode1 and theBetweenNode2
3559   int nbLinkNodes = 2 + theNodesToInsert.size();
3560   const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
3561   linkNodes[ 0 ] = nodes[ il1 ];
3562   linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
3563   list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
3564   for ( iNode = 1; nIt != theNodesToInsert.end(); nIt++ ) {
3565     linkNodes[ iNode++ ] = *nIt;
3566   }
3567   // decide how to split a quadrangle: compare possible variants
3568   // and choose which of splits to be a quadrangle
3569   int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
3570   if ( nbFaceNodes == 3 )
3571   {
3572     iBestQuad = nbSplits;
3573     i4 = i3;
3574   }
3575   else if ( nbFaceNodes == 4 )
3576   {
3577     SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
3578     double aBestRate = DBL_MAX;
3579     for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
3580       i1 = 0; i2 = 1;
3581       double aBadRate = 0;
3582       // evaluate elements quality
3583       for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
3584         if ( iSplit == iQuad ) {
3585           SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
3586                                  linkNodes[ i2++ ],
3587                                  nodes[ i3 ],
3588                                  nodes[ i4 ]);
3589           aBadRate += getBadRate( &quad, aCrit );
3590         }
3591         else {
3592           SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
3593                                  linkNodes[ i2++ ],
3594                                  nodes[ iSplit < iQuad ? i4 : i3 ]);
3595           aBadRate += getBadRate( &tria, aCrit );
3596         }
3597       }
3598       // choice
3599       if ( aBadRate < aBestRate ) {
3600         iBestQuad = iQuad;
3601         aBestRate = aBadRate;
3602       }
3603     }
3604   }
3605
3606   // create new elements
3607   SMESHDS_Mesh *aMesh = GetMeshDS();
3608   int aShapeId = FindShape( theFace );
3609   
3610   i1 = 0; i2 = 1;
3611   for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
3612     SMDS_MeshElement* newElem = 0;
3613     if ( iSplit == iBestQuad )
3614       newElem = aMesh->AddFace (linkNodes[ i1++ ],
3615                                 linkNodes[ i2++ ],
3616                                 nodes[ i3 ],
3617                                 nodes[ i4 ]);
3618     else
3619       newElem = aMesh->AddFace (linkNodes[ i1++ ],
3620                                 linkNodes[ i2++ ],
3621                                 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
3622     if ( aShapeId && newElem )
3623       aMesh->SetMeshElementOnShape( newElem, aShapeId );
3624   }
3625
3626   // change nodes of theFace
3627   const SMDS_MeshNode* newNodes[ 4 ];
3628   newNodes[ 0 ] = linkNodes[ i1 ];
3629   newNodes[ 1 ] = linkNodes[ i2 ];
3630   newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
3631   newNodes[ 3 ] = nodes[ i4 ];
3632   aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
3633 }
3634
3635 //=======================================================================
3636 //function : SewSideElements
3637 //purpose  : 
3638 //=======================================================================
3639
3640 SMESH_MeshEditor::Sew_Error
3641   SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
3642                                      set<const SMDS_MeshElement*>& theSide2,
3643                                      const SMDS_MeshNode*          theFirstNode1,
3644                                      const SMDS_MeshNode*          theFirstNode2,
3645                                      const SMDS_MeshNode*          theSecondNode1,
3646                                      const SMDS_MeshNode*          theSecondNode2)
3647 {
3648   MESSAGE ("::::SewSideElements()");
3649   if ( theSide1.size() != theSide2.size() )
3650     return SEW_DIFF_NB_OF_ELEMENTS;
3651
3652   Sew_Error aResult = SEW_OK;
3653   // Algo:
3654   // 1. Build set of faces representing each side
3655   // 2. Find which nodes of the side 1 to merge with ones on the side 2
3656   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
3657
3658   // =======================================================================
3659   // 1. Build set of faces representing each side:
3660   // =======================================================================
3661   // a. build set of nodes belonging to faces
3662   // b. complete set of faces: find missing fices whose nodes are in set of nodes
3663   // c. create temporary faces representing side of volumes if correspondent
3664   //    face does not exist
3665
3666   SMESHDS_Mesh* aMesh = GetMeshDS();
3667   SMDS_Mesh aTmpFacesMesh;
3668   set<const SMDS_MeshElement*> faceSet1, faceSet2;
3669   set<const SMDS_MeshElement*> volSet1,  volSet2;
3670   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
3671   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
3672   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
3673   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
3674   set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
3675   int iSide, iFace, iNode;
3676
3677   for ( iSide = 0; iSide < 2; iSide++ ) {
3678     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
3679     set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
3680     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3681     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
3682     set<const SMDS_MeshElement*>::iterator vIt, eIt;
3683     set<const SMDS_MeshNode*>::iterator    nIt;
3684
3685   // -----------------------------------------------------------
3686   // 1a. Collect nodes of existing faces
3687   //     and build set of face nodes in order to detect missing
3688   //     faces corresponing to sides of volumes
3689   // -----------------------------------------------------------
3690
3691     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
3692
3693     // loop on the given element of a side
3694     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
3695       const SMDS_MeshElement* elem = *eIt;
3696       if ( elem->GetType() == SMDSAbs_Face ) {
3697         faceSet->insert( elem );
3698         set <const SMDS_MeshNode*> faceNodeSet;
3699         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3700         while ( nodeIt->more() ) {
3701           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3702           nodeSet->insert( n );
3703           faceNodeSet.insert( n );
3704         }
3705         setOfFaceNodeSet.insert( faceNodeSet );
3706       }
3707       else if ( elem->GetType() == SMDSAbs_Volume )
3708         volSet->insert( elem );
3709     }
3710     // ------------------------------------------------------------------------------
3711     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
3712     // ------------------------------------------------------------------------------
3713
3714     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3715       SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3716       while ( fIt->more() ) { // loop on faces sharing a node
3717         const SMDS_MeshElement* f = fIt->next();
3718         if ( faceSet->find( f ) == faceSet->end() ) {
3719           // check if all nodes are in nodeSet and
3720           // complete setOfFaceNodeSet if they are
3721           set <const SMDS_MeshNode*> faceNodeSet;
3722           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3723           bool allInSet = true;
3724           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3725             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3726             if ( nodeSet->find( n ) == nodeSet->end() )
3727               allInSet = false;
3728             else
3729               faceNodeSet.insert( n );
3730           }
3731           if ( allInSet ) {
3732             faceSet->insert( f );
3733             setOfFaceNodeSet.insert( faceNodeSet );
3734           }
3735         }
3736       }
3737     }
3738
3739     // -------------------------------------------------------------------------
3740     // 1c. Create temporary faces representing sides of volumes if correspondent
3741     //     face does not exist
3742     // -------------------------------------------------------------------------
3743
3744     if ( !volSet->empty() )
3745     {
3746       //int nodeSetSize = nodeSet->size();
3747       
3748       // loop on given volumes
3749       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
3750         SMDS_VolumeTool vol (*vIt);
3751         // loop on volume faces: find free faces
3752         // --------------------------------------
3753         list<const SMDS_MeshElement* > freeFaceList;
3754         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
3755           if ( !vol.IsFreeFace( iFace ))
3756             continue;
3757           // check if there is already a face with same nodes in a face set
3758           const SMDS_MeshElement* aFreeFace = 0;
3759           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
3760           int nbNodes = vol.NbFaceNodes( iFace );
3761           set <const SMDS_MeshNode*> faceNodeSet;
3762           vol.GetFaceNodes( iFace, faceNodeSet );
3763           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
3764           if ( isNewFace ) {
3765             // no such a face is given but it still can exist, check it
3766             if ( nbNodes == 3 )
3767               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
3768             else
3769               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3770           }
3771           if ( !aFreeFace ) {
3772             // create a temporary face
3773             if ( nbNodes == 3 )
3774               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
3775             else
3776               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3777           }
3778           if ( aFreeFace )
3779             freeFaceList.push_back( aFreeFace );
3780
3781         } // loop on faces of a volume
3782
3783         // choose one of several free faces
3784         // --------------------------------------
3785         if ( freeFaceList.size() > 1 ) {
3786           // choose a face having max nb of nodes shared by other elems of a side
3787           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
3788           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
3789           while ( fIt != freeFaceList.end() ) { // loop on free faces
3790             int nbSharedNodes = 0;
3791             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3792             while ( nodeIt->more() ) { // loop on free face nodes
3793               const SMDS_MeshNode* n =
3794                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3795               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
3796               while ( invElemIt->more() ) {
3797                 const SMDS_MeshElement* e = invElemIt->next();
3798                 if ( faceSet->find( e ) != faceSet->end() )
3799                   nbSharedNodes++;
3800                 if ( elemSet->find( e ) != elemSet->end() )
3801                   nbSharedNodes++;
3802               }
3803             }
3804             if ( nbSharedNodes >= maxNbNodes ) {
3805               maxNbNodes = nbSharedNodes;
3806               fIt++;
3807             }
3808             else 
3809               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
3810           }
3811           if ( freeFaceList.size() > 1 )
3812           {
3813             // could not choose one face, use another way
3814             // choose a face most close to the bary center of the opposite side
3815             gp_XYZ aBC( 0., 0., 0. );
3816             set <const SMDS_MeshNode*> addedNodes;
3817             set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
3818             eIt = elemSet2->begin();
3819             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
3820               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
3821               while ( nodeIt->more() ) { // loop on free face nodes
3822                 const SMDS_MeshNode* n =
3823                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3824                 if ( addedNodes.insert( n ).second )
3825                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
3826               }
3827             }
3828             aBC /= addedNodes.size();
3829             double minDist = DBL_MAX;
3830             fIt = freeFaceList.begin();
3831             while ( fIt != freeFaceList.end() ) { // loop on free faces
3832               double dist = 0;
3833               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3834               while ( nodeIt->more() ) { // loop on free face nodes
3835                 const SMDS_MeshNode* n =
3836                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3837                 gp_XYZ p( n->X(),n->Y(),n->Z() );
3838                 dist += ( aBC - p ).SquareModulus();
3839               }
3840               if ( dist < minDist ) {
3841                 minDist = dist;
3842                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
3843               }
3844               else
3845                 fIt = freeFaceList.erase( fIt++ );
3846             }
3847           }
3848         } // choose one of several free faces of a volume
3849
3850         if ( freeFaceList.size() == 1 ) {
3851           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
3852           faceSet->insert( aFreeFace );
3853           // complete a node set with nodes of a found free face
3854 //           for ( iNode = 0; iNode < ; iNode++ )
3855 //             nodeSet->insert( fNodes[ iNode ] );
3856         }
3857
3858       } // loop on volumes of a side
3859
3860 //       // complete a set of faces if new nodes in a nodeSet appeared
3861 //       // ----------------------------------------------------------
3862 //       if ( nodeSetSize != nodeSet->size() ) {
3863 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3864 //           SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3865 //           while ( fIt->more() ) { // loop on faces sharing a node
3866 //             const SMDS_MeshElement* f = fIt->next();
3867 //             if ( faceSet->find( f ) == faceSet->end() ) {
3868 //               // check if all nodes are in nodeSet and
3869 //               // complete setOfFaceNodeSet if they are
3870 //               set <const SMDS_MeshNode*> faceNodeSet;
3871 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3872 //               bool allInSet = true;
3873 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3874 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3875 //                 if ( nodeSet->find( n ) == nodeSet->end() )
3876 //                   allInSet = false;
3877 //                 else
3878 //                   faceNodeSet.insert( n );
3879 //               }
3880 //               if ( allInSet ) {
3881 //                 faceSet->insert( f );
3882 //                 setOfFaceNodeSet.insert( faceNodeSet );
3883 //               }
3884 //             }
3885 //           }
3886 //         }
3887 //       }
3888     } // Create temporary faces, if there are volumes given
3889   } // loop on sides
3890
3891   if ( faceSet1.size() != faceSet2.size() ) {
3892     // delete temporary faces: they are in reverseElements of actual nodes
3893     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
3894     while ( tmpFaceIt->more() )
3895       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
3896     MESSAGE("Diff nb of faces");
3897     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3898   }
3899
3900   // ============================================================
3901   // 2. Find nodes to merge:
3902   //              bind a node to remove to a node to put instead
3903   // ============================================================
3904
3905   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
3906   if ( theFirstNode1 != theFirstNode2 )
3907     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
3908   if ( theSecondNode1 != theSecondNode2 )
3909     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
3910
3911   LinkID_Gen aLinkID_Gen( GetMeshDS() );
3912   set< long > linkIdSet; // links to process
3913   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
3914
3915   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
3916   list< TPairOfNodes > linkList[2];
3917   linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
3918   linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
3919   // loop on links in linkList; find faces by links and append links
3920   // of the found faces to linkList
3921   list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
3922   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
3923   {
3924     TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
3925     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
3926     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
3927       continue;
3928
3929     // by links, find faces in the face sets,
3930     // and find indices of link nodes in the found faces;
3931     // in a face set, there is only one or no face sharing a link
3932     // ---------------------------------------------------------------
3933
3934     const SMDS_MeshElement* face[] = { 0, 0 };
3935     const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
3936     const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
3937     int iLinkNode[2][2];
3938     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
3939       const SMDS_MeshNode* n1 = link[iSide].first;
3940       const SMDS_MeshNode* n2 = link[iSide].second;
3941       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3942       set< const SMDS_MeshElement* > fMap;
3943       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
3944         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
3945         SMDS_ElemIteratorPtr fIt = n->facesIterator();
3946         while ( fIt->more() ) { // loop on faces sharing a node
3947           const SMDS_MeshElement* f = fIt->next();
3948           if (faceSet->find( f ) != faceSet->end() && // f is in face set
3949               ! fMap.insert( f ).second ) // f encounters twice
3950           {
3951             if ( face[ iSide ] ) {
3952               MESSAGE( "2 faces per link " );
3953               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
3954               break;
3955             }
3956             face[ iSide ] = f;
3957             faceSet->erase( f );
3958             // get face nodes and find ones of a link
3959             iNode = 0;
3960             SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3961             while ( nIt->more() ) {
3962               const SMDS_MeshNode* n =
3963                 static_cast<const SMDS_MeshNode*>( nIt->next() );
3964               if ( n == n1 )
3965                 iLinkNode[ iSide ][ 0 ] = iNode;
3966               else if ( n == n2 )
3967                 iLinkNode[ iSide ][ 1 ] = iNode;
3968               else if ( notLinkNodes[ iSide ][ 0 ] )
3969                 notLinkNodes[ iSide ][ 1 ] = n;
3970               else
3971                 notLinkNodes[ iSide ][ 0 ] = n;
3972               faceNodes[ iSide ][ iNode++ ] = n;
3973             }
3974             faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
3975           }
3976         }
3977       }
3978     }
3979     // check similarity of elements of the sides
3980     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
3981       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
3982       if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
3983         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
3984       else
3985         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3986       break; // do not return because it s necessary to remove tmp faces
3987     }
3988
3989     // set nodes to merge
3990     // -------------------
3991
3992     if ( face[0] && face[1] )
3993     {
3994       int nbNodes = face[0]->NbNodes();
3995       if ( nbNodes != face[1]->NbNodes() ) {
3996         MESSAGE("Diff nb of face nodes");
3997         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3998         break; // do not return because it s necessary to remove tmp faces
3999       }
4000       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4001       if ( nbNodes == 3 )
4002         nReplaceMap.insert( TNodeNodeMap::value_type
4003                            ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4004       else {
4005         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4006           // analyse link orientation in faces
4007           int i1 = iLinkNode[ iSide ][ 0 ];
4008           int i2 = iLinkNode[ iSide ][ 1 ];
4009           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4010           // if notLinkNodes are the first and the last ones, then
4011           // their order does not correspond to the link orientation
4012           if (( i1 == 1 && i2 == 2 ) ||
4013               ( i1 == 2 && i2 == 1 ))
4014             reverse[ iSide ] = !reverse[ iSide ];
4015         }
4016         if ( reverse[0] == reverse[1] ) {
4017           nReplaceMap.insert( TNodeNodeMap::value_type
4018                              ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4019           nReplaceMap.insert( TNodeNodeMap::value_type
4020                              ( notLinkNodes[0][1], notLinkNodes[1][1] ));
4021         }
4022         else {
4023           nReplaceMap.insert( TNodeNodeMap::value_type
4024                              ( notLinkNodes[0][0], notLinkNodes[1][1] ));
4025           nReplaceMap.insert( TNodeNodeMap::value_type
4026                              ( notLinkNodes[0][1], notLinkNodes[1][0] ));
4027         }
4028       }
4029
4030       // add other links of the faces to linkList
4031       // -----------------------------------------
4032
4033       const SMDS_MeshNode** nodes = faceNodes[ 0 ];
4034       for ( iNode = 0; iNode < nbNodes; iNode++ )
4035       {
4036         linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
4037         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
4038         if ( !iter_isnew.second ) { // already in a set: no need to process
4039           linkIdSet.erase( iter_isnew.first );
4040         }
4041         else // new in set == encountered for the first time: add
4042         {
4043           const SMDS_MeshNode* n1 = nodes[ iNode ];
4044           const SMDS_MeshNode* n2 = nodes[ iNode + 1];
4045           linkList[0].push_back ( TPairOfNodes( n1, n2 ));
4046           linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
4047         }
4048       }
4049     } // 2 faces found
4050   } // loop on link lists
4051
4052   if ( aResult == SEW_OK &&
4053       ( linkIt[0] != linkList[0].end() ||
4054        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
4055     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
4056             " " << (faceSetPtr[1]->empty()));
4057     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4058   }
4059
4060   // ====================================================================
4061   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4062   // ====================================================================
4063
4064   // delete temporary faces: they are in reverseElements of actual nodes
4065   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4066   while ( tmpFaceIt->more() )
4067     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4068
4069   if ( aResult != SEW_OK)
4070     return aResult;
4071
4072   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
4073   // loop on nodes replacement map
4074   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
4075   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
4076     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
4077     {
4078       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
4079       nodeIDsToRemove.push_back( nToRemove->GetID() );
4080       // loop on elements sharing nToRemove
4081       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
4082       while ( invElemIt->more() ) {
4083         const SMDS_MeshElement* e = invElemIt->next();
4084         // get a new suite of nodes: make replacement
4085         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
4086         const SMDS_MeshNode* nodes[ 8 ];
4087         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4088         while ( nIt->more() ) {
4089           const SMDS_MeshNode* n =
4090             static_cast<const SMDS_MeshNode*>( nIt->next() );
4091           nnIt = nReplaceMap.find( n );
4092           if ( nnIt != nReplaceMap.end() ) {
4093             nbReplaced++;
4094             n = (*nnIt).second;
4095           }
4096           nodes[ i++ ] = n;
4097         }
4098         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
4099         //         elemIDsToRemove.push_back( e->GetID() );
4100         //       else
4101         if ( nbReplaced )
4102           aMesh->ChangeElementNodes( e, nodes, nbNodes );
4103       }
4104   }
4105
4106   Remove( nodeIDsToRemove, true );
4107
4108   return aResult;
4109 }