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