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