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