Salome HOME
0019957: EDF 785 SMESH: Convert Quadratic and Group on GEOM
[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.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 // File      : SMESH_MeshEditor.cxx
25 // Created   : Mon Apr 12 16:10:22 2004
26 // Author    : Edward AGAPOV (eap)
27
28
29 #include "SMESH_MeshEditor.hxx"
30
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
37 #include "SMDS_QuadraticFaceOfNodes.hxx"
38 #include "SMDS_MeshGroup.hxx"
39
40 #include "SMESHDS_Group.hxx"
41 #include "SMESHDS_Mesh.hxx"
42
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_ControlsDef.hxx"
45 #include "SMESH_MesherHelper.hxx"
46 #include "SMESH_OctreeNode.hxx"
47 #include "SMESH_Group.hxx"
48
49 #include "utilities.h"
50
51 #include <BRep_Tool.hxx>
52 #include <ElCLib.hxx>
53 #include <Extrema_GenExtPS.hxx>
54 #include <Extrema_POnSurf.hxx>
55 #include <Geom2d_Curve.hxx>
56 #include <GeomAdaptor_Surface.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Surface.hxx>
59 #include <TColStd_ListOfInteger.hxx>
60 #include <TopExp.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopTools_ListIteratorOfListOfShape.hxx>
63 #include <TopTools_ListOfShape.hxx>
64 #include <TopoDS.hxx>
65 #include <TopoDS_Face.hxx>
66 #include <gp.hxx>
67 #include <gp_Ax1.hxx>
68 #include <gp_Dir.hxx>
69 #include <gp_Lin.hxx>
70 #include <gp_Pln.hxx>
71 #include <gp_Trsf.hxx>
72 #include <gp_Vec.hxx>
73 #include <gp_XY.hxx>
74 #include <gp_XYZ.hxx>
75 #include <math.h>
76
77 #include <map>
78 #include <set>
79
80 #define cast2Node(elem) static_cast<const SMDS_MeshNode*>( elem )
81
82 using namespace std;
83 using namespace SMESH::Controls;
84
85 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> >    TElemOfNodeListMap;
86 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
87 //typedef map<const SMDS_MeshNode*, vector<const SMDS_MeshNode*> >     TNodeOfNodeVecMap;
88 //typedef TNodeOfNodeVecMap::iterator                                  TNodeOfNodeVecMapItr;
89 //typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeVecMapItr> >  TElemOfVecOfMapNodesMap;
90
91 struct TNodeXYZ : public gp_XYZ {
92   TNodeXYZ( const SMDS_MeshNode* n ):gp_XYZ( n->X(), n->Y(), n->Z() ) {}
93 };
94
95 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > NLink;
96
97 //=======================================================================
98 /*!
99  * \brief A sorted pair of nodes
100  */
101 //=======================================================================
102
103 struct TLink: public NLink
104 {
105   TLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ):NLink( n1, n2 )
106   { if ( n1->GetID() < n2->GetID() ) std::swap( first, second ); }
107   TLink(const NLink& link ):NLink( link )
108   { if ( first->GetID() < second->GetID() ) std::swap( first, second ); }
109 };
110
111 //=======================================================================
112 //function : SMESH_MeshEditor
113 //purpose  :
114 //=======================================================================
115
116 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh )
117   :myMesh( theMesh ) // theMesh may be NULL
118 {
119 }
120
121 //=======================================================================
122 /*!
123  * \brief Add element
124  */
125 //=======================================================================
126
127 SMDS_MeshElement*
128 SMESH_MeshEditor::AddElement(const vector<const SMDS_MeshNode*> & node,
129                              const SMDSAbs_ElementType            type,
130                              const bool                           isPoly,
131                              const int                            ID)
132 {
133   SMDS_MeshElement* e = 0;
134   int nbnode = node.size();
135   SMESHDS_Mesh* mesh = GetMeshDS();
136   switch ( type ) {
137   case SMDSAbs_Edge:
138     if ( nbnode == 2 )
139       if ( ID ) e = mesh->AddEdgeWithID(node[0], node[1], ID);
140       else      e = mesh->AddEdge      (node[0], node[1] );
141     else if ( nbnode == 3 )
142       if ( ID ) e = mesh->AddEdgeWithID(node[0], node[1], node[2], ID);
143       else      e = mesh->AddEdge      (node[0], node[1], node[2] );
144     break;
145   case SMDSAbs_Face:
146     if ( !isPoly ) {
147       if      (nbnode == 3)
148         if ( ID ) e = mesh->AddFaceWithID(node[0], node[1], node[2], ID);
149         else      e = mesh->AddFace      (node[0], node[1], node[2] );
150       else if (nbnode == 4) 
151         if ( ID ) e = mesh->AddFaceWithID(node[0], node[1], node[2], node[3], ID);
152         else      e = mesh->AddFace      (node[0], node[1], node[2], node[3] );
153       else if (nbnode == 6)
154         if ( ID ) e = mesh->AddFaceWithID(node[0], node[1], node[2], node[3],
155                                           node[4], node[5], ID);
156         else      e = mesh->AddFace      (node[0], node[1], node[2], node[3],
157                                           node[4], node[5] );
158       else if (nbnode == 8)
159         if ( ID ) e = mesh->AddFaceWithID(node[0], node[1], node[2], node[3],
160                                           node[4], node[5], node[6], node[7], ID);
161         else      e = mesh->AddFace      (node[0], node[1], node[2], node[3],
162                                           node[4], node[5], node[6], node[7] );
163     } else {
164       if ( ID ) e = mesh->AddPolygonalFaceWithID(node, ID);
165       else      e = mesh->AddPolygonalFace      (node    );
166     }
167     break;
168   case SMDSAbs_Volume:
169     if ( !isPoly ) {
170       if      (nbnode == 4)
171         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3], ID);
172         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3] );
173       else if (nbnode == 5)
174         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3],
175                                             node[4], ID);
176         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3],
177                                             node[4] );
178       else if (nbnode == 6)
179         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3],
180                                             node[4], node[5], ID);
181         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3],
182                                             node[4], node[5] );
183       else if (nbnode == 8)
184         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3],
185                                             node[4], node[5], node[6], node[7], ID);
186         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3],
187                                             node[4], node[5], node[6], node[7] );
188       else if (nbnode == 10)
189         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3],
190                                             node[4], node[5], node[6], node[7],
191                                             node[8], node[9], ID);
192         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3],
193                                             node[4], node[5], node[6], node[7],
194                                             node[8], node[9] );
195       else if (nbnode == 13)
196         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3],
197                                             node[4], node[5], node[6], node[7],
198                                             node[8], node[9], node[10],node[11],
199                                             node[12],ID);
200         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3],
201                                             node[4], node[5], node[6], node[7],
202                                             node[8], node[9], node[10],node[11],
203                                             node[12] );
204       else if (nbnode == 15)
205         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3],
206                                             node[4], node[5], node[6], node[7],
207                                             node[8], node[9], node[10],node[11],
208                                             node[12],node[13],node[14],ID);
209         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3],
210                                             node[4], node[5], node[6], node[7],
211                                             node[8], node[9], node[10],node[11],
212                                             node[12],node[13],node[14] );
213       else if (nbnode == 20)
214         if ( ID ) e = mesh->AddVolumeWithID(node[0], node[1], node[2], node[3],
215                                             node[4], node[5], node[6], node[7],
216                                             node[8], node[9], node[10],node[11],
217                                             node[12],node[13],node[14],node[15],
218                                             node[16],node[17],node[18],node[19],ID);
219         else      e = mesh->AddVolume      (node[0], node[1], node[2], node[3],
220                                             node[4], node[5], node[6], node[7],
221                                             node[8], node[9], node[10],node[11],
222                                             node[12],node[13],node[14],node[15],
223                                             node[16],node[17],node[18],node[19] );
224     }
225   }
226   return e;
227 }
228
229 //=======================================================================
230 /*!
231  * \brief Add element
232  */
233 //=======================================================================
234
235 SMDS_MeshElement* SMESH_MeshEditor::AddElement(const vector<int> &       nodeIDs,
236                                                const SMDSAbs_ElementType type,
237                                                const bool                isPoly,
238                                                const int                 ID)
239 {
240   vector<const SMDS_MeshNode*> nodes;
241   nodes.reserve( nodeIDs.size() );
242   vector<int>::const_iterator id = nodeIDs.begin();
243   while ( id != nodeIDs.end() ) {
244     if ( const SMDS_MeshNode* node = GetMeshDS()->FindNode( *id++ ))
245       nodes.push_back( node );
246     else
247       return 0;
248   }
249   return AddElement( nodes, type, isPoly, ID );
250 }
251
252 //=======================================================================
253 //function : Remove
254 //purpose  : Remove a node or an element.
255 //           Modify a compute state of sub-meshes which become empty
256 //=======================================================================
257
258 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
259                                const bool         isNodes )
260 {
261   myLastCreatedElems.Clear();
262   myLastCreatedNodes.Clear();
263
264   SMESHDS_Mesh* aMesh = GetMeshDS();
265   set< SMESH_subMesh *> smmap;
266
267   list<int>::const_iterator it = theIDs.begin();
268   for ( ; it != theIDs.end(); it++ ) {
269     const SMDS_MeshElement * elem;
270     if ( isNodes )
271       elem = aMesh->FindNode( *it );
272     else
273       elem = aMesh->FindElement( *it );
274     if ( !elem )
275       continue;
276
277     // Notify VERTEX sub-meshes about modification
278     if ( isNodes ) {
279       const SMDS_MeshNode* node = cast2Node( elem );
280       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
281         if ( int aShapeID = node->GetPosition()->GetShapeId() )
282           if ( SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShapeID ) )
283             smmap.insert( sm );
284     }
285     // Find sub-meshes to notify about modification
286 //     SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
287 //     while ( nodeIt->more() ) {
288 //       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
289 //       const SMDS_PositionPtr& aPosition = node->GetPosition();
290 //       if ( aPosition.get() ) {
291 //         if ( int aShapeID = aPosition->GetShapeId() ) {
292 //           if ( SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShapeID ) )
293 //             smmap.insert( sm );
294 //         }
295 //       }
296 //     }
297
298     // Do remove
299     if ( isNodes )
300       aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
301     else
302       aMesh->RemoveElement( elem );
303   }
304
305   // Notify sub-meshes about modification
306   if ( !smmap.empty() ) {
307     set< SMESH_subMesh *>::iterator smIt;
308     for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
309       (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
310   }
311
312 //   // Check if the whole mesh becomes empty
313 //   if ( SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( 1 ) )
314 //     sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
315
316   return true;
317 }
318
319 //=======================================================================
320 //function : FindShape
321 //purpose  : Return an index of the shape theElem is on
322 //           or zero if a shape not found
323 //=======================================================================
324
325 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
326 {
327   myLastCreatedElems.Clear();
328   myLastCreatedNodes.Clear();
329
330   SMESHDS_Mesh * aMesh = GetMeshDS();
331   if ( aMesh->ShapeToMesh().IsNull() )
332     return 0;
333
334   if ( theElem->GetType() == SMDSAbs_Node ) {
335     const SMDS_PositionPtr& aPosition =
336       static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
337     if ( aPosition.get() )
338       return aPosition->GetShapeId();
339     else
340       return 0;
341   }
342
343   TopoDS_Shape aShape; // the shape a node is on
344   SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
345   while ( nodeIt->more() ) {
346     const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
347     const SMDS_PositionPtr& aPosition = node->GetPosition();
348     if ( aPosition.get() ) {
349       int aShapeID = aPosition->GetShapeId();
350       SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
351       if ( sm ) {
352         if ( sm->Contains( theElem ))
353           return aShapeID;
354         if ( aShape.IsNull() )
355           aShape = aMesh->IndexToShape( aShapeID );
356       }
357       else {
358         //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
359       }
360     }
361   }
362
363   // None of nodes is on a proper shape,
364   // find the shape among ancestors of aShape on which a node is
365   if ( aShape.IsNull() ) {
366     //MESSAGE ("::FindShape() - NONE node is on shape")
367     return 0;
368   }
369   TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
370   for ( ; ancIt.More(); ancIt.Next() ) {
371     SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
372     if ( sm && sm->Contains( theElem ))
373       return aMesh->ShapeToIndex( ancIt.Value() );
374   }
375
376   //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
377   return 0;
378 }
379
380 //=======================================================================
381 //function : IsMedium
382 //purpose  :
383 //=======================================================================
384
385 bool SMESH_MeshEditor::IsMedium(const SMDS_MeshNode*      node,
386                                 const SMDSAbs_ElementType typeToCheck)
387 {
388   bool isMedium = false;
389   SMDS_ElemIteratorPtr it = node->GetInverseElementIterator(typeToCheck);
390   while (it->more() && !isMedium ) {
391     const SMDS_MeshElement* elem = it->next();
392     isMedium = elem->IsMediumNode(node);
393   }
394   return isMedium;
395 }
396
397 //=======================================================================
398 //function : ShiftNodesQuadTria
399 //purpose  : auxilary
400 //           Shift nodes in the array corresponded to quadratic triangle
401 //           example: (0,1,2,3,4,5) -> (1,2,0,4,5,3)
402 //=======================================================================
403 static void ShiftNodesQuadTria(const SMDS_MeshNode* aNodes[])
404 {
405   const SMDS_MeshNode* nd1 = aNodes[0];
406   aNodes[0] = aNodes[1];
407   aNodes[1] = aNodes[2];
408   aNodes[2] = nd1;
409   const SMDS_MeshNode* nd2 = aNodes[3];
410   aNodes[3] = aNodes[4];
411   aNodes[4] = aNodes[5];
412   aNodes[5] = nd2;
413 }
414
415 //=======================================================================
416 //function : GetNodesFromTwoTria
417 //purpose  : auxilary
418 //           Shift nodes in the array corresponded to quadratic triangle
419 //           example: (0,1,2,3,4,5) -> (1,2,0,4,5,3)
420 //=======================================================================
421 static bool GetNodesFromTwoTria(const SMDS_MeshElement * theTria1,
422                                 const SMDS_MeshElement * theTria2,
423                                 const SMDS_MeshNode* N1[],
424                                 const SMDS_MeshNode* N2[])
425 {
426   SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
427   int i=0;
428   while(i<6) {
429     N1[i] = static_cast<const SMDS_MeshNode*>( it->next() );
430     i++;
431   }
432   if(it->more()) return false;
433   it = theTria2->nodesIterator();
434   i=0;
435   while(i<6) {
436     N2[i] = static_cast<const SMDS_MeshNode*>( it->next() );
437     i++;
438   }
439   if(it->more()) return false;
440
441   int sames[3] = {-1,-1,-1};
442   int nbsames = 0;
443   int j;
444   for(i=0; i<3; i++) {
445     for(j=0; j<3; j++) {
446       if(N1[i]==N2[j]) {
447         sames[i] = j;
448         nbsames++;
449         break;
450       }
451     }
452   }
453   if(nbsames!=2) return false;
454   if(sames[0]>-1) {
455     ShiftNodesQuadTria(N1);
456     if(sames[1]>-1) {
457       ShiftNodesQuadTria(N1);
458     }
459   }
460   i = sames[0] + sames[1] + sames[2];
461   for(; i<2; i++) {
462     ShiftNodesQuadTria(N2);
463   }
464   // now we receive following N1 and N2 (using numeration as above image)
465   // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6)
466   // i.e. first nodes from both arrays determ new diagonal
467   return true;
468 }
469
470 //=======================================================================
471 //function : InverseDiag
472 //purpose  : Replace two neighbour triangles with ones built on the same 4 nodes
473 //           but having other common link.
474 //           Return False if args are improper
475 //=======================================================================
476
477 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
478                                     const SMDS_MeshElement * theTria2 )
479 {
480   myLastCreatedElems.Clear();
481   myLastCreatedNodes.Clear();
482
483   if (!theTria1 || !theTria2)
484     return false;
485
486   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
487   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
488   if (F1 && F2) {
489
490     //  1 +--+ A  theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
491     //    | /|    theTria2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |
492     //    |/ |                                         | \|
493     //  B +--+ 2                                     B +--+ 2
494
495     // put nodes in array and find out indices of the same ones
496     const SMDS_MeshNode* aNodes [6];
497     int sameInd [] = { 0, 0, 0, 0, 0, 0 };
498     int i = 0;
499     SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
500     while ( it->more() ) {
501       aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
502
503       if ( i > 2 ) // theTria2
504         // find same node of theTria1
505         for ( int j = 0; j < 3; j++ )
506           if ( aNodes[ i ] == aNodes[ j ]) {
507             sameInd[ j ] = i;
508             sameInd[ i ] = j;
509             break;
510           }
511       // next
512       i++;
513       if ( i == 3 ) {
514         if ( it->more() )
515           return false; // theTria1 is not a triangle
516         it = theTria2->nodesIterator();
517       }
518       if ( i == 6 && it->more() )
519         return false; // theTria2 is not a triangle
520     }
521
522     // find indices of 1,2 and of A,B in theTria1
523     int iA = 0, iB = 0, i1 = 0, i2 = 0;
524     for ( i = 0; i < 6; i++ ) {
525       if ( sameInd [ i ] == 0 )
526         if ( i < 3 ) i1 = i;
527         else         i2 = i;
528       else if (i < 3)
529         if ( iA ) iB = i;
530         else      iA = i;
531     }
532     // nodes 1 and 2 should not be the same
533     if ( aNodes[ i1 ] == aNodes[ i2 ] )
534       return false;
535
536     // theTria1: A->2
537     aNodes[ iA ] = aNodes[ i2 ];
538     // theTria2: B->1
539     aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
540
541     //MESSAGE( theTria1 << theTria2 );
542
543     GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
544     GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
545
546     //MESSAGE( theTria1 << theTria2 );
547
548     return true;
549
550   } // end if(F1 && F2)
551
552   // check case of quadratic faces
553   const SMDS_QuadraticFaceOfNodes* QF1 =
554     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (theTria1);
555   if(!QF1) return false;
556   const SMDS_QuadraticFaceOfNodes* QF2 =
557     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (theTria2);
558   if(!QF2) return false;
559
560   //       5
561   //  1 +--+--+ 2  theTria1: (1 2 4 5 9 7) or (2 4 1 9 7 5) or (4 1 2 7 5 9)
562   //    |    /|    theTria2: (2 3 4 6 8 9) or (3 4 2 8 9 6) or (4 2 3 9 6 8)
563   //    |   / |
564   //  7 +  +  + 6
565   //    | /9  |
566   //    |/    |
567   //  4 +--+--+ 3
568   //       8
569
570   const SMDS_MeshNode* N1 [6];
571   const SMDS_MeshNode* N2 [6];
572   if(!GetNodesFromTwoTria(theTria1,theTria2,N1,N2))
573     return false;
574   // now we receive following N1 and N2 (using numeration as above image)
575   // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6)
576   // i.e. first nodes from both arrays determ new diagonal
577
578   const SMDS_MeshNode* N1new [6];
579   const SMDS_MeshNode* N2new [6];
580   N1new[0] = N1[0];
581   N1new[1] = N2[0];
582   N1new[2] = N2[1];
583   N1new[3] = N1[4];
584   N1new[4] = N2[3];
585   N1new[5] = N1[5];
586   N2new[0] = N1[0];
587   N2new[1] = N1[1];
588   N2new[2] = N2[0];
589   N2new[3] = N1[3];
590   N2new[4] = N2[5];
591   N2new[5] = N1[4];
592   // replaces nodes in faces
593   GetMeshDS()->ChangeElementNodes( theTria1, N1new, 6 );
594   GetMeshDS()->ChangeElementNodes( theTria2, N2new, 6 );
595
596   return true;
597 }
598
599 //=======================================================================
600 //function : findTriangles
601 //purpose  : find triangles sharing theNode1-theNode2 link
602 //=======================================================================
603
604 static bool findTriangles(const SMDS_MeshNode *    theNode1,
605                           const SMDS_MeshNode *    theNode2,
606                           const SMDS_MeshElement*& theTria1,
607                           const SMDS_MeshElement*& theTria2)
608 {
609   if ( !theNode1 || !theNode2 ) return false;
610
611   theTria1 = theTria2 = 0;
612
613   set< const SMDS_MeshElement* > emap;
614   SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator(SMDSAbs_Face);
615   while (it->more()) {
616     const SMDS_MeshElement* elem = it->next();
617     if ( elem->NbNodes() == 3 )
618       emap.insert( elem );
619   }
620   it = theNode2->GetInverseElementIterator(SMDSAbs_Face);
621   while (it->more()) {
622     const SMDS_MeshElement* elem = it->next();
623     if ( emap.find( elem ) != emap.end() )
624       if ( theTria1 ) {
625         // theTria1 must be element with minimum ID
626         if( theTria1->GetID() < elem->GetID() ) {
627           theTria2 = elem;
628         }
629         else {
630           theTria2 = theTria1;
631           theTria1 = elem;
632         }
633         break;
634       }
635       else {
636         theTria1 = elem;
637       }
638   }
639   return ( theTria1 && theTria2 );
640 }
641
642 //=======================================================================
643 //function : InverseDiag
644 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
645 //           with ones built on the same 4 nodes but having other common link.
646 //           Return false if proper faces not found
647 //=======================================================================
648
649 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
650                                     const SMDS_MeshNode * theNode2)
651 {
652   myLastCreatedElems.Clear();
653   myLastCreatedNodes.Clear();
654
655   MESSAGE( "::InverseDiag()" );
656
657   const SMDS_MeshElement *tr1, *tr2;
658   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
659     return false;
660
661   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
662   //if (!F1) return false;
663   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
664   //if (!F2) return false;
665   if (F1 && F2) {
666
667     //  1 +--+ A  tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
668     //    | /|    tr2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |
669     //    |/ |                                    | \|
670     //  B +--+ 2                                B +--+ 2
671
672     // put nodes in array
673     // and find indices of 1,2 and of A in tr1 and of B in tr2
674     int i, iA1 = 0, i1 = 0;
675     const SMDS_MeshNode* aNodes1 [3];
676     SMDS_ElemIteratorPtr it;
677     for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
678       aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
679       if ( aNodes1[ i ] == theNode1 )
680         iA1 = i; // node A in tr1
681       else if ( aNodes1[ i ] != theNode2 )
682         i1 = i;  // node 1
683     }
684     int iB2 = 0, i2 = 0;
685     const SMDS_MeshNode* aNodes2 [3];
686     for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
687       aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
688       if ( aNodes2[ i ] == theNode2 )
689         iB2 = i; // node B in tr2
690       else if ( aNodes2[ i ] != theNode1 )
691         i2 = i;  // node 2
692     }
693
694     // nodes 1 and 2 should not be the same
695     if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
696       return false;
697
698     // tr1: A->2
699     aNodes1[ iA1 ] = aNodes2[ i2 ];
700     // tr2: B->1
701     aNodes2[ iB2 ] = aNodes1[ i1 ];
702
703     //MESSAGE( tr1 << tr2 );
704
705     GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
706     GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
707
708     //MESSAGE( tr1 << tr2 );
709
710     return true;
711   }
712
713   // check case of quadratic faces
714   const SMDS_QuadraticFaceOfNodes* QF1 =
715     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr1);
716   if(!QF1) return false;
717   const SMDS_QuadraticFaceOfNodes* QF2 =
718     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr2);
719   if(!QF2) return false;
720   return InverseDiag(tr1,tr2);
721 }
722
723 //=======================================================================
724 //function : getQuadrangleNodes
725 //purpose  : fill theQuadNodes - nodes of a quadrangle resulting from
726 //           fusion of triangles tr1 and tr2 having shared link on
727 //           theNode1 and theNode2
728 //=======================================================================
729
730 bool getQuadrangleNodes(const SMDS_MeshNode *    theQuadNodes [],
731                         const SMDS_MeshNode *    theNode1,
732                         const SMDS_MeshNode *    theNode2,
733                         const SMDS_MeshElement * tr1,
734                         const SMDS_MeshElement * tr2 )
735 {
736   if( tr1->NbNodes() != tr2->NbNodes() )
737     return false;
738   // find the 4-th node to insert into tr1
739   const SMDS_MeshNode* n4 = 0;
740   SMDS_ElemIteratorPtr it = tr2->nodesIterator();
741   int i=0;
742   while ( !n4 && i<3 ) {
743     const SMDS_MeshNode * n = cast2Node( it->next() );
744     i++;
745     bool isDiag = ( n == theNode1 || n == theNode2 );
746     if ( !isDiag )
747       n4 = n;
748   }
749   // Make an array of nodes to be in a quadrangle
750   int iNode = 0, iFirstDiag = -1;
751   it = tr1->nodesIterator();
752   i=0;
753   while ( i<3 ) {
754     const SMDS_MeshNode * n = cast2Node( it->next() );
755     i++;
756     bool isDiag = ( n == theNode1 || n == theNode2 );
757     if ( isDiag ) {
758       if ( iFirstDiag < 0 )
759         iFirstDiag = iNode;
760       else if ( iNode - iFirstDiag == 1 )
761         theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
762     }
763     else if ( n == n4 ) {
764       return false; // tr1 and tr2 should not have all the same nodes
765     }
766     theQuadNodes[ iNode++ ] = n;
767   }
768   if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
769     theQuadNodes[ iNode ] = n4;
770
771   return true;
772 }
773
774 //=======================================================================
775 //function : DeleteDiag
776 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
777 //           with a quadrangle built on the same 4 nodes.
778 //           Return false if proper faces not found
779 //=======================================================================
780
781 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
782                                    const SMDS_MeshNode * theNode2)
783 {
784   myLastCreatedElems.Clear();
785   myLastCreatedNodes.Clear();
786
787   MESSAGE( "::DeleteDiag()" );
788
789   const SMDS_MeshElement *tr1, *tr2;
790   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
791     return false;
792
793   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
794   //if (!F1) return false;
795   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
796   //if (!F2) return false;
797   if (F1 && F2) {
798
799     const SMDS_MeshNode* aNodes [ 4 ];
800     if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
801       return false;
802
803     //MESSAGE( endl << tr1 << tr2 );
804
805     GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
806     myLastCreatedElems.Append(tr1);
807     GetMeshDS()->RemoveElement( tr2 );
808
809     //MESSAGE( endl << tr1 );
810
811     return true;
812   }
813
814   // check case of quadratic faces
815   const SMDS_QuadraticFaceOfNodes* QF1 =
816     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr1);
817   if(!QF1) return false;
818   const SMDS_QuadraticFaceOfNodes* QF2 =
819     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr2);
820   if(!QF2) return false;
821
822   //       5
823   //  1 +--+--+ 2  tr1: (1 2 4 5 9 7) or (2 4 1 9 7 5) or (4 1 2 7 5 9)
824   //    |    /|    tr2: (2 3 4 6 8 9) or (3 4 2 8 9 6) or (4 2 3 9 6 8)
825   //    |   / |
826   //  7 +  +  + 6
827   //    | /9  |
828   //    |/    |
829   //  4 +--+--+ 3
830   //       8
831
832   const SMDS_MeshNode* N1 [6];
833   const SMDS_MeshNode* N2 [6];
834   if(!GetNodesFromTwoTria(tr1,tr2,N1,N2))
835     return false;
836   // now we receive following N1 and N2 (using numeration as above image)
837   // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6)
838   // i.e. first nodes from both arrays determ new diagonal
839
840   const SMDS_MeshNode* aNodes[8];
841   aNodes[0] = N1[0];
842   aNodes[1] = N1[1];
843   aNodes[2] = N2[0];
844   aNodes[3] = N2[1];
845   aNodes[4] = N1[3];
846   aNodes[5] = N2[5];
847   aNodes[6] = N2[3];
848   aNodes[7] = N1[5];
849
850   GetMeshDS()->ChangeElementNodes( tr1, aNodes, 8 );
851   myLastCreatedElems.Append(tr1);
852   GetMeshDS()->RemoveElement( tr2 );
853
854   // remove middle node (9)
855   GetMeshDS()->RemoveNode( N1[4] );
856
857   return true;
858 }
859
860 //=======================================================================
861 //function : Reorient
862 //purpose  : Reverse theElement orientation
863 //=======================================================================
864
865 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
866 {
867   myLastCreatedElems.Clear();
868   myLastCreatedNodes.Clear();
869
870   if (!theElem)
871     return false;
872   SMDS_ElemIteratorPtr it = theElem->nodesIterator();
873   if ( !it || !it->more() )
874     return false;
875
876   switch ( theElem->GetType() ) {
877
878   case SMDSAbs_Edge:
879   case SMDSAbs_Face: {
880     if(!theElem->IsQuadratic()) {
881       int i = theElem->NbNodes();
882       vector<const SMDS_MeshNode*> aNodes( i );
883       while ( it->more() )
884         aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
885       return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
886     }
887     else {
888       // quadratic elements
889       if(theElem->GetType()==SMDSAbs_Edge) {
890         vector<const SMDS_MeshNode*> aNodes(3);
891         aNodes[1]= static_cast<const SMDS_MeshNode*>( it->next() );
892         aNodes[0]= static_cast<const SMDS_MeshNode*>( it->next() );
893         aNodes[2]= static_cast<const SMDS_MeshNode*>( it->next() );
894         return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], 3 );
895       }
896       else {
897         int nbn = theElem->NbNodes();
898         vector<const SMDS_MeshNode*> aNodes(nbn);
899         aNodes[0]= static_cast<const SMDS_MeshNode*>( it->next() );
900         int i=1;
901         for(; i<nbn/2; i++) {
902           aNodes[nbn/2-i]= static_cast<const SMDS_MeshNode*>( it->next() );
903         }
904         for(i=0; i<nbn/2; i++) {
905           aNodes[nbn-i-1]= static_cast<const SMDS_MeshNode*>( it->next() );
906         }
907         return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], nbn );
908       }
909     }
910   }
911   case SMDSAbs_Volume: {
912     if (theElem->IsPoly()) {
913       const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
914         static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
915       if (!aPolyedre) {
916         MESSAGE("Warning: bad volumic element");
917         return false;
918       }
919
920       int nbFaces = aPolyedre->NbFaces();
921       vector<const SMDS_MeshNode *> poly_nodes;
922       vector<int> quantities (nbFaces);
923
924       // reverse each face of the polyedre
925       for (int iface = 1; iface <= nbFaces; iface++) {
926         int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
927         quantities[iface - 1] = nbFaceNodes;
928
929         for (inode = nbFaceNodes; inode >= 1; inode--) {
930           const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
931           poly_nodes.push_back(curNode);
932         }
933       }
934
935       return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
936
937     }
938     else {
939       SMDS_VolumeTool vTool;
940       if ( !vTool.Set( theElem ))
941         return false;
942       vTool.Inverse();
943       return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
944     }
945   }
946   default:;
947   }
948
949   return false;
950 }
951
952 //=======================================================================
953 //function : getBadRate
954 //purpose  :
955 //=======================================================================
956
957 static double getBadRate (const SMDS_MeshElement*               theElem,
958                           SMESH::Controls::NumericalFunctorPtr& theCrit)
959 {
960   SMESH::Controls::TSequenceOfXYZ P;
961   if ( !theElem || !theCrit->GetPoints( theElem, P ))
962     return 1e100;
963   return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
964   //return theCrit->GetBadRate( theCrit->GetValue( theElem->GetID() ), theElem->NbNodes() );
965 }
966
967 //=======================================================================
968 //function : QuadToTri
969 //purpose  : Cut quadrangles into triangles.
970 //           theCrit is used to select a diagonal to cut
971 //=======================================================================
972
973 bool SMESH_MeshEditor::QuadToTri (TIDSortedElemSet &                   theElems,
974                                   SMESH::Controls::NumericalFunctorPtr theCrit)
975 {
976   myLastCreatedElems.Clear();
977   myLastCreatedNodes.Clear();
978
979   MESSAGE( "::QuadToTri()" );
980
981   if ( !theCrit.get() )
982     return false;
983
984   SMESHDS_Mesh * aMesh = GetMeshDS();
985
986   Handle(Geom_Surface) surface;
987   SMESH_MesherHelper   helper( *GetMesh() );
988
989   TIDSortedElemSet::iterator itElem;
990   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
991     const SMDS_MeshElement* elem = *itElem;
992     if ( !elem || elem->GetType() != SMDSAbs_Face )
993       continue;
994     if ( elem->NbNodes() != ( elem->IsQuadratic() ? 8 : 4 ))
995       continue;
996
997     // retrieve element nodes
998     const SMDS_MeshNode* aNodes [8];
999     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1000     int i = 0;
1001     while ( itN->more() )
1002       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1003
1004     // compare two sets of possible triangles
1005     double aBadRate1, aBadRate2; // to what extent a set is bad
1006     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
1007     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
1008     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
1009
1010     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
1011     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
1012     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
1013
1014     int aShapeId = FindShape( elem );
1015     const SMDS_MeshElement* newElem = 0;
1016
1017     if( !elem->IsQuadratic() ) {
1018
1019       // split liner quadrangle
1020
1021       if ( aBadRate1 <= aBadRate2 ) {
1022         // tr1 + tr2 is better
1023         aMesh->ChangeElementNodes( elem, aNodes, 3 );
1024         newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
1025       }
1026       else {
1027         // tr3 + tr4 is better
1028         aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
1029         newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
1030       }
1031     }
1032     else {
1033
1034       // split quadratic quadrangle
1035
1036       // get surface elem is on
1037       if ( aShapeId != helper.GetSubShapeID() ) {
1038         surface.Nullify();
1039         TopoDS_Shape shape;
1040         if ( aShapeId > 0 )
1041           shape = aMesh->IndexToShape( aShapeId );
1042         if ( !shape.IsNull() && shape.ShapeType() == TopAbs_FACE ) {
1043           TopoDS_Face face = TopoDS::Face( shape );
1044           surface = BRep_Tool::Surface( face );
1045           if ( !surface.IsNull() )
1046             helper.SetSubShape( shape );
1047         }
1048       }
1049       // get elem nodes
1050       const SMDS_MeshNode* aNodes [8];
1051       const SMDS_MeshNode* inFaceNode = 0;
1052       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1053       int i = 0;
1054       while ( itN->more() ) {
1055         aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1056         if ( !inFaceNode && helper.GetNodeUVneedInFaceNode() &&
1057              aNodes[ i-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1058         {
1059           inFaceNode = aNodes[ i-1 ];
1060         }
1061       }
1062       // find middle point for (0,1,2,3)
1063       // and create a node in this point;
1064       gp_XYZ p( 0,0,0 );
1065       if ( surface.IsNull() ) {
1066         for(i=0; i<4; i++)
1067           p += gp_XYZ(aNodes[i]->X(), aNodes[i]->Y(), aNodes[i]->Z() );
1068         p /= 4;
1069       }
1070       else {
1071         TopoDS_Face face = TopoDS::Face( helper.GetSubShape() );
1072         gp_XY uv( 0,0 );
1073         for(i=0; i<4; i++)
1074           uv += helper.GetNodeUV( face, aNodes[i], inFaceNode );
1075         uv /= 4.;
1076         p = surface->Value( uv.X(), uv.Y() ).XYZ();
1077       }
1078       const SMDS_MeshNode* newN = aMesh->AddNode( p.X(), p.Y(), p.Z() );
1079       myLastCreatedNodes.Append(newN);
1080
1081       // create a new element
1082       const SMDS_MeshNode* N[6];
1083       if ( aBadRate1 <= aBadRate2 ) {
1084         N[0] = aNodes[0];
1085         N[1] = aNodes[1];
1086         N[2] = aNodes[2];
1087         N[3] = aNodes[4];
1088         N[4] = aNodes[5];
1089         N[5] = newN;
1090         newElem = aMesh->AddFace(aNodes[2], aNodes[3], aNodes[0],
1091                                  aNodes[6], aNodes[7], newN );
1092       }
1093       else {
1094         N[0] = aNodes[1];
1095         N[1] = aNodes[2];
1096         N[2] = aNodes[3];
1097         N[3] = aNodes[5];
1098         N[4] = aNodes[6];
1099         N[5] = newN;
1100         newElem = aMesh->AddFace(aNodes[3], aNodes[0], aNodes[1],
1101                                  aNodes[7], aNodes[4], newN );
1102       }
1103       aMesh->ChangeElementNodes( elem, N, 6 );
1104
1105     } // quadratic case
1106
1107     // care of a new element
1108
1109     myLastCreatedElems.Append(newElem);
1110     AddToSameGroups( newElem, elem, aMesh );
1111
1112     // put a new triangle on the same shape
1113     if ( aShapeId )
1114       aMesh->SetMeshElementOnShape( newElem, aShapeId );
1115   }
1116   return true;
1117 }
1118
1119 //=======================================================================
1120 //function : BestSplit
1121 //purpose  : Find better diagonal for cutting.
1122 //=======================================================================
1123 int SMESH_MeshEditor::BestSplit (const SMDS_MeshElement*              theQuad,
1124                                  SMESH::Controls::NumericalFunctorPtr theCrit)
1125 {
1126   myLastCreatedElems.Clear();
1127   myLastCreatedNodes.Clear();
1128
1129   if (!theCrit.get())
1130     return -1;
1131
1132   if (!theQuad || theQuad->GetType() != SMDSAbs_Face )
1133     return -1;
1134
1135   if( theQuad->NbNodes()==4 ||
1136       (theQuad->NbNodes()==8 && theQuad->IsQuadratic()) ) {
1137
1138     // retrieve element nodes
1139     const SMDS_MeshNode* aNodes [4];
1140     SMDS_ElemIteratorPtr itN = theQuad->nodesIterator();
1141     int i = 0;
1142     //while (itN->more())
1143     while (i<4) {
1144       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1145     }
1146     // compare two sets of possible triangles
1147     double aBadRate1, aBadRate2; // to what extent a set is bad
1148     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
1149     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
1150     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
1151
1152     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
1153     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
1154     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
1155
1156     if (aBadRate1 <= aBadRate2) // tr1 + tr2 is better
1157       return 1; // diagonal 1-3
1158
1159     return 2; // diagonal 2-4
1160   }
1161   return -1;
1162 }
1163
1164 //=======================================================================
1165 //function : AddToSameGroups
1166 //purpose  : add elemToAdd to the groups the elemInGroups belongs to
1167 //=======================================================================
1168
1169 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
1170                                         const SMDS_MeshElement* elemInGroups,
1171                                         SMESHDS_Mesh *          aMesh)
1172 {
1173   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
1174   if (!groups.empty()) {
1175     set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
1176     for ( ; grIt != groups.end(); grIt++ ) {
1177       SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
1178       if ( group && group->Contains( elemInGroups ))
1179         group->SMDSGroup().Add( elemToAdd );
1180     }
1181   }
1182 }
1183
1184
1185 //=======================================================================
1186 //function : RemoveElemFromGroups
1187 //purpose  : Remove removeelem to the groups the elemInGroups belongs to
1188 //=======================================================================
1189 void SMESH_MeshEditor::RemoveElemFromGroups (const SMDS_MeshElement* removeelem,
1190                                              SMESHDS_Mesh *          aMesh)
1191 {
1192   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
1193   if (!groups.empty())
1194   {
1195     set<SMESHDS_GroupBase*>::const_iterator GrIt = groups.begin();
1196     for (; GrIt != groups.end(); GrIt++)
1197     {
1198       SMESHDS_Group* grp = dynamic_cast<SMESHDS_Group*>(*GrIt);
1199       if (!grp || grp->IsEmpty()) continue;
1200       grp->SMDSGroup().Remove(removeelem);
1201     }
1202   }
1203 }
1204
1205 //=======================================================================
1206 //function : ReplaceElemInGroups
1207 //purpose  : replace elemToRm by elemToAdd in the all groups
1208 //=======================================================================
1209
1210 void SMESH_MeshEditor::ReplaceElemInGroups (const SMDS_MeshElement* elemToRm,
1211                                             const SMDS_MeshElement* elemToAdd,
1212                                             SMESHDS_Mesh *          aMesh)
1213 {
1214   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
1215   if (!groups.empty()) {
1216     set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
1217     for ( ; grIt != groups.end(); grIt++ ) {
1218       SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
1219       if ( group && group->SMDSGroup().Remove( elemToRm ) && elemToAdd )
1220         group->SMDSGroup().Add( elemToAdd );
1221     }
1222   }
1223 }
1224
1225 //=======================================================================
1226 //function : QuadToTri
1227 //purpose  : Cut quadrangles into triangles.
1228 //           theCrit is used to select a diagonal to cut
1229 //=======================================================================
1230
1231 bool SMESH_MeshEditor::QuadToTri (TIDSortedElemSet & theElems,
1232                                   const bool         the13Diag)
1233 {
1234   myLastCreatedElems.Clear();
1235   myLastCreatedNodes.Clear();
1236
1237   MESSAGE( "::QuadToTri()" );
1238
1239   SMESHDS_Mesh * aMesh = GetMeshDS();
1240
1241   Handle(Geom_Surface) surface;
1242   SMESH_MesherHelper   helper( *GetMesh() );
1243
1244   TIDSortedElemSet::iterator itElem;
1245   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1246     const SMDS_MeshElement* elem = *itElem;
1247     if ( !elem || elem->GetType() != SMDSAbs_Face )
1248       continue;
1249     bool isquad = elem->NbNodes()==4 || elem->NbNodes()==8;
1250     if(!isquad) continue;
1251
1252     if(elem->NbNodes()==4) {
1253       // retrieve element nodes
1254       const SMDS_MeshNode* aNodes [4];
1255       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1256       int i = 0;
1257       while ( itN->more() )
1258         aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1259
1260       int aShapeId = FindShape( elem );
1261       const SMDS_MeshElement* newElem = 0;
1262       if ( the13Diag ) {
1263         aMesh->ChangeElementNodes( elem, aNodes, 3 );
1264         newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
1265       }
1266       else {
1267         aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
1268         newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
1269       }
1270       myLastCreatedElems.Append(newElem);
1271       // put a new triangle on the same shape and add to the same groups
1272       if ( aShapeId )
1273         aMesh->SetMeshElementOnShape( newElem, aShapeId );
1274       AddToSameGroups( newElem, elem, aMesh );
1275     }
1276
1277     // Quadratic quadrangle
1278
1279     if( elem->NbNodes()==8 && elem->IsQuadratic() ) {
1280
1281       // get surface elem is on
1282       int aShapeId = FindShape( elem );
1283       if ( aShapeId != helper.GetSubShapeID() ) {
1284         surface.Nullify();
1285         TopoDS_Shape shape;
1286         if ( aShapeId > 0 )
1287           shape = aMesh->IndexToShape( aShapeId );
1288         if ( !shape.IsNull() && shape.ShapeType() == TopAbs_FACE ) {
1289           TopoDS_Face face = TopoDS::Face( shape );
1290           surface = BRep_Tool::Surface( face );
1291           if ( !surface.IsNull() )
1292             helper.SetSubShape( shape );
1293         }
1294       }
1295
1296       const SMDS_MeshNode* aNodes [8];
1297       const SMDS_MeshNode* inFaceNode = 0;
1298       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1299       int i = 0;
1300       while ( itN->more() ) {
1301         aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1302         if ( !inFaceNode && helper.GetNodeUVneedInFaceNode() &&
1303              aNodes[ i-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1304         {
1305           inFaceNode = aNodes[ i-1 ];
1306         }
1307       }
1308
1309       // find middle point for (0,1,2,3)
1310       // and create a node in this point;
1311       gp_XYZ p( 0,0,0 );
1312       if ( surface.IsNull() ) {
1313         for(i=0; i<4; i++)
1314           p += gp_XYZ(aNodes[i]->X(), aNodes[i]->Y(), aNodes[i]->Z() );
1315         p /= 4;
1316       }
1317       else {
1318         TopoDS_Face geomFace = TopoDS::Face( helper.GetSubShape() );
1319         gp_XY uv( 0,0 );
1320         for(i=0; i<4; i++)
1321           uv += helper.GetNodeUV( geomFace, aNodes[i], inFaceNode );
1322         uv /= 4.;
1323         p = surface->Value( uv.X(), uv.Y() ).XYZ();
1324       }
1325       const SMDS_MeshNode* newN = aMesh->AddNode( p.X(), p.Y(), p.Z() );
1326       myLastCreatedNodes.Append(newN);
1327
1328       // create a new element
1329       const SMDS_MeshElement* newElem = 0;
1330       const SMDS_MeshNode* N[6];
1331       if ( the13Diag ) {
1332         N[0] = aNodes[0];
1333         N[1] = aNodes[1];
1334         N[2] = aNodes[2];
1335         N[3] = aNodes[4];
1336         N[4] = aNodes[5];
1337         N[5] = newN;
1338         newElem = aMesh->AddFace(aNodes[2], aNodes[3], aNodes[0],
1339                                  aNodes[6], aNodes[7], newN );
1340       }
1341       else {
1342         N[0] = aNodes[1];
1343         N[1] = aNodes[2];
1344         N[2] = aNodes[3];
1345         N[3] = aNodes[5];
1346         N[4] = aNodes[6];
1347         N[5] = newN;
1348         newElem = aMesh->AddFace(aNodes[3], aNodes[0], aNodes[1],
1349                                  aNodes[7], aNodes[4], newN );
1350       }
1351       myLastCreatedElems.Append(newElem);
1352       aMesh->ChangeElementNodes( elem, N, 6 );
1353       // put a new triangle on the same shape and add to the same groups
1354       if ( aShapeId )
1355         aMesh->SetMeshElementOnShape( newElem, aShapeId );
1356       AddToSameGroups( newElem, elem, aMesh );
1357     }
1358   }
1359
1360   return true;
1361 }
1362
1363 //=======================================================================
1364 //function : getAngle
1365 //purpose  :
1366 //=======================================================================
1367
1368 double getAngle(const SMDS_MeshElement * tr1,
1369                 const SMDS_MeshElement * tr2,
1370                 const SMDS_MeshNode *    n1,
1371                 const SMDS_MeshNode *    n2)
1372 {
1373   double angle = 2*PI; // bad angle
1374
1375   // get normals
1376   SMESH::Controls::TSequenceOfXYZ P1, P2;
1377   if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
1378        !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
1379     return angle;
1380   gp_Vec N1,N2;
1381   if(!tr1->IsQuadratic())
1382     N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
1383   else
1384     N1 = gp_Vec( P1(3) - P1(1) ) ^ gp_Vec( P1(5) - P1(1) );
1385   if ( N1.SquareMagnitude() <= gp::Resolution() )
1386     return angle;
1387   if(!tr2->IsQuadratic())
1388     N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
1389   else
1390     N2 = gp_Vec( P2(3) - P2(1) ) ^ gp_Vec( P2(5) - P2(1) );
1391   if ( N2.SquareMagnitude() <= gp::Resolution() )
1392     return angle;
1393
1394   // find the first diagonal node n1 in the triangles:
1395   // take in account a diagonal link orientation
1396   const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
1397   for ( int t = 0; t < 2; t++ ) {
1398     SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
1399     int i = 0, iDiag = -1;
1400     while ( it->more()) {
1401       const SMDS_MeshElement *n = it->next();
1402       if ( n == n1 || n == n2 )
1403         if ( iDiag < 0)
1404           iDiag = i;
1405         else {
1406           if ( i - iDiag == 1 )
1407             nFirst[ t ] = ( n == n1 ? n2 : n1 );
1408           else
1409             nFirst[ t ] = n;
1410           break;
1411         }
1412       i++;
1413     }
1414   }
1415   if ( nFirst[ 0 ] == nFirst[ 1 ] )
1416     N2.Reverse();
1417
1418   angle = N1.Angle( N2 );
1419   //SCRUTE( angle );
1420   return angle;
1421 }
1422
1423 // =================================================
1424 // class generating a unique ID for a pair of nodes
1425 // and able to return nodes by that ID
1426 // =================================================
1427 class LinkID_Gen {
1428  public:
1429
1430   LinkID_Gen( const SMESHDS_Mesh* theMesh )
1431     :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
1432   {}
1433
1434   long GetLinkID (const SMDS_MeshNode * n1,
1435                   const SMDS_MeshNode * n2) const
1436   {
1437     return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
1438   }
1439
1440   bool GetNodes (const long             theLinkID,
1441                  const SMDS_MeshNode* & theNode1,
1442                  const SMDS_MeshNode* & theNode2) const
1443   {
1444     theNode1 = myMesh->FindNode( theLinkID / myMaxID );
1445     if ( !theNode1 ) return false;
1446     theNode2 = myMesh->FindNode( theLinkID % myMaxID );
1447     if ( !theNode2 ) return false;
1448     return true;
1449   }
1450
1451  private:
1452   LinkID_Gen();
1453   const SMESHDS_Mesh* myMesh;
1454   long                myMaxID;
1455 };
1456
1457
1458 //=======================================================================
1459 //function : TriToQuad
1460 //purpose  : Fuse neighbour triangles into quadrangles.
1461 //           theCrit is used to select a neighbour to fuse with.
1462 //           theMaxAngle is a max angle between element normals at which
1463 //           fusion is still performed.
1464 //=======================================================================
1465
1466 bool SMESH_MeshEditor::TriToQuad (TIDSortedElemSet &                   theElems,
1467                                   SMESH::Controls::NumericalFunctorPtr theCrit,
1468                                   const double                         theMaxAngle)
1469 {
1470   myLastCreatedElems.Clear();
1471   myLastCreatedNodes.Clear();
1472
1473   MESSAGE( "::TriToQuad()" );
1474
1475   if ( !theCrit.get() )
1476     return false;
1477
1478   SMESHDS_Mesh * aMesh = GetMeshDS();
1479
1480   // Prepare data for algo: build
1481   // 1. map of elements with their linkIDs
1482   // 2. map of linkIDs with their elements
1483
1484   map< TLink, list< const SMDS_MeshElement* > > mapLi_listEl;
1485   map< TLink, list< const SMDS_MeshElement* > >::iterator itLE;
1486   map< const SMDS_MeshElement*, set< TLink > >  mapEl_setLi;
1487   map< const SMDS_MeshElement*, set< TLink > >::iterator itEL;
1488
1489   TIDSortedElemSet::iterator itElem;
1490   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1491     const SMDS_MeshElement* elem = *itElem;
1492     if(!elem || elem->GetType() != SMDSAbs_Face ) continue;
1493     bool IsTria = elem->NbNodes()==3 || (elem->NbNodes()==6 && elem->IsQuadratic());
1494     if(!IsTria) continue;
1495
1496     // retrieve element nodes
1497     const SMDS_MeshNode* aNodes [4];
1498     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1499     int i = 0;
1500     while ( i<3 )
1501       aNodes[ i++ ] = cast2Node( itN->next() );
1502     aNodes[ 3 ] = aNodes[ 0 ];
1503
1504     // fill maps
1505     for ( i = 0; i < 3; i++ ) {
1506       TLink link( aNodes[i], aNodes[i+1] );
1507       // check if elements sharing a link can be fused
1508       itLE = mapLi_listEl.find( link );
1509       if ( itLE != mapLi_listEl.end() ) {
1510         if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
1511           continue;
1512         const SMDS_MeshElement* elem2 = (*itLE).second.front();
1513         //if ( FindShape( elem ) != FindShape( elem2 ))
1514         //  continue; // do not fuse triangles laying on different shapes
1515         if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
1516           continue; // avoid making badly shaped quads
1517         (*itLE).second.push_back( elem );
1518       }
1519       else {
1520         mapLi_listEl[ link ].push_back( elem );
1521       }
1522       mapEl_setLi [ elem ].insert( link );
1523     }
1524   }
1525   // Clean the maps from the links shared by a sole element, ie
1526   // links to which only one element is bound in mapLi_listEl
1527
1528   for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ ) {
1529     int nbElems = (*itLE).second.size();
1530     if ( nbElems < 2  ) {
1531       const SMDS_MeshElement* elem = (*itLE).second.front();
1532       TLink link = (*itLE).first;
1533       mapEl_setLi[ elem ].erase( link );
1534       if ( mapEl_setLi[ elem ].empty() )
1535         mapEl_setLi.erase( elem );
1536     }
1537   }
1538
1539   // Algo: fuse triangles into quadrangles
1540
1541   while ( ! mapEl_setLi.empty() ) {
1542     // Look for the start element:
1543     // the element having the least nb of shared links
1544     const SMDS_MeshElement* startElem = 0;
1545     int minNbLinks = 4;
1546     for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ ) {
1547       int nbLinks = (*itEL).second.size();
1548       if ( nbLinks < minNbLinks ) {
1549         startElem = (*itEL).first;
1550         minNbLinks = nbLinks;
1551         if ( minNbLinks == 1 )
1552           break;
1553       }
1554     }
1555
1556     // search elements to fuse starting from startElem or links of elements
1557     // fused earlyer - startLinks
1558     list< TLink > startLinks;
1559     while ( startElem || !startLinks.empty() ) {
1560       while ( !startElem && !startLinks.empty() ) {
1561         // Get an element to start, by a link
1562         TLink linkId = startLinks.front();
1563         startLinks.pop_front();
1564         itLE = mapLi_listEl.find( linkId );
1565         if ( itLE != mapLi_listEl.end() ) {
1566           list< const SMDS_MeshElement* > & listElem = (*itLE).second;
1567           list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
1568           for ( ; itE != listElem.end() ; itE++ )
1569             if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
1570               startElem = (*itE);
1571           mapLi_listEl.erase( itLE );
1572         }
1573       }
1574
1575       if ( startElem ) {
1576         // Get candidates to be fused
1577         const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
1578         const TLink *link12, *link13;
1579         startElem = 0;
1580         ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
1581         set< TLink >& setLi = mapEl_setLi[ tr1 ];
1582         ASSERT( !setLi.empty() );
1583         set< TLink >::iterator itLi;
1584         for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
1585         {
1586           const TLink & link = (*itLi);
1587           itLE = mapLi_listEl.find( link );
1588           if ( itLE == mapLi_listEl.end() )
1589             continue;
1590
1591           const SMDS_MeshElement* elem = (*itLE).second.front();
1592           if ( elem == tr1 )
1593             elem = (*itLE).second.back();
1594           mapLi_listEl.erase( itLE );
1595           if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
1596             continue;
1597           if ( tr2 ) {
1598             tr3 = elem;
1599             link13 = &link;
1600           }
1601           else {
1602             tr2 = elem;
1603             link12 = &link;
1604           }
1605
1606           // add other links of elem to list of links to re-start from
1607           set< TLink >& links = mapEl_setLi[ elem ];
1608           set< TLink >::iterator it;
1609           for ( it = links.begin(); it != links.end(); it++ ) {
1610             const TLink& link2 = (*it);
1611             if ( link2 != link )
1612               startLinks.push_back( link2 );
1613           }
1614         }
1615
1616         // Get nodes of possible quadrangles
1617         const SMDS_MeshNode *n12 [4], *n13 [4];
1618         bool Ok12 = false, Ok13 = false;
1619         const SMDS_MeshNode *linkNode1, *linkNode2;
1620         if(tr2) {
1621           linkNode1 = link12->first;
1622           linkNode2 = link12->second;
1623           if ( tr2 && getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
1624             Ok12 = true;
1625         }
1626         if(tr3) {
1627           linkNode1 = link13->first;
1628           linkNode2 = link13->second;
1629           if ( tr3 && getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1630             Ok13 = true;
1631         }
1632
1633         // Choose a pair to fuse
1634         if ( Ok12 && Ok13 ) {
1635           SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
1636           SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
1637           double aBadRate12 = getBadRate( &quad12, theCrit );
1638           double aBadRate13 = getBadRate( &quad13, theCrit );
1639           if (  aBadRate13 < aBadRate12 )
1640             Ok12 = false;
1641           else
1642             Ok13 = false;
1643         }
1644
1645         // Make quadrangles
1646         // and remove fused elems and removed links from the maps
1647         mapEl_setLi.erase( tr1 );
1648         if ( Ok12 ) {
1649           mapEl_setLi.erase( tr2 );
1650           mapLi_listEl.erase( *link12 );
1651           if(tr1->NbNodes()==3) {
1652             if( tr1->GetID() < tr2->GetID() ) {
1653               aMesh->ChangeElementNodes( tr1, n12, 4 );
1654               myLastCreatedElems.Append(tr1);
1655               aMesh->RemoveElement( tr2 );
1656             }
1657             else {
1658               aMesh->ChangeElementNodes( tr2, n12, 4 );
1659               myLastCreatedElems.Append(tr2);
1660               aMesh->RemoveElement( tr1);
1661             }
1662           }
1663           else {
1664             const SMDS_MeshNode* N1 [6];
1665             const SMDS_MeshNode* N2 [6];
1666             GetNodesFromTwoTria(tr1,tr2,N1,N2);
1667             // now we receive following N1 and N2 (using numeration as above image)
1668             // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6)
1669             // i.e. first nodes from both arrays determ new diagonal
1670             const SMDS_MeshNode* aNodes[8];
1671             aNodes[0] = N1[0];
1672             aNodes[1] = N1[1];
1673             aNodes[2] = N2[0];
1674             aNodes[3] = N2[1];
1675             aNodes[4] = N1[3];
1676             aNodes[5] = N2[5];
1677             aNodes[6] = N2[3];
1678             aNodes[7] = N1[5];
1679             if( tr1->GetID() < tr2->GetID() ) {
1680               GetMeshDS()->ChangeElementNodes( tr1, aNodes, 8 );
1681               myLastCreatedElems.Append(tr1);
1682               GetMeshDS()->RemoveElement( tr2 );
1683             }
1684             else {
1685               GetMeshDS()->ChangeElementNodes( tr2, aNodes, 8 );
1686               myLastCreatedElems.Append(tr2);
1687               GetMeshDS()->RemoveElement( tr1 );
1688             }
1689             // remove middle node (9)
1690             GetMeshDS()->RemoveNode( N1[4] );
1691           }
1692         }
1693         else if ( Ok13 ) {
1694           mapEl_setLi.erase( tr3 );
1695           mapLi_listEl.erase( *link13 );
1696           if(tr1->NbNodes()==3) {
1697             if( tr1->GetID() < tr2->GetID() ) {
1698               aMesh->ChangeElementNodes( tr1, n13, 4 );
1699               myLastCreatedElems.Append(tr1);
1700               aMesh->RemoveElement( tr3 );
1701             }
1702             else {
1703               aMesh->ChangeElementNodes( tr3, n13, 4 );
1704               myLastCreatedElems.Append(tr3);
1705               aMesh->RemoveElement( tr1 );
1706             }
1707           }
1708           else {
1709             const SMDS_MeshNode* N1 [6];
1710             const SMDS_MeshNode* N2 [6];
1711             GetNodesFromTwoTria(tr1,tr3,N1,N2);
1712             // now we receive following N1 and N2 (using numeration as above image)
1713             // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6)
1714             // i.e. first nodes from both arrays determ new diagonal
1715             const SMDS_MeshNode* aNodes[8];
1716             aNodes[0] = N1[0];
1717             aNodes[1] = N1[1];
1718             aNodes[2] = N2[0];
1719             aNodes[3] = N2[1];
1720             aNodes[4] = N1[3];
1721             aNodes[5] = N2[5];
1722             aNodes[6] = N2[3];
1723             aNodes[7] = N1[5];
1724             if( tr1->GetID() < tr2->GetID() ) {
1725               GetMeshDS()->ChangeElementNodes( tr1, aNodes, 8 );
1726               myLastCreatedElems.Append(tr1);
1727               GetMeshDS()->RemoveElement( tr3 );
1728             }
1729             else {
1730               GetMeshDS()->ChangeElementNodes( tr3, aNodes, 8 );
1731               myLastCreatedElems.Append(tr3);
1732               GetMeshDS()->RemoveElement( tr1 );
1733             }
1734             // remove middle node (9)
1735             GetMeshDS()->RemoveNode( N1[4] );
1736           }
1737         }
1738
1739         // Next element to fuse: the rejected one
1740         if ( tr3 )
1741           startElem = Ok12 ? tr3 : tr2;
1742
1743       } // if ( startElem )
1744     } // while ( startElem || !startLinks.empty() )
1745   } // while ( ! mapEl_setLi.empty() )
1746
1747   return true;
1748 }
1749
1750
1751 /*#define DUMPSO(txt) \
1752 //  cout << txt << endl;
1753 //=============================================================================
1754 //
1755 //
1756 //
1757 //=============================================================================
1758 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1759 {
1760   if ( i1 == i2 )
1761     return;
1762   int tmp = idNodes[ i1 ];
1763   idNodes[ i1 ] = idNodes[ i2 ];
1764   idNodes[ i2 ] = tmp;
1765   gp_Pnt Ptmp = P[ i1 ];
1766   P[ i1 ] = P[ i2 ];
1767   P[ i2 ] = Ptmp;
1768   DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1769 }
1770
1771 //=======================================================================
1772 //function : SortQuadNodes
1773 //purpose  : Set 4 nodes of a quadrangle face in a good order.
1774 //           Swap 1<->2 or 2<->3 nodes and correspondingly return
1775 //           1 or 2 else 0.
1776 //=======================================================================
1777
1778 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1779                                      int               idNodes[] )
1780 {
1781   gp_Pnt P[4];
1782   int i;
1783   for ( i = 0; i < 4; i++ ) {
1784     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1785     if ( !n ) return 0;
1786     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1787   }
1788
1789   gp_Vec V1(P[0], P[1]);
1790   gp_Vec V2(P[0], P[2]);
1791   gp_Vec V3(P[0], P[3]);
1792
1793   gp_Vec Cross1 = V1 ^ V2;
1794   gp_Vec Cross2 = V2 ^ V3;
1795
1796   i = 0;
1797   if (Cross1.Dot(Cross2) < 0)
1798   {
1799     Cross1 = V2 ^ V1;
1800     Cross2 = V1 ^ V3;
1801
1802     if (Cross1.Dot(Cross2) < 0)
1803       i = 2;
1804     else
1805       i = 1;
1806     swap ( i, i + 1, idNodes, P );
1807
1808 //     for ( int ii = 0; ii < 4; ii++ ) {
1809 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1810 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1811 //     }
1812   }
1813   return i;
1814 }
1815
1816 //=======================================================================
1817 //function : SortHexaNodes
1818 //purpose  : Set 8 nodes of a hexahedron in a good order.
1819 //           Return success status
1820 //=======================================================================
1821
1822 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1823                                       int               idNodes[] )
1824 {
1825   gp_Pnt P[8];
1826   int i;
1827   DUMPSO( "INPUT: ========================================");
1828   for ( i = 0; i < 8; i++ ) {
1829     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1830     if ( !n ) return false;
1831     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1832     DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1833   }
1834   DUMPSO( "========================================");
1835
1836
1837   set<int> faceNodes;  // ids of bottom face nodes, to be found
1838   set<int> checkedId1; // ids of tried 2-nd nodes
1839   Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1840   const Standard_Real tol = 1.e-6;   // tolerance to find nodes in plane
1841   int iMin, iLoop1 = 0;
1842
1843   // Loop to try the 2-nd nodes
1844
1845   while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1846   {
1847     // Find not checked 2-nd node
1848     for ( i = 1; i < 8; i++ )
1849       if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1850         int id1 = idNodes[i];
1851         swap ( 1, i, idNodes, P );
1852         checkedId1.insert ( id1 );
1853         break;
1854       }
1855
1856     // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1857     // ie that all but meybe one (id3 which is on the same face) nodes
1858     // lay on the same side from the triangle plane.
1859
1860     bool manyInPlane = false; // more than 4 nodes lay in plane
1861     int iLoop2 = 0;
1862     while ( ++iLoop2 < 6 ) {
1863
1864       // get 1-2-3 plane coeffs
1865       Standard_Real A, B, C, D;
1866       gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1867       if ( N.SquareMagnitude() > gp::Resolution() )
1868       {
1869         gp_Pln pln ( P[0], N );
1870         pln.Coefficients( A, B, C, D );
1871
1872         // find the node (iMin) closest to pln
1873         Standard_Real dist[ 8 ], minDist = DBL_MAX;
1874         set<int> idInPln;
1875         for ( i = 3; i < 8; i++ ) {
1876           dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1877           if ( fabs( dist[i] ) < minDist ) {
1878             minDist = fabs( dist[i] );
1879             iMin = i;
1880           }
1881           if ( fabs( dist[i] ) <= tol )
1882             idInPln.insert( idNodes[i] );
1883         }
1884
1885         // there should not be more than 4 nodes in bottom plane
1886         if ( idInPln.size() > 1 )
1887         {
1888           DUMPSO( "### idInPln.size() = " << idInPln.size());
1889           // idInPlane does not contain the first 3 nodes
1890           if ( manyInPlane || idInPln.size() == 5)
1891             return false; // all nodes in one plane
1892           manyInPlane = true;
1893
1894           // set the 1-st node to be not in plane
1895           for ( i = 3; i < 8; i++ ) {
1896             if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1897               DUMPSO( "### Reset 0-th node");
1898               swap( 0, i, idNodes, P );
1899               break;
1900             }
1901           }
1902
1903           // reset to re-check second nodes
1904           leastDist = DBL_MAX;
1905           faceNodes.clear();
1906           checkedId1.clear();
1907           iLoop1 = 0;
1908           break; // from iLoop2;
1909         }
1910
1911         // check that the other 4 nodes are on the same side
1912         bool sameSide = true;
1913         bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1914         for ( i = 3; sameSide && i < 8; i++ ) {
1915           if ( i != iMin )
1916             sameSide = ( isNeg == dist[i] <= 0.);
1917         }
1918
1919         // keep best solution
1920         if ( sameSide && minDist < leastDist ) {
1921           leastDist = minDist;
1922           faceNodes.clear();
1923           faceNodes.insert( idNodes[ 1 ] );
1924           faceNodes.insert( idNodes[ 2 ] );
1925           faceNodes.insert( idNodes[ iMin ] );
1926           DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1927             << " leastDist = " << leastDist);
1928           if ( leastDist <= DBL_MIN )
1929             break;
1930         }
1931       }
1932
1933       // set next 3-d node to check
1934       int iNext = 2 + iLoop2;
1935       if ( iNext < 8 ) {
1936         DUMPSO( "Try 2-nd");
1937         swap ( 2, iNext, idNodes, P );
1938       }
1939     } // while ( iLoop2 < 6 )
1940   } // iLoop1
1941
1942   if ( faceNodes.empty() ) return false;
1943
1944   // Put the faceNodes in proper places
1945   for ( i = 4; i < 8; i++ ) {
1946     if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1947       // find a place to put
1948       int iTo = 1;
1949       while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1950         iTo++;
1951       DUMPSO( "Set faceNodes");
1952       swap ( iTo, i, idNodes, P );
1953     }
1954   }
1955
1956
1957   // Set nodes of the found bottom face in good order
1958   DUMPSO( " Found bottom face: ");
1959   i = SortQuadNodes( theMesh, idNodes );
1960   if ( i ) {
1961     gp_Pnt Ptmp = P[ i ];
1962     P[ i ] = P[ i+1 ];
1963     P[ i+1 ] = Ptmp;
1964   }
1965 //   else
1966 //     for ( int ii = 0; ii < 4; ii++ ) {
1967 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1968 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1969 //    }
1970
1971   // Gravity center of the top and bottom faces
1972   gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1973   gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1974
1975   // Get direction from the bottom to the top face
1976   gp_Vec upDir ( aGCb, aGCt );
1977   Standard_Real upDirSize = upDir.Magnitude();
1978   if ( upDirSize <= gp::Resolution() ) return false;
1979   upDir / upDirSize;
1980
1981   // Assure that the bottom face normal points up
1982   gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1983   Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1984   if ( Nb.Dot( upDir ) < 0 ) {
1985     DUMPSO( "Reverse bottom face");
1986     swap( 1, 3, idNodes, P );
1987   }
1988
1989   // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1990   Standard_Real minDist = DBL_MAX;
1991   for ( i = 4; i < 8; i++ ) {
1992     // projection of P[i] to the plane defined by P[0] and upDir
1993     gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1994     Standard_Real sqDist = P[0].SquareDistance( Pp );
1995     if ( sqDist < minDist ) {
1996       minDist = sqDist;
1997       iMin = i;
1998     }
1999   }
2000   DUMPSO( "Set 4-th");
2001   swap ( 4, iMin, idNodes, P );
2002
2003   // Set nodes of the top face in good order
2004   DUMPSO( "Sort top face");
2005   i = SortQuadNodes( theMesh, &idNodes[4] );
2006   if ( i ) {
2007     i += 4;
2008     gp_Pnt Ptmp = P[ i ];
2009     P[ i ] = P[ i+1 ];
2010     P[ i+1 ] = Ptmp;
2011   }
2012
2013   // Assure that direction of the top face normal is from the bottom face
2014   gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
2015   Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
2016   if ( Nt.Dot( upDir ) < 0 ) {
2017     DUMPSO( "Reverse top face");
2018     swap( 5, 7, idNodes, P );
2019   }
2020
2021 //   DUMPSO( "OUTPUT: ========================================");
2022 //   for ( i = 0; i < 8; i++ ) {
2023 //     float *p = ugrid->GetPoint(idNodes[i]);
2024 //     DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
2025 //   }
2026
2027   return true;
2028 }*/
2029
2030 //================================================================================
2031 /*!
2032  * \brief Return nodes linked to the given one
2033   * \param theNode - the node
2034   * \param linkedNodes - the found nodes
2035   * \param type - the type of elements to check
2036   *
2037   * Medium nodes are ignored
2038  */
2039 //================================================================================
2040
2041 void SMESH_MeshEditor::GetLinkedNodes( const SMDS_MeshNode* theNode,
2042                                        TIDSortedElemSet &   linkedNodes,
2043                                        SMDSAbs_ElementType  type )
2044 {
2045   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator(type);
2046   while ( elemIt->more() )
2047   {
2048     const SMDS_MeshElement* elem = elemIt->next();
2049     SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
2050     if ( elem->GetType() == SMDSAbs_Volume )
2051     {
2052       SMDS_VolumeTool vol( elem );
2053       while ( nodeIt->more() ) {
2054         const SMDS_MeshNode* n = cast2Node( nodeIt->next() );
2055         if ( theNode != n && vol.IsLinked( theNode, n ))
2056           linkedNodes.insert( n );
2057       }
2058     }
2059     else
2060     {
2061       for ( int i = 0; nodeIt->more(); ++i ) {
2062         const SMDS_MeshNode* n = cast2Node( nodeIt->next() );
2063         if ( n == theNode ) {
2064           int iBefore = i - 1;
2065           int iAfter  = i + 1;
2066           if ( elem->IsQuadratic() ) {
2067             int nb = elem->NbNodes() / 2;
2068             iAfter  = SMESH_MesherHelper::WrapIndex( iAfter, nb );
2069             iBefore = SMESH_MesherHelper::WrapIndex( iBefore, nb );
2070           }
2071           linkedNodes.insert( elem->GetNode( iAfter ));
2072           linkedNodes.insert( elem->GetNode( iBefore ));
2073         }
2074       }
2075     }
2076   }
2077 }
2078
2079 //=======================================================================
2080 //function : laplacianSmooth
2081 //purpose  : pulls theNode toward the center of surrounding nodes directly
2082 //           connected to that node along an element edge
2083 //=======================================================================
2084
2085 void laplacianSmooth(const SMDS_MeshNode*                 theNode,
2086                      const Handle(Geom_Surface)&          theSurface,
2087                      map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
2088 {
2089   // find surrounding nodes
2090
2091   TIDSortedElemSet nodeSet;
2092   SMESH_MeshEditor::GetLinkedNodes( theNode, nodeSet, SMDSAbs_Face );
2093
2094   // compute new coodrs
2095
2096   double coord[] = { 0., 0., 0. };
2097   TIDSortedElemSet::iterator nodeSetIt = nodeSet.begin();
2098   for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
2099     const SMDS_MeshNode* node = cast2Node(*nodeSetIt);
2100     if ( theSurface.IsNull() ) { // smooth in 3D
2101       coord[0] += node->X();
2102       coord[1] += node->Y();
2103       coord[2] += node->Z();
2104     }
2105     else { // smooth in 2D
2106       ASSERT( theUVMap.find( node ) != theUVMap.end() );
2107       gp_XY* uv = theUVMap[ node ];
2108       coord[0] += uv->X();
2109       coord[1] += uv->Y();
2110     }
2111   }
2112   int nbNodes = nodeSet.size();
2113   if ( !nbNodes )
2114     return;
2115   coord[0] /= nbNodes;
2116   coord[1] /= nbNodes;
2117
2118   if ( !theSurface.IsNull() ) {
2119     ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
2120     theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
2121     gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
2122     coord[0] = p3d.X();
2123     coord[1] = p3d.Y();
2124     coord[2] = p3d.Z();
2125   }
2126   else
2127     coord[2] /= nbNodes;
2128
2129   // move node
2130
2131   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
2132 }
2133
2134 //=======================================================================
2135 //function : centroidalSmooth
2136 //purpose  : pulls theNode toward the element-area-weighted centroid of the
2137 //           surrounding elements
2138 //=======================================================================
2139
2140 void centroidalSmooth(const SMDS_MeshNode*                 theNode,
2141                       const Handle(Geom_Surface)&          theSurface,
2142                       map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
2143 {
2144   gp_XYZ aNewXYZ(0.,0.,0.);
2145   SMESH::Controls::Area anAreaFunc;
2146   double totalArea = 0.;
2147   int nbElems = 0;
2148
2149   // compute new XYZ
2150
2151   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator(SMDSAbs_Face);
2152   while ( elemIt->more() )
2153   {
2154     const SMDS_MeshElement* elem = elemIt->next();
2155     nbElems++;
2156
2157     gp_XYZ elemCenter(0.,0.,0.);
2158     SMESH::Controls::TSequenceOfXYZ aNodePoints;
2159     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2160     int nn = elem->NbNodes();
2161     if(elem->IsQuadratic()) nn = nn/2;
2162     int i=0;
2163     //while ( itN->more() ) {
2164     while ( i<nn ) {
2165       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
2166       i++;
2167       gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
2168       aNodePoints.push_back( aP );
2169       if ( !theSurface.IsNull() ) { // smooth in 2D
2170         ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
2171         gp_XY* uv = theUVMap[ aNode ];
2172         aP.SetCoord( uv->X(), uv->Y(), 0. );
2173       }
2174       elemCenter += aP;
2175     }
2176     double elemArea = anAreaFunc.GetValue( aNodePoints );
2177     totalArea += elemArea;
2178     elemCenter /= nn;
2179     aNewXYZ += elemCenter * elemArea;
2180   }
2181   aNewXYZ /= totalArea;
2182   if ( !theSurface.IsNull() ) {
2183     theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
2184     aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
2185   }
2186
2187   // move node
2188
2189   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
2190 }
2191
2192 //=======================================================================
2193 //function : getClosestUV
2194 //purpose  : return UV of closest projection
2195 //=======================================================================
2196
2197 static bool getClosestUV (Extrema_GenExtPS& projector,
2198                           const gp_Pnt&     point,
2199                           gp_XY &           result)
2200 {
2201   projector.Perform( point );
2202   if ( projector.IsDone() ) {
2203     double u, v, minVal = DBL_MAX;
2204     for ( int i = projector.NbExt(); i > 0; i-- )
2205       if ( projector.Value( i ) < minVal ) {
2206         minVal = projector.Value( i );
2207         projector.Point( i ).Parameter( u, v );
2208       }
2209     result.SetCoord( u, v );
2210     return true;
2211   }
2212   return false;
2213 }
2214
2215 //=======================================================================
2216 //function : Smooth
2217 //purpose  : Smooth theElements during theNbIterations or until a worst
2218 //           element has aspect ratio <= theTgtAspectRatio.
2219 //           Aspect Ratio varies in range [1.0, inf].
2220 //           If theElements is empty, the whole mesh is smoothed.
2221 //           theFixedNodes contains additionally fixed nodes. Nodes built
2222 //           on edges and boundary nodes are always fixed.
2223 //=======================================================================
2224
2225 void SMESH_MeshEditor::Smooth (TIDSortedElemSet &          theElems,
2226                                set<const SMDS_MeshNode*> & theFixedNodes,
2227                                const SmoothMethod          theSmoothMethod,
2228                                const int                   theNbIterations,
2229                                double                      theTgtAspectRatio,
2230                                const bool                  the2D)
2231 {
2232   myLastCreatedElems.Clear();
2233   myLastCreatedNodes.Clear();
2234
2235   MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
2236
2237   if ( theTgtAspectRatio < 1.0 )
2238     theTgtAspectRatio = 1.0;
2239
2240   const double disttol = 1.e-16;
2241
2242   SMESH::Controls::AspectRatio aQualityFunc;
2243
2244   SMESHDS_Mesh* aMesh = GetMeshDS();
2245
2246   if ( theElems.empty() ) {
2247     // add all faces to theElems
2248     SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
2249     while ( fIt->more() ) {
2250       const SMDS_MeshElement* face = fIt->next();
2251       theElems.insert( face );
2252     }
2253   }
2254   // get all face ids theElems are on
2255   set< int > faceIdSet;
2256   TIDSortedElemSet::iterator itElem;
2257   if ( the2D )
2258     for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
2259       int fId = FindShape( *itElem );
2260       // check that corresponding submesh exists and a shape is face
2261       if (fId &&
2262           faceIdSet.find( fId ) == faceIdSet.end() &&
2263           aMesh->MeshElements( fId )) {
2264         TopoDS_Shape F = aMesh->IndexToShape( fId );
2265         if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
2266           faceIdSet.insert( fId );
2267       }
2268     }
2269   faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
2270
2271   // ===============================================
2272   // smooth elements on each TopoDS_Face separately
2273   // ===============================================
2274
2275   set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
2276   for ( ; fId != faceIdSet.rend(); ++fId ) {
2277     // get face surface and submesh
2278     Handle(Geom_Surface) surface;
2279     SMESHDS_SubMesh* faceSubMesh = 0;
2280     TopoDS_Face face;
2281     double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
2282     double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
2283     bool isUPeriodic = false, isVPeriodic = false;
2284     if ( *fId ) {
2285       face = TopoDS::Face( aMesh->IndexToShape( *fId ));
2286       surface = BRep_Tool::Surface( face );
2287       faceSubMesh = aMesh->MeshElements( *fId );
2288       fToler2 = BRep_Tool::Tolerance( face );
2289       fToler2 *= fToler2 * 10.;
2290       isUPeriodic = surface->IsUPeriodic();
2291       if ( isUPeriodic )
2292         vPeriod = surface->UPeriod();
2293       isVPeriodic = surface->IsVPeriodic();
2294       if ( isVPeriodic )
2295         uPeriod = surface->VPeriod();
2296       surface->Bounds( u1, u2, v1, v2 );
2297     }
2298     // ---------------------------------------------------------
2299     // for elements on a face, find movable and fixed nodes and
2300     // compute UV for them
2301     // ---------------------------------------------------------
2302     bool checkBoundaryNodes = false;
2303     bool isQuadratic = false;
2304     set<const SMDS_MeshNode*> setMovableNodes;
2305     map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
2306     list< gp_XY > listUV; // uvs the 2 uvMaps refer to
2307     list< const SMDS_MeshElement* > elemsOnFace;
2308
2309     Extrema_GenExtPS projector;
2310     GeomAdaptor_Surface surfAdaptor;
2311     if ( !surface.IsNull() ) {
2312       surfAdaptor.Load( surface );
2313       projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
2314     }
2315     int nbElemOnFace = 0;
2316     itElem = theElems.begin();
2317      // loop on not yet smoothed elements: look for elems on a face
2318     while ( itElem != theElems.end() ) {
2319       if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
2320         break; // all elements found
2321
2322       const SMDS_MeshElement* elem = *itElem;
2323       if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
2324           ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
2325         ++itElem;
2326         continue;
2327       }
2328       elemsOnFace.push_back( elem );
2329       theElems.erase( itElem++ );
2330       nbElemOnFace++;
2331
2332       if ( !isQuadratic )
2333         isQuadratic = elem->IsQuadratic();
2334
2335       // get movable nodes of elem
2336       const SMDS_MeshNode* node;
2337       SMDS_TypeOfPosition posType;
2338       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2339       int nn = 0, nbn =  elem->NbNodes();
2340       if(elem->IsQuadratic())
2341         nbn = nbn/2;
2342       while ( nn++ < nbn ) {
2343         node = static_cast<const SMDS_MeshNode*>( itN->next() );
2344         const SMDS_PositionPtr& pos = node->GetPosition();
2345         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
2346         if (posType != SMDS_TOP_EDGE &&
2347             posType != SMDS_TOP_VERTEX &&
2348             theFixedNodes.find( node ) == theFixedNodes.end())
2349         {
2350           // check if all faces around the node are on faceSubMesh
2351           // because a node on edge may be bound to face
2352           SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Face);
2353           bool all = true;
2354           if ( faceSubMesh ) {
2355             while ( eIt->more() && all ) {
2356               const SMDS_MeshElement* e = eIt->next();
2357               all = faceSubMesh->Contains( e );
2358             }
2359           }
2360           if ( all )
2361             setMovableNodes.insert( node );
2362           else
2363             checkBoundaryNodes = true;
2364         }
2365         if ( posType == SMDS_TOP_3DSPACE )
2366           checkBoundaryNodes = true;
2367       }
2368
2369       if ( surface.IsNull() )
2370         continue;
2371
2372       // get nodes to check UV
2373       list< const SMDS_MeshNode* > uvCheckNodes;
2374       itN = elem->nodesIterator();
2375       nn = 0; nbn =  elem->NbNodes();
2376       if(elem->IsQuadratic())
2377         nbn = nbn/2;
2378       while ( nn++ < nbn ) {
2379         node = static_cast<const SMDS_MeshNode*>( itN->next() );
2380         if ( uvMap.find( node ) == uvMap.end() )
2381           uvCheckNodes.push_back( node );
2382         // add nodes of elems sharing node
2383 //         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Face);
2384 //         while ( eIt->more() ) {
2385 //           const SMDS_MeshElement* e = eIt->next();
2386 //           if ( e != elem ) {
2387 //             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2388 //             while ( nIt->more() ) {
2389 //               const SMDS_MeshNode* n =
2390 //                 static_cast<const SMDS_MeshNode*>( nIt->next() );
2391 //               if ( uvMap.find( n ) == uvMap.end() )
2392 //                 uvCheckNodes.push_back( n );
2393 //             }
2394 //           }
2395 //         }
2396       }
2397       // check UV on face
2398       list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
2399       for ( ; n != uvCheckNodes.end(); ++n ) {
2400         node = *n;
2401         gp_XY uv( 0, 0 );
2402         const SMDS_PositionPtr& pos = node->GetPosition();
2403         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
2404         // get existing UV
2405         switch ( posType ) {
2406         case SMDS_TOP_FACE: {
2407           SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
2408           uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
2409           break;
2410         }
2411         case SMDS_TOP_EDGE: {
2412           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
2413           Handle(Geom2d_Curve) pcurve;
2414           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
2415             pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
2416           if ( !pcurve.IsNull() ) {
2417             double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
2418             uv = pcurve->Value( u ).XY();
2419           }
2420           break;
2421         }
2422         case SMDS_TOP_VERTEX: {
2423           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
2424           if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
2425             uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
2426           break;
2427         }
2428         default:;
2429         }
2430         // check existing UV
2431         bool project = true;
2432         gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
2433         double dist1 = DBL_MAX, dist2 = 0;
2434         if ( posType != SMDS_TOP_3DSPACE ) {
2435           dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
2436           project = dist1 > fToler2;
2437         }
2438         if ( project ) { // compute new UV
2439           gp_XY newUV;
2440           if ( !getClosestUV( projector, pNode, newUV )) {
2441             MESSAGE("Node Projection Failed " << node);
2442           }
2443           else {
2444             if ( isUPeriodic )
2445               newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
2446             if ( isVPeriodic )
2447               newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
2448             // check new UV
2449             if ( posType != SMDS_TOP_3DSPACE )
2450               dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
2451             if ( dist2 < dist1 )
2452               uv = newUV;
2453           }
2454         }
2455         // store UV in the map
2456         listUV.push_back( uv );
2457         uvMap.insert( make_pair( node, &listUV.back() ));
2458       }
2459     } // loop on not yet smoothed elements
2460
2461     if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
2462       checkBoundaryNodes = true;
2463
2464     // fix nodes on mesh boundary
2465
2466     if ( checkBoundaryNodes ) {
2467       typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
2468       map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
2469       map< TLink, int >::iterator link_nb;
2470       // put all elements links to linkNbMap
2471       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
2472       for ( ; elemIt != elemsOnFace.end(); ++elemIt ) {
2473         const SMDS_MeshElement* elem = (*elemIt);
2474         int nbn =  elem->NbNodes();
2475         if(elem->IsQuadratic())
2476           nbn = nbn/2;
2477         // loop on elem links: insert them in linkNbMap
2478         const SMDS_MeshNode* curNode, *prevNode = elem->GetNode( nbn );
2479         for ( int iN = 0; iN < nbn; ++iN ) {
2480           curNode = elem->GetNode( iN );
2481           TLink link;
2482           if ( curNode < prevNode ) link = make_pair( curNode , prevNode );
2483           else                      link = make_pair( prevNode , curNode );
2484           prevNode = curNode;
2485           link_nb = linkNbMap.find( link );
2486           if ( link_nb == linkNbMap.end() )
2487             linkNbMap.insert( make_pair ( link, 1 ));
2488           else
2489             link_nb->second++;
2490         }
2491       }
2492       // remove nodes that are in links encountered only once from setMovableNodes
2493       for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
2494         if ( link_nb->second == 1 ) {
2495           setMovableNodes.erase( link_nb->first.first );
2496           setMovableNodes.erase( link_nb->first.second );
2497         }
2498       }
2499     }
2500
2501     // -----------------------------------------------------
2502     // for nodes on seam edge, compute one more UV ( uvMap2 );
2503     // find movable nodes linked to nodes on seam and which
2504     // are to be smoothed using the second UV ( uvMap2 )
2505     // -----------------------------------------------------
2506
2507     set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
2508     if ( !surface.IsNull() ) {
2509       TopExp_Explorer eExp( face, TopAbs_EDGE );
2510       for ( ; eExp.More(); eExp.Next() ) {
2511         TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
2512         if ( !BRep_Tool::IsClosed( edge, face ))
2513           continue;
2514         SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
2515         if ( !sm ) continue;
2516         // find out which parameter varies for a node on seam
2517         double f,l;
2518         gp_Pnt2d uv1, uv2;
2519         Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
2520         if ( pcurve.IsNull() ) continue;
2521         uv1 = pcurve->Value( f );
2522         edge.Reverse();
2523         pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
2524         if ( pcurve.IsNull() ) continue;
2525         uv2 = pcurve->Value( f );
2526         int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
2527         // assure uv1 < uv2
2528         if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
2529           gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
2530         }
2531         // get nodes on seam and its vertices
2532         list< const SMDS_MeshNode* > seamNodes;
2533         SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
2534         while ( nSeamIt->more() ) {
2535           const SMDS_MeshNode* node = nSeamIt->next();
2536           if ( !isQuadratic || !IsMedium( node ))
2537             seamNodes.push_back( node );
2538         }
2539         TopExp_Explorer vExp( edge, TopAbs_VERTEX );
2540         for ( ; vExp.More(); vExp.Next() ) {
2541           sm = aMesh->MeshElements( vExp.Current() );
2542           if ( sm ) {
2543             nSeamIt = sm->GetNodes();
2544             while ( nSeamIt->more() )
2545               seamNodes.push_back( nSeamIt->next() );
2546           }
2547         }
2548         // loop on nodes on seam
2549         list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
2550         for ( ; noSeIt != seamNodes.end(); ++noSeIt ) {
2551           const SMDS_MeshNode* nSeam = *noSeIt;
2552           map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
2553           if ( n_uv == uvMap.end() )
2554             continue;
2555           // set the first UV
2556           n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
2557           // set the second UV
2558           listUV.push_back( *n_uv->second );
2559           listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
2560           if ( uvMap2.empty() )
2561             uvMap2 = uvMap; // copy the uvMap contents
2562           uvMap2[ nSeam ] = &listUV.back();
2563
2564           // collect movable nodes linked to ones on seam in nodesNearSeam
2565           SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator(SMDSAbs_Face);
2566           while ( eIt->more() ) {
2567             const SMDS_MeshElement* e = eIt->next();
2568             int nbUseMap1 = 0, nbUseMap2 = 0;
2569             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2570             int nn = 0, nbn =  e->NbNodes();
2571             if(e->IsQuadratic()) nbn = nbn/2;
2572             while ( nn++ < nbn )
2573             {
2574               const SMDS_MeshNode* n =
2575                 static_cast<const SMDS_MeshNode*>( nIt->next() );
2576               if (n == nSeam ||
2577                   setMovableNodes.find( n ) == setMovableNodes.end() )
2578                 continue;
2579               // add only nodes being closer to uv2 than to uv1
2580               gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
2581                            0.5 * ( n->Y() + nSeam->Y() ),
2582                            0.5 * ( n->Z() + nSeam->Z() ));
2583               gp_XY uv;
2584               getClosestUV( projector, pMid, uv );
2585               if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
2586                 nodesNearSeam.insert( n );
2587                 nbUseMap2++;
2588               }
2589               else
2590                 nbUseMap1++;
2591             }
2592             // for centroidalSmooth all element nodes must
2593             // be on one side of a seam
2594             if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 ) {
2595               SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2596               nn = 0;
2597               while ( nn++ < nbn ) {
2598                 const SMDS_MeshNode* n =
2599                   static_cast<const SMDS_MeshNode*>( nIt->next() );
2600                 setMovableNodes.erase( n );
2601               }
2602             }
2603           }
2604         } // loop on nodes on seam
2605       } // loop on edge of a face
2606     } // if ( !face.IsNull() )
2607
2608     if ( setMovableNodes.empty() ) {
2609       MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
2610       continue; // goto next face
2611     }
2612
2613     // -------------
2614     // SMOOTHING //
2615     // -------------
2616
2617     int it = -1;
2618     double maxRatio = -1., maxDisplacement = -1.;
2619     set<const SMDS_MeshNode*>::iterator nodeToMove;
2620     for ( it = 0; it < theNbIterations; it++ ) {
2621       maxDisplacement = 0.;
2622       nodeToMove = setMovableNodes.begin();
2623       for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ ) {
2624         const SMDS_MeshNode* node = (*nodeToMove);
2625         gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
2626
2627         // smooth
2628         bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
2629         if ( theSmoothMethod == LAPLACIAN )
2630           laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
2631         else
2632           centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
2633
2634         // node displacement
2635         gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
2636         Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
2637         if ( aDispl > maxDisplacement )
2638           maxDisplacement = aDispl;
2639       }
2640       // no node movement => exit
2641       //if ( maxDisplacement < 1.e-16 ) {
2642       if ( maxDisplacement < disttol ) {
2643         MESSAGE("-- no node movement --");
2644         break;
2645       }
2646
2647       // check elements quality
2648       maxRatio  = 0;
2649       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
2650       for ( ; elemIt != elemsOnFace.end(); ++elemIt ) {
2651         const SMDS_MeshElement* elem = (*elemIt);
2652         if ( !elem || elem->GetType() != SMDSAbs_Face )
2653           continue;
2654         SMESH::Controls::TSequenceOfXYZ aPoints;
2655         if ( aQualityFunc.GetPoints( elem, aPoints )) {
2656           double aValue = aQualityFunc.GetValue( aPoints );
2657           if ( aValue > maxRatio )
2658             maxRatio = aValue;
2659         }
2660       }
2661       if ( maxRatio <= theTgtAspectRatio ) {
2662         MESSAGE("-- quality achived --");
2663         break;
2664       }
2665       if (it+1 == theNbIterations) {
2666         MESSAGE("-- Iteration limit exceeded --");
2667       }
2668     } // smoothing iterations
2669
2670     MESSAGE(" Face id: " << *fId <<
2671             " Nb iterstions: " << it <<
2672             " Displacement: " << maxDisplacement <<
2673             " Aspect Ratio " << maxRatio);
2674
2675     // ---------------------------------------
2676     // new nodes positions are computed,
2677     // record movement in DS and set new UV
2678     // ---------------------------------------
2679     nodeToMove = setMovableNodes.begin();
2680     for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ ) {
2681       SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
2682       aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
2683       map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
2684       if ( node_uv != uvMap.end() ) {
2685         gp_XY* uv = node_uv->second;
2686         node->SetPosition
2687           ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
2688       }
2689     }
2690
2691     // move medium nodes of quadratic elements
2692     if ( isQuadratic )
2693     {
2694       SMESH_MesherHelper helper( *GetMesh() );
2695       if ( !face.IsNull() )
2696         helper.SetSubShape( face );
2697       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
2698       for ( ; elemIt != elemsOnFace.end(); ++elemIt ) {
2699         const SMDS_QuadraticFaceOfNodes* QF =
2700           dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (*elemIt);
2701         if(QF) {
2702           vector<const SMDS_MeshNode*> Ns;
2703           Ns.reserve(QF->NbNodes()+1);
2704           SMDS_NodeIteratorPtr anIter = QF->interlacedNodesIterator();
2705           while ( anIter->more() )
2706             Ns.push_back( anIter->next() );
2707           Ns.push_back( Ns[0] );
2708           double x, y, z;
2709           for(int i=0; i<QF->NbNodes(); i=i+2) {
2710             if ( !surface.IsNull() ) {
2711               gp_XY uv1 = helper.GetNodeUV( face, Ns[i], Ns[i+2] );
2712               gp_XY uv2 = helper.GetNodeUV( face, Ns[i+2], Ns[i] );
2713               gp_XY uv = ( uv1 + uv2 ) / 2.;
2714               gp_Pnt xyz = surface->Value( uv.X(), uv.Y() );
2715               x = xyz.X(); y = xyz.Y(); z = xyz.Z();
2716             }
2717             else {
2718               x = (Ns[i]->X() + Ns[i+2]->X())/2;
2719               y = (Ns[i]->Y() + Ns[i+2]->Y())/2;
2720               z = (Ns[i]->Z() + Ns[i+2]->Z())/2;
2721             }
2722             if( fabs( Ns[i+1]->X() - x ) > disttol ||
2723                 fabs( Ns[i+1]->Y() - y ) > disttol ||
2724                 fabs( Ns[i+1]->Z() - z ) > disttol ) {
2725               // we have to move i+1 node
2726               aMesh->MoveNode( Ns[i+1], x, y, z );
2727             }
2728           }
2729         }
2730       }
2731     }
2732
2733   } // loop on face ids
2734
2735 }
2736
2737 //=======================================================================
2738 //function : isReverse
2739 //purpose  : Return true if normal of prevNodes is not co-directied with
2740 //           gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
2741 //           iNotSame is where prevNodes and nextNodes are different
2742 //=======================================================================
2743
2744 static bool isReverse(vector<const SMDS_MeshNode*> prevNodes,
2745                       vector<const SMDS_MeshNode*> nextNodes,
2746                       const int            nbNodes,
2747                       const int            iNotSame)
2748 {
2749   int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
2750   int iAfterNotSame  = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
2751
2752   const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
2753   const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
2754   const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
2755   const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
2756
2757   gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
2758   gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
2759   gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
2760   gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
2761
2762   gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
2763
2764   return (vA ^ vB) * vN < 0.0;
2765 }
2766
2767 //=======================================================================
2768 /*!
2769  * \brief Create elements by sweeping an element
2770  * \param elem - element to sweep
2771  * \param newNodesItVec - nodes generated from each node of the element
2772  * \param newElems - generated elements
2773  * \param nbSteps - number of sweeping steps
2774  * \param srcElements - to append elem for each generated element
2775  */
2776 //=======================================================================
2777
2778 void SMESH_MeshEditor::sweepElement(const SMDS_MeshElement*               elem,
2779                                     const vector<TNodeOfNodeListMapItr> & newNodesItVec,
2780                                     list<const SMDS_MeshElement*>&        newElems,
2781                                     const int                             nbSteps,
2782                                     SMESH_SequenceOfElemPtr&              srcElements)
2783 {
2784   SMESHDS_Mesh* aMesh = GetMeshDS();
2785
2786   // Loop on elem nodes:
2787   // find new nodes and detect same nodes indices
2788   int nbNodes = elem->NbNodes();
2789   vector < list< const SMDS_MeshNode* >::const_iterator > itNN( nbNodes );
2790   vector<const SMDS_MeshNode*> prevNod( nbNodes );
2791   vector<const SMDS_MeshNode*> nextNod( nbNodes );
2792   vector<const SMDS_MeshNode*> midlNod( nbNodes );
2793
2794   int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
2795   vector<int> sames(nbNodes);
2796
2797   //bool issimple[nbNodes];
2798   vector<bool> issimple(nbNodes);
2799
2800   for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2801     TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
2802     const SMDS_MeshNode*                 node         = nnIt->first;
2803     const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
2804     if ( listNewNodes.empty() )
2805       return;
2806
2807     if(listNewNodes.size()==nbSteps) {
2808       issimple[iNode] = true;
2809     }
2810     else {
2811       issimple[iNode] = false;
2812     }
2813
2814     itNN[ iNode ] = listNewNodes.begin();
2815     prevNod[ iNode ] = node;
2816     nextNod[ iNode ] = listNewNodes.front();
2817 //cout<<"iNode="<<iNode<<endl;
2818 //cout<<" prevNod[iNode]="<< prevNod[iNode]<<" nextNod[iNode]="<< nextNod[iNode]<<endl;
2819     if ( prevNod[ iNode ] != nextNod [ iNode ])
2820       iNotSameNode = iNode;
2821     else {
2822       iSameNode = iNode;
2823       //nbSame++;
2824       sames[nbSame++] = iNode;
2825     }
2826   }
2827 //cout<<"1 nbSame="<<nbSame<<endl;
2828   if ( nbSame == nbNodes || nbSame > 2) {
2829     MESSAGE( " Too many same nodes of element " << elem->GetID() );
2830     return;
2831   }
2832
2833 //  if( elem->IsQuadratic() && nbSame>0 ) {
2834 //    MESSAGE( "Can not rotate quadratic element " << elem->GetID() );
2835 //    return;
2836 //  }
2837
2838   int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
2839   if ( nbSame > 0 ) {
2840     iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
2841     iAfterSame  = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2842     iOpposSame  = ( iSameNode - 2 < 0  ? iSameNode + 2 : iSameNode - 2 );
2843   }
2844
2845 //if(nbNodes==8)
2846 //cout<<" prevNod[0]="<< prevNod[0]<<" prevNod[1]="<< prevNod[1]
2847 //    <<" prevNod[2]="<< prevNod[2]<<" prevNod[3]="<< prevNod[4]
2848 //    <<" prevNod[4]="<< prevNod[4]<<" prevNod[5]="<< prevNod[5]
2849 //    <<" prevNod[6]="<< prevNod[6]<<" prevNod[7]="<< prevNod[7]<<endl;
2850
2851   // check element orientation
2852   int i0 = 0, i2 = 2;
2853   if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2854     //MESSAGE("Reversed elem " << elem );
2855     i0 = 2;
2856     i2 = 0;
2857     if ( nbSame > 0 ) {
2858       int iAB = iAfterSame + iBeforeSame;
2859       iBeforeSame = iAB - iBeforeSame;
2860       iAfterSame  = iAB - iAfterSame;
2861     }
2862   }
2863
2864   // make new elements
2865   for (int iStep = 0; iStep < nbSteps; iStep++ ) {
2866     // get next nodes
2867     for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2868       if(issimple[iNode]) {
2869         nextNod[ iNode ] = *itNN[ iNode ];
2870         itNN[ iNode ]++;
2871       }
2872       else {
2873         if( elem->GetType()==SMDSAbs_Node ) {
2874           // we have to use two nodes
2875           midlNod[ iNode ] = *itNN[ iNode ];
2876           itNN[ iNode ]++;
2877           nextNod[ iNode ] = *itNN[ iNode ];
2878           itNN[ iNode ]++;
2879         }
2880         else if(!elem->IsQuadratic() ||
2881            elem->IsQuadratic() && elem->IsMediumNode(prevNod[iNode]) ) {
2882           // we have to use each second node
2883           itNN[ iNode ]++;
2884           nextNod[ iNode ] = *itNN[ iNode ];
2885           itNN[ iNode ]++;
2886         }
2887         else {
2888           // we have to use two nodes
2889           midlNod[ iNode ] = *itNN[ iNode ];
2890           itNN[ iNode ]++;
2891           nextNod[ iNode ] = *itNN[ iNode ];
2892           itNN[ iNode ]++;
2893         }
2894       }
2895     }
2896     SMDS_MeshElement* aNewElem = 0;
2897     if(!elem->IsPoly()) {
2898       switch ( nbNodes ) {
2899       case 0:
2900         return;
2901       case 1: { // NODE
2902         if ( nbSame == 0 ) {
2903           if(issimple[0])
2904             aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2905           else
2906             aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ], midlNod[ 0 ] );
2907         }
2908         break;
2909       }
2910       case 2: { // EDGE
2911         if ( nbSame == 0 )
2912           aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2913                                     nextNod[ 1 ], nextNod[ 0 ] );
2914         else
2915           aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2916                                     nextNod[ iNotSameNode ] );
2917         break;
2918       }
2919
2920       case 3: { // TRIANGLE or quadratic edge
2921         if(elem->GetType() == SMDSAbs_Face) { // TRIANGLE
2922
2923           if ( nbSame == 0 )       // --- pentahedron
2924             aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2925                                          nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2926
2927           else if ( nbSame == 1 )  // --- pyramid
2928             aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2929                                          nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2930                                          nextNod[ iSameNode ]);
2931
2932           else // 2 same nodes:      --- tetrahedron
2933             aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2934                                          nextNod[ iNotSameNode ]);
2935         }
2936         else { // quadratic edge
2937           if(nbSame==0) {     // quadratic quadrangle
2938             aNewElem = aMesh->AddFace(prevNod[0], nextNod[0], nextNod[1], prevNod[1],
2939                                       midlNod[0], nextNod[2], midlNod[1], prevNod[2]);
2940           }
2941           else if(nbSame==1) { // quadratic triangle
2942             if(sames[0]==2)
2943               return; // medium node on axis
2944             else if(sames[0]==0) {
2945               aNewElem = aMesh->AddFace(prevNod[0], nextNod[1], prevNod[1],
2946                                         nextNod[2], midlNod[1], prevNod[2]);
2947             }
2948             else { // sames[0]==1
2949               aNewElem = aMesh->AddFace(prevNod[0], nextNod[0], prevNod[1],
2950                                         midlNod[0], nextNod[2], prevNod[2]);
2951             }
2952           }
2953           else
2954             return;
2955         }
2956         break;
2957       }
2958       case 4: { // QUADRANGLE
2959
2960         if ( nbSame == 0 )       // --- hexahedron
2961           aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2962                                        nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2963
2964         else if ( nbSame == 1 ) { // --- pyramid + pentahedron
2965           aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2966                                        nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2967                                        nextNod[ iSameNode ]);
2968           newElems.push_back( aNewElem );
2969           aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2970                                        prevNod[ iBeforeSame ],  nextNod[ iAfterSame ],
2971                                        nextNod[ iOpposSame ],  nextNod[ iBeforeSame ] );
2972         }
2973         else if ( nbSame == 2 ) { // pentahedron
2974           if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2975             // iBeforeSame is same too
2976             aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2977                                          nextNod[ iOpposSame ], prevNod[ iSameNode ],
2978                                          prevNod[ iAfterSame ],  nextNod[ iAfterSame ]);
2979           else
2980             // iAfterSame is same too
2981             aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2982                                          nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2983                                          prevNod[ iOpposSame ],  nextNod[ iOpposSame ]);
2984         }
2985         break;
2986       }
2987       case 6: { // quadratic triangle
2988         // create pentahedron with 15 nodes
2989         if(i0>0) { // reversed case
2990           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[2], prevNod[1],
2991                                        nextNod[0], nextNod[2], nextNod[1],
2992                                        prevNod[5], prevNod[4], prevNod[3],
2993                                        nextNod[5], nextNod[4], nextNod[3],
2994                                        midlNod[0], midlNod[2], midlNod[1]);
2995         }
2996         else { // not reversed case
2997           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[1], prevNod[2],
2998                                        nextNod[0], nextNod[1], nextNod[2],
2999                                        prevNod[3], prevNod[4], prevNod[5],
3000                                        nextNod[3], nextNod[4], nextNod[5],
3001                                        midlNod[0], midlNod[1], midlNod[2]);
3002         }
3003         break;
3004       }
3005       case 8: { // quadratic quadrangle
3006         // create hexahedron with 20 nodes
3007         if(i0>0) { // reversed case
3008           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[3], prevNod[2], prevNod[1],
3009                                        nextNod[0], nextNod[3], nextNod[2], nextNod[1],
3010                                        prevNod[7], prevNod[6], prevNod[5], prevNod[4],
3011                                        nextNod[7], nextNod[6], nextNod[5], nextNod[4],
3012                                        midlNod[0], midlNod[3], midlNod[2], midlNod[1]);
3013         }
3014         else { // not reversed case
3015           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[1], prevNod[2], prevNod[3],
3016                                        nextNod[0], nextNod[1], nextNod[2], nextNod[3],
3017                                        prevNod[4], prevNod[5], prevNod[6], prevNod[7],
3018                                        nextNod[4], nextNod[5], nextNod[6], nextNod[7],
3019                                        midlNod[0], midlNod[1], midlNod[2], midlNod[3]);
3020         }
3021         break;
3022       }
3023       default: {
3024         // realized for extrusion only
3025         //vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
3026         //vector<int> quantities (nbNodes + 2);
3027
3028         //quantities[0] = nbNodes; // bottom of prism
3029         //for (int inode = 0; inode < nbNodes; inode++) {
3030         //  polyedre_nodes[inode] = prevNod[inode];
3031         //}
3032
3033         //quantities[1] = nbNodes; // top of prism
3034         //for (int inode = 0; inode < nbNodes; inode++) {
3035         //  polyedre_nodes[nbNodes + inode] = nextNod[inode];
3036         //}
3037
3038         //for (int iface = 0; iface < nbNodes; iface++) {
3039         //  quantities[iface + 2] = 4;
3040         //  int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
3041         //  polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
3042         //  polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
3043         //  polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
3044         //  polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
3045         //}
3046         //aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
3047         break;
3048       }
3049       }
3050     }
3051
3052     if(!aNewElem) {
3053       // realized for extrusion only
3054       vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
3055       vector<int> quantities (nbNodes + 2);
3056
3057       quantities[0] = nbNodes; // bottom of prism
3058       for (int inode = 0; inode < nbNodes; inode++) {
3059         polyedre_nodes[inode] = prevNod[inode];
3060       }
3061
3062       quantities[1] = nbNodes; // top of prism
3063       for (int inode = 0; inode < nbNodes; inode++) {
3064         polyedre_nodes[nbNodes + inode] = nextNod[inode];
3065       }
3066
3067       for (int iface = 0; iface < nbNodes; iface++) {
3068         quantities[iface + 2] = 4;
3069         int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
3070         polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
3071         polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
3072         polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
3073         polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
3074       }
3075       aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
3076     }
3077
3078     if ( aNewElem ) {
3079       newElems.push_back( aNewElem );
3080       myLastCreatedElems.Append(aNewElem);
3081       srcElements.Append( elem );
3082     }
3083
3084     // set new prev nodes
3085     for ( iNode = 0; iNode < nbNodes; iNode++ )
3086       prevNod[ iNode ] = nextNod[ iNode ];
3087
3088   } // for steps
3089 }
3090
3091 //=======================================================================
3092 /*!
3093  * \brief Create 1D and 2D elements around swept elements
3094  * \param mapNewNodes - source nodes and ones generated from them
3095  * \param newElemsMap - source elements and ones generated from them
3096  * \param elemNewNodesMap - nodes generated from each node of each element
3097  * \param elemSet - all swept elements
3098  * \param nbSteps - number of sweeping steps
3099  * \param srcElements - to append elem for each generated element
3100  */
3101 //=======================================================================
3102
3103 void SMESH_MeshEditor::makeWalls (TNodeOfNodeListMap &     mapNewNodes,
3104                                   TElemOfElemListMap &     newElemsMap,
3105                                   TElemOfVecOfNnlmiMap &   elemNewNodesMap,
3106                                   TIDSortedElemSet&        elemSet,
3107                                   const int                nbSteps,
3108                                   SMESH_SequenceOfElemPtr& srcElements)
3109 {
3110   ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
3111   SMESHDS_Mesh* aMesh = GetMeshDS();
3112
3113   // Find nodes belonging to only one initial element - sweep them to get edges.
3114
3115   TNodeOfNodeListMapItr nList = mapNewNodes.begin();
3116   for ( ; nList != mapNewNodes.end(); nList++ ) {
3117     const SMDS_MeshNode* node =
3118       static_cast<const SMDS_MeshNode*>( nList->first );
3119     SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3120     int nbInitElems = 0;
3121     const SMDS_MeshElement* el = 0;
3122     SMDSAbs_ElementType highType = SMDSAbs_Edge; // count most complex elements only
3123     while ( eIt->more() && nbInitElems < 2 ) {
3124       el = eIt->next();
3125       SMDSAbs_ElementType type = el->GetType();
3126       if ( type == SMDSAbs_Volume || type < highType ) continue;
3127       if ( type > highType ) {
3128         nbInitElems = 0;
3129         highType = type;
3130       }
3131       if ( elemSet.find(el) != elemSet.end() )
3132         nbInitElems++;
3133     }
3134     if ( nbInitElems < 2 ) {
3135       bool NotCreateEdge = el && el->IsQuadratic() && el->IsMediumNode(node);
3136       if(!NotCreateEdge) {
3137         vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
3138         list<const SMDS_MeshElement*> newEdges;
3139         sweepElement( node, newNodesItVec, newEdges, nbSteps, srcElements );
3140       }
3141     }
3142   }
3143
3144   // Make a ceiling for each element ie an equal element of last new nodes.
3145   // Find free links of faces - make edges and sweep them into faces.
3146
3147   TElemOfElemListMap::iterator   itElem      = newElemsMap.begin();
3148   TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
3149   for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ ) {
3150     const SMDS_MeshElement* elem = itElem->first;
3151     vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
3152
3153     if ( elem->GetType() == SMDSAbs_Edge ) {
3154       // create a ceiling edge
3155       if (!elem->IsQuadratic()) {
3156         if ( !aMesh->FindEdge( vecNewNodes[ 0 ]->second.back(),
3157                                vecNewNodes[ 1 ]->second.back())) {
3158           myLastCreatedElems.Append(aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
3159                                                    vecNewNodes[ 1 ]->second.back()));
3160           srcElements.Append( myLastCreatedElems.Last() );
3161         }
3162       }
3163       else {
3164         if ( !aMesh->FindEdge( vecNewNodes[ 0 ]->second.back(),
3165                                vecNewNodes[ 1 ]->second.back(),
3166                                vecNewNodes[ 2 ]->second.back())) {
3167           myLastCreatedElems.Append(aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
3168                                                    vecNewNodes[ 1 ]->second.back(),
3169                                                    vecNewNodes[ 2 ]->second.back()));
3170           srcElements.Append( myLastCreatedElems.Last() );
3171         }
3172       }
3173     }
3174     if ( elem->GetType() != SMDSAbs_Face )
3175       continue;
3176
3177     if(itElem->second.size()==0) continue;
3178
3179     bool hasFreeLinks = false;
3180
3181     TIDSortedElemSet avoidSet;
3182     avoidSet.insert( elem );
3183
3184     set<const SMDS_MeshNode*> aFaceLastNodes;
3185     int iNode, nbNodes = vecNewNodes.size();
3186     if(!elem->IsQuadratic()) {
3187       // loop on the face nodes
3188       for ( iNode = 0; iNode < nbNodes; iNode++ ) {
3189         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3190         // look for free links of the face
3191         int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
3192         const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
3193         const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
3194         // check if a link is free
3195         if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet )) {
3196           hasFreeLinks = true;
3197           // make an edge and a ceiling for a new edge
3198           if ( !aMesh->FindEdge( n1, n2 )) {
3199             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2 )); // free link edge
3200             srcElements.Append( myLastCreatedElems.Last() );
3201           }
3202           n1 = vecNewNodes[ iNode ]->second.back();
3203           n2 = vecNewNodes[ iNext ]->second.back();
3204           if ( !aMesh->FindEdge( n1, n2 )) {
3205             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2 )); // ceiling edge
3206             srcElements.Append( myLastCreatedElems.Last() );
3207           }
3208         }
3209       }
3210     }
3211     else { // elem is quadratic face
3212       int nbn = nbNodes/2;
3213       for ( iNode = 0; iNode < nbn; iNode++ ) {
3214         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3215         int iNext = ( iNode + 1 == nbn ) ? 0 : iNode + 1;
3216         const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
3217         const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
3218         // check if a link is free
3219         if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet )) {
3220           hasFreeLinks = true;
3221           // make an edge and a ceiling for a new edge
3222           // find medium node
3223           const SMDS_MeshNode* n3 = vecNewNodes[ iNode+nbn ]->first;
3224           if ( !aMesh->FindEdge( n1, n2, n3 )) {
3225             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2, n3 )); // free link edge
3226             srcElements.Append( myLastCreatedElems.Last() );
3227           }
3228           n1 = vecNewNodes[ iNode ]->second.back();
3229           n2 = vecNewNodes[ iNext ]->second.back();
3230           n3 = vecNewNodes[ iNode+nbn ]->second.back();
3231           if ( !aMesh->FindEdge( n1, n2, n3 )) {
3232             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2, n3 )); // ceiling edge
3233             srcElements.Append( myLastCreatedElems.Last() );
3234           }
3235         }
3236       }
3237       for ( iNode = nbn; iNode < 2*nbn; iNode++ ) {
3238         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3239       }
3240     }
3241
3242     // sweep free links into faces
3243
3244     if ( hasFreeLinks )  {
3245       list<const SMDS_MeshElement*> & newVolumes = itElem->second;
3246       int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
3247
3248       set<const SMDS_MeshNode*> initNodeSet, topNodeSet, faceNodeSet;
3249       for ( iNode = 0; iNode < nbNodes; iNode++ ) {
3250         initNodeSet.insert( vecNewNodes[ iNode ]->first );
3251         topNodeSet .insert( vecNewNodes[ iNode ]->second.back() );
3252       }
3253       for ( volNb = 0; volNb < nbVolumesByStep; volNb++ ) {
3254         list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
3255         iVol = 0;
3256         while ( iVol++ < volNb ) v++;
3257         // find indices of free faces of a volume and their source edges
3258         list< int > freeInd;
3259         list< const SMDS_MeshElement* > srcEdges; // source edges of free faces
3260         SMDS_VolumeTool vTool( *v );
3261         int iF, nbF = vTool.NbFaces();
3262         for ( iF = 0; iF < nbF; iF ++ ) {
3263           if (vTool.IsFreeFace( iF ) &&
3264               vTool.GetFaceNodes( iF, faceNodeSet ) &&
3265               initNodeSet != faceNodeSet) // except an initial face
3266           {
3267             if ( nbSteps == 1 && faceNodeSet == topNodeSet )
3268               continue;
3269             freeInd.push_back( iF );
3270             // find source edge of a free face iF
3271             vector<const SMDS_MeshNode*> commonNodes; // shared by the initial and free faces
3272             commonNodes.resize( initNodeSet.size(), NULL ); // avoid spoiling memory
3273             std::set_intersection( faceNodeSet.begin(), faceNodeSet.end(),
3274                                    initNodeSet.begin(), initNodeSet.end(),
3275                                    commonNodes.begin());
3276             if ( (*v)->IsQuadratic() )
3277               srcEdges.push_back(aMesh->FindEdge (commonNodes[0],commonNodes[1],commonNodes[2]));
3278             else
3279               srcEdges.push_back(aMesh->FindEdge (commonNodes[0],commonNodes[1]));
3280 #ifdef _DEBUG_
3281             if ( !srcEdges.back() )
3282             {
3283               cout << "SMESH_MeshEditor::makeWalls(), no source edge found for a free face #"
3284                    << iF << " of volume #" << vTool.ID() << endl;
3285             }
3286 #endif
3287           }
3288         }
3289         if ( freeInd.empty() )
3290           continue;
3291
3292         // create faces for all steps;
3293         // if such a face has been already created by sweep of edge,
3294         // assure that its orientation is OK
3295         for ( int iStep = 0; iStep < nbSteps; iStep++ )  {
3296           vTool.Set( *v );
3297           vTool.SetExternalNormal();
3298           list< int >::iterator ind = freeInd.begin();
3299           list< const SMDS_MeshElement* >::iterator srcEdge = srcEdges.begin();
3300           for ( ; ind != freeInd.end(); ++ind, ++srcEdge ) // loop on free faces
3301           {
3302             const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
3303             int nbn = vTool.NbFaceNodes( *ind );
3304             switch ( nbn ) {
3305             case 3: { ///// triangle
3306               const SMDS_MeshFace * f = aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]);
3307               if ( !f )
3308                 myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
3309               else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3310                 aMesh->ChangeElementNodes( f, nodes, nbn );
3311               break;
3312             }
3313             case 4: { ///// quadrangle
3314               const SMDS_MeshFace * f = aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]);
3315               if ( !f )
3316                 myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ));
3317               else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3318                 aMesh->ChangeElementNodes( f, nodes, nbn );
3319               break;
3320             }
3321             default:
3322               if( (*v)->IsQuadratic() ) {
3323                 if(nbn==6) { /////// quadratic triangle
3324                   const SMDS_MeshFace * f = aMesh->FindFace( nodes[0], nodes[2], nodes[4],
3325                                                              nodes[1], nodes[3], nodes[5] );
3326                   if ( !f )
3327                     myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4],
3328                                                              nodes[1], nodes[3], nodes[5]));
3329                   else if ( nodes[ 2 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3330                     aMesh->ChangeElementNodes( f, nodes, nbn );
3331                 }
3332                 else {       /////// quadratic quadrangle
3333                   const SMDS_MeshFace * f = aMesh->FindFace( nodes[0], nodes[2], nodes[4], nodes[6],
3334                                                              nodes[1], nodes[3], nodes[5], nodes[7] );
3335                   if ( !f )
3336                     myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4], nodes[6],
3337                                                              nodes[1], nodes[3], nodes[5], nodes[7]));
3338                   else if ( nodes[ 2 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3339                     aMesh->ChangeElementNodes( f, nodes, nbn );
3340                 }
3341               }
3342               else { //////// polygon
3343                 vector<const SMDS_MeshNode*> polygon_nodes ( nodes, &nodes[nbn] );
3344                 const SMDS_MeshFace * f = aMesh->FindFace( polygon_nodes );
3345                 if ( !f )
3346                   myLastCreatedElems.Append(aMesh->AddPolygonalFace(polygon_nodes));
3347                 else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3348                   aMesh->ChangeElementNodes( f, nodes, nbn );
3349               }
3350             }
3351             while ( srcElements.Length() < myLastCreatedElems.Length() )
3352               srcElements.Append( *srcEdge );
3353
3354           }  // loop on free faces
3355
3356           // go to the next volume
3357           iVol = 0;
3358           while ( iVol++ < nbVolumesByStep ) v++;
3359         }
3360       }
3361     } // sweep free links into faces
3362
3363     // Make a ceiling face with a normal external to a volume
3364
3365     SMDS_VolumeTool lastVol( itElem->second.back() );
3366
3367     int iF = lastVol.GetFaceIndex( aFaceLastNodes );
3368     if ( iF >= 0 ) {
3369       lastVol.SetExternalNormal();
3370       const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
3371       int nbn = lastVol.NbFaceNodes( iF );
3372       switch ( nbn ) {
3373       case 3:
3374         if (!hasFreeLinks ||
3375             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
3376           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
3377         break;
3378       case 4:
3379         if (!hasFreeLinks ||
3380             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
3381           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ));
3382         break;
3383       default:
3384         if(itElem->second.back()->IsQuadratic()) {
3385           if(nbn==6) {
3386             if (!hasFreeLinks ||
3387                 !aMesh->FindFace(nodes[0], nodes[2], nodes[4],
3388                                  nodes[1], nodes[3], nodes[5]) ) {
3389               myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4],
3390                                                        nodes[1], nodes[3], nodes[5]));
3391             }
3392           }
3393           else { // nbn==8
3394             if (!hasFreeLinks ||
3395                 !aMesh->FindFace(nodes[0], nodes[2], nodes[4], nodes[6],
3396                                  nodes[1], nodes[3], nodes[5], nodes[7]) )
3397               myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4], nodes[6],
3398                                                        nodes[1], nodes[3], nodes[5], nodes[7]));
3399           }
3400         }
3401         else {
3402           vector<const SMDS_MeshNode*> polygon_nodes ( nodes, &nodes[nbn] );
3403           if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
3404             myLastCreatedElems.Append(aMesh->AddPolygonalFace(polygon_nodes));
3405         }
3406       } // switch
3407
3408       while ( srcElements.Length() < myLastCreatedElems.Length() )
3409         srcElements.Append( myLastCreatedElems.Last() );
3410     }
3411   } // loop on swept elements
3412 }
3413
3414 //=======================================================================
3415 //function : RotationSweep
3416 //purpose  :
3417 //=======================================================================
3418
3419 SMESH_MeshEditor::PGroupIDs
3420 SMESH_MeshEditor::RotationSweep(TIDSortedElemSet & theElems,
3421                                 const gp_Ax1&      theAxis,
3422                                 const double       theAngle,
3423                                 const int          theNbSteps,
3424                                 const double       theTol,
3425                                 const bool         theMakeGroups,
3426                                 const bool         theMakeWalls)
3427 {
3428   myLastCreatedElems.Clear();
3429   myLastCreatedNodes.Clear();
3430
3431   // source elements for each generated one
3432   SMESH_SequenceOfElemPtr srcElems, srcNodes;
3433
3434   MESSAGE( "RotationSweep()");
3435   gp_Trsf aTrsf;
3436   aTrsf.SetRotation( theAxis, theAngle );
3437   gp_Trsf aTrsf2;
3438   aTrsf2.SetRotation( theAxis, theAngle/2. );
3439
3440   gp_Lin aLine( theAxis );
3441   double aSqTol = theTol * theTol;
3442
3443   SMESHDS_Mesh* aMesh = GetMeshDS();
3444
3445   TNodeOfNodeListMap mapNewNodes;
3446   TElemOfVecOfNnlmiMap mapElemNewNodes;
3447   TElemOfElemListMap newElemsMap;
3448
3449   // loop on theElems
3450   TIDSortedElemSet::iterator itElem;
3451   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3452     const SMDS_MeshElement* elem = *itElem;
3453     if ( !elem || elem->GetType() == SMDSAbs_Volume )
3454       continue;
3455     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3456     newNodesItVec.reserve( elem->NbNodes() );
3457
3458     // loop on elem nodes
3459     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3460     while ( itN->more() )
3461     {
3462       // check if a node has been already sweeped
3463       const SMDS_MeshNode* node = cast2Node( itN->next() );
3464       TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
3465       if ( nIt == mapNewNodes.end() ) {
3466         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3467         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3468
3469         // make new nodes
3470         gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
3471         double coord[3];
3472         aXYZ.Coord( coord[0], coord[1], coord[2] );
3473         bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
3474         const SMDS_MeshNode * newNode = node;
3475         for ( int i = 0; i < theNbSteps; i++ ) {
3476           if ( !isOnAxis ) {
3477             if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3478               // create two nodes
3479               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3480               //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3481               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3482               myLastCreatedNodes.Append(newNode);
3483               srcNodes.Append( node );
3484               listNewNodes.push_back( newNode );
3485               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3486               //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3487             }
3488             else {
3489               aTrsf.Transforms( coord[0], coord[1], coord[2] );
3490             }
3491             newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3492             myLastCreatedNodes.Append(newNode);
3493             srcNodes.Append( node );
3494           }
3495           listNewNodes.push_back( newNode );
3496         }
3497       }
3498       else {
3499         // if current elem is quadratic and current node is not medium
3500         // we have to check - may be it is needed to insert additional nodes
3501         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3502           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3503           if(listNewNodes.size()==theNbSteps) {
3504             listNewNodes.clear();
3505             // make new nodes
3506             gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
3507             double coord[3];
3508             aXYZ.Coord( coord[0], coord[1], coord[2] );
3509             const SMDS_MeshNode * newNode = node;
3510             for(int i = 0; i<theNbSteps; i++) {
3511               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3512               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3513               myLastCreatedNodes.Append(newNode);
3514               listNewNodes.push_back( newNode );
3515               srcNodes.Append( node );
3516               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3517               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3518               myLastCreatedNodes.Append(newNode);
3519               srcNodes.Append( node );
3520               listNewNodes.push_back( newNode );
3521             }
3522           }
3523         }
3524       }
3525       newNodesItVec.push_back( nIt );
3526     }
3527     // make new elements
3528     sweepElement( elem, newNodesItVec, newElemsMap[elem], theNbSteps, srcElems );
3529   }
3530
3531   if ( theMakeWalls )
3532     makeWalls( mapNewNodes, newElemsMap, mapElemNewNodes, theElems, theNbSteps, srcElems );
3533   
3534   PGroupIDs newGroupIDs;
3535   if ( theMakeGroups )
3536     newGroupIDs = generateGroups( srcNodes, srcElems, "rotated");
3537
3538   return newGroupIDs;
3539 }
3540
3541
3542 //=======================================================================
3543 //function : CreateNode
3544 //purpose  :
3545 //=======================================================================
3546 const SMDS_MeshNode* SMESH_MeshEditor::CreateNode(const double x,
3547                                                   const double y,
3548                                                   const double z,
3549                                                   const double tolnode,
3550                                                   SMESH_SequenceOfNode& aNodes)
3551 {
3552   myLastCreatedElems.Clear();
3553   myLastCreatedNodes.Clear();
3554
3555   gp_Pnt P1(x,y,z);
3556   SMESHDS_Mesh * aMesh = myMesh->GetMeshDS();
3557
3558   // try to search in sequence of existing nodes
3559   // if aNodes.Length()>0 we 'nave to use given sequence
3560   // else - use all nodes of mesh
3561   if(aNodes.Length()>0) {
3562     int i;
3563     for(i=1; i<=aNodes.Length(); i++) {
3564       gp_Pnt P2(aNodes.Value(i)->X(),aNodes.Value(i)->Y(),aNodes.Value(i)->Z());
3565       if(P1.Distance(P2)<tolnode)
3566         return aNodes.Value(i);
3567     }
3568   }
3569   else {
3570     SMDS_NodeIteratorPtr itn = aMesh->nodesIterator();
3571     while(itn->more()) {
3572       const SMDS_MeshNode* aN = static_cast<const SMDS_MeshNode*> (itn->next());
3573       gp_Pnt P2(aN->X(),aN->Y(),aN->Z());
3574       if(P1.Distance(P2)<tolnode)
3575         return aN;
3576     }
3577   }
3578
3579   // create new node and return it
3580   const SMDS_MeshNode* NewNode = aMesh->AddNode(x,y,z);
3581   myLastCreatedNodes.Append(NewNode);
3582   return NewNode;
3583 }
3584
3585
3586 //=======================================================================
3587 //function : ExtrusionSweep
3588 //purpose  :
3589 //=======================================================================
3590
3591 SMESH_MeshEditor::PGroupIDs
3592 SMESH_MeshEditor::ExtrusionSweep (TIDSortedElemSet &  theElems,
3593                                   const gp_Vec&       theStep,
3594                                   const int           theNbSteps,
3595                                   TElemOfElemListMap& newElemsMap,
3596                                   const bool          theMakeGroups,
3597                                   const int           theFlags,
3598                                   const double        theTolerance)
3599 {
3600   ExtrusParam aParams;
3601   aParams.myDir = gp_Dir(theStep);
3602   aParams.myNodes.Clear();
3603   aParams.mySteps = new TColStd_HSequenceOfReal;
3604   int i;
3605   for(i=1; i<=theNbSteps; i++)
3606     aParams.mySteps->Append(theStep.Magnitude());
3607
3608   return
3609     ExtrusionSweep(theElems,aParams,newElemsMap,theMakeGroups,theFlags,theTolerance);
3610 }
3611
3612
3613 //=======================================================================
3614 //function : ExtrusionSweep
3615 //purpose  :
3616 //=======================================================================
3617
3618 SMESH_MeshEditor::PGroupIDs
3619 SMESH_MeshEditor::ExtrusionSweep (TIDSortedElemSet &  theElems,
3620                                   ExtrusParam&        theParams,
3621                                   TElemOfElemListMap& newElemsMap,
3622                                   const bool          theMakeGroups,
3623                                   const int           theFlags,
3624                                   const double        theTolerance)
3625 {
3626   myLastCreatedElems.Clear();
3627   myLastCreatedNodes.Clear();
3628
3629   // source elements for each generated one
3630   SMESH_SequenceOfElemPtr srcElems, srcNodes;
3631
3632   SMESHDS_Mesh* aMesh = GetMeshDS();
3633
3634   int nbsteps = theParams.mySteps->Length();
3635
3636   TNodeOfNodeListMap mapNewNodes;
3637   //TNodeOfNodeVecMap mapNewNodes;
3638   TElemOfVecOfNnlmiMap mapElemNewNodes;
3639   //TElemOfVecOfMapNodesMap mapElemNewNodes;
3640
3641   // loop on theElems
3642   TIDSortedElemSet::iterator itElem;
3643   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3644     // check element type
3645     const SMDS_MeshElement* elem = *itElem;
3646     if ( !elem  || elem->GetType() == SMDSAbs_Volume )
3647       continue;
3648
3649     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3650     //vector<TNodeOfNodeVecMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3651     newNodesItVec.reserve( elem->NbNodes() );
3652
3653     // loop on elem nodes
3654     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3655     while ( itN->more() )
3656     {
3657       // check if a node has been already sweeped
3658       const SMDS_MeshNode* node = cast2Node( itN->next() );
3659       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
3660       //TNodeOfNodeVecMap::iterator nIt = mapNewNodes.find( node );
3661       if ( nIt == mapNewNodes.end() ) {
3662         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3663         //nIt = mapNewNodes.insert( make_pair( node, vector<const SMDS_MeshNode*>() )).first;
3664         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3665         //vector<const SMDS_MeshNode*>& vecNewNodes = nIt->second;
3666         //vecNewNodes.reserve(nbsteps);
3667
3668         // make new nodes
3669         double coord[] = { node->X(), node->Y(), node->Z() };
3670         //int nbsteps = theParams.mySteps->Length();
3671         for ( int i = 0; i < nbsteps; i++ ) {
3672           if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3673             // create additional node
3674             double x = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1)/2.;
3675             double y = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1)/2.;
3676             double z = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1)/2.;
3677             if( theFlags & EXTRUSION_FLAG_SEW ) {
3678               const SMDS_MeshNode * newNode = CreateNode(x, y, z,
3679                                                          theTolerance, theParams.myNodes);
3680               listNewNodes.push_back( newNode );
3681             }
3682             else {
3683               const SMDS_MeshNode * newNode = aMesh->AddNode(x, y, z);
3684               myLastCreatedNodes.Append(newNode);
3685               srcNodes.Append( node );
3686               listNewNodes.push_back( newNode );
3687             }
3688           }
3689           //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3690           coord[0] = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3691           coord[1] = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3692           coord[2] = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3693           if( theFlags & EXTRUSION_FLAG_SEW ) {
3694             const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1], coord[2],
3695                                                        theTolerance, theParams.myNodes);
3696             listNewNodes.push_back( newNode );
3697             //vecNewNodes[i]=newNode;
3698           }
3699           else {
3700             const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3701             myLastCreatedNodes.Append(newNode);
3702             srcNodes.Append( node );
3703             listNewNodes.push_back( newNode );
3704             //vecNewNodes[i]=newNode;
3705           }
3706         }
3707       }
3708       else {
3709         // if current elem is quadratic and current node is not medium
3710         // we have to check - may be it is needed to insert additional nodes
3711         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3712           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3713           if(listNewNodes.size()==nbsteps) {
3714             listNewNodes.clear();
3715             double coord[] = { node->X(), node->Y(), node->Z() };
3716             for ( int i = 0; i < nbsteps; i++ ) {
3717               double x = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3718               double y = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3719               double z = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3720               if( theFlags & EXTRUSION_FLAG_SEW ) {
3721                 const SMDS_MeshNode * newNode = CreateNode(x, y, z,
3722                                                            theTolerance, theParams.myNodes);
3723                 listNewNodes.push_back( newNode );
3724               }
3725               else {
3726                 const SMDS_MeshNode * newNode = aMesh->AddNode(x, y, z);
3727                 myLastCreatedNodes.Append(newNode);
3728                 srcNodes.Append( node );
3729                 listNewNodes.push_back( newNode );
3730               }
3731               coord[0] = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3732               coord[1] = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3733               coord[2] = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3734               if( theFlags & EXTRUSION_FLAG_SEW ) {
3735                 const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1], coord[2],
3736                                                            theTolerance, theParams.myNodes);
3737                 listNewNodes.push_back( newNode );
3738               }
3739               else {
3740                 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3741                 myLastCreatedNodes.Append(newNode);
3742                 srcNodes.Append( node );
3743                 listNewNodes.push_back( newNode );
3744               }
3745             }
3746           }
3747         }
3748       }
3749       newNodesItVec.push_back( nIt );
3750     }
3751     // make new elements
3752     sweepElement( elem, newNodesItVec, newElemsMap[elem], nbsteps, srcElems );
3753   }
3754
3755   if( theFlags & EXTRUSION_FLAG_BOUNDARY ) {
3756     makeWalls( mapNewNodes, newElemsMap, mapElemNewNodes, theElems, nbsteps, srcElems );
3757   }
3758   PGroupIDs newGroupIDs;
3759   if ( theMakeGroups )
3760     newGroupIDs = generateGroups( srcNodes, srcElems, "extruded");
3761
3762   return newGroupIDs;
3763 }
3764
3765
3766 //=======================================================================
3767 //class    : SMESH_MeshEditor_PathPoint
3768 //purpose  : auxiliary class
3769 //=======================================================================
3770 class SMESH_MeshEditor_PathPoint {
3771 public:
3772   SMESH_MeshEditor_PathPoint() {
3773     myPnt.SetCoord(99., 99., 99.);
3774     myTgt.SetCoord(1.,0.,0.);
3775     myAngle=0.;
3776     myPrm=0.;
3777   }
3778   void SetPnt(const gp_Pnt& aP3D){
3779     myPnt=aP3D;
3780   }
3781   void SetTangent(const gp_Dir& aTgt){
3782     myTgt=aTgt;
3783   }
3784   void SetAngle(const double& aBeta){
3785     myAngle=aBeta;
3786   }
3787   void SetParameter(const double& aPrm){
3788     myPrm=aPrm;
3789   }
3790   const gp_Pnt& Pnt()const{
3791     return myPnt;
3792   }
3793   const gp_Dir& Tangent()const{
3794     return myTgt;
3795   }
3796   double Angle()const{
3797     return myAngle;
3798   }
3799   double Parameter()const{
3800     return myPrm;
3801   }
3802
3803 protected:
3804   gp_Pnt myPnt;
3805   gp_Dir myTgt;
3806   double myAngle;
3807   double myPrm;
3808 };
3809
3810 //=======================================================================
3811 //function : ExtrusionAlongTrack
3812 //purpose  :
3813 //=======================================================================
3814 SMESH_MeshEditor::Extrusion_Error
3815   SMESH_MeshEditor::ExtrusionAlongTrack (TIDSortedElemSet &   theElements,
3816                                          SMESH_subMesh*       theTrack,
3817                                          const SMDS_MeshNode* theN1,
3818                                          const bool           theHasAngles,
3819                                          list<double>&        theAngles,
3820                                          const bool           theHasRefPoint,
3821                                          const gp_Pnt&        theRefPoint,
3822                                          const bool           theMakeGroups)
3823 {
3824   myLastCreatedElems.Clear();
3825   myLastCreatedNodes.Clear();
3826
3827   // source elements for each generated one
3828   SMESH_SequenceOfElemPtr srcElems, srcNodes;
3829
3830   int j, aNbTP, aNbE, aNb;
3831   double aT1, aT2, aT, aAngle, aX, aY, aZ;
3832   std::list<double> aPrms;
3833   std::list<double>::iterator aItD;
3834   TIDSortedElemSet::iterator itElem;
3835
3836   Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
3837   gp_Pnt aP3D, aV0;
3838   gp_Vec aVec;
3839   gp_XYZ aGC;
3840   Handle(Geom_Curve) aC3D;
3841   TopoDS_Edge aTrackEdge;
3842   TopoDS_Vertex aV1, aV2;
3843
3844   SMDS_ElemIteratorPtr aItE;
3845   SMDS_NodeIteratorPtr aItN;
3846   SMDSAbs_ElementType aTypeE;
3847
3848   TNodeOfNodeListMap mapNewNodes;
3849   TElemOfVecOfNnlmiMap mapElemNewNodes;
3850   TElemOfElemListMap newElemsMap;
3851
3852   aTolVec=1.e-7;
3853   aTolVec2=aTolVec*aTolVec;
3854
3855   // 1. Check data
3856   aNbE = theElements.size();
3857   // nothing to do
3858   if ( !aNbE )
3859     return EXTR_NO_ELEMENTS;
3860
3861   // 1.1 Track Pattern
3862   ASSERT( theTrack );
3863
3864   SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
3865
3866   aItE = pSubMeshDS->GetElements();
3867   while ( aItE->more() ) {
3868     const SMDS_MeshElement* pE = aItE->next();
3869     aTypeE = pE->GetType();
3870     // Pattern must contain links only
3871     if ( aTypeE != SMDSAbs_Edge )
3872       return EXTR_PATH_NOT_EDGE;
3873   }
3874
3875   const TopoDS_Shape& aS = theTrack->GetSubShape();
3876   // Sub shape for the Pattern must be an Edge
3877   if ( aS.ShapeType() != TopAbs_EDGE )
3878     return EXTR_BAD_PATH_SHAPE;
3879
3880   aTrackEdge = TopoDS::Edge( aS );
3881   // the Edge must not be degenerated
3882   if ( BRep_Tool::Degenerated( aTrackEdge ) )
3883     return EXTR_BAD_PATH_SHAPE;
3884
3885   TopExp::Vertices( aTrackEdge, aV1, aV2 );
3886   aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
3887   aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
3888
3889   aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
3890   const SMDS_MeshNode* aN1 = aItN->next();
3891
3892   aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
3893   const SMDS_MeshNode* aN2 = aItN->next();
3894
3895   // starting node must be aN1 or aN2
3896   if ( !( aN1 == theN1 || aN2 == theN1 ) )
3897     return EXTR_BAD_STARTING_NODE;
3898
3899   aNbTP = pSubMeshDS->NbNodes() + 2;
3900
3901   // 1.2. Angles
3902   vector<double> aAngles( aNbTP );
3903
3904   for ( j=0; j < aNbTP; ++j ) {
3905     aAngles[j] = 0.;
3906   }
3907
3908   if ( theHasAngles ) {
3909     aItD = theAngles.begin();
3910     for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
3911       aAngle = *aItD;
3912       aAngles[j] = aAngle;
3913     }
3914   }
3915
3916   // 2. Collect parameters on the track edge
3917   aPrms.push_back( aT1 );
3918   aPrms.push_back( aT2 );
3919
3920   aItN = pSubMeshDS->GetNodes();
3921   while ( aItN->more() ) {
3922     const SMDS_MeshNode* pNode = aItN->next();
3923     const SMDS_EdgePosition* pEPos =
3924       static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
3925     aT = pEPos->GetUParameter();
3926     aPrms.push_back( aT );
3927   }
3928
3929   // sort parameters
3930   aPrms.sort();
3931   if ( aN1 == theN1 ) {
3932     if ( aT1 > aT2 ) {
3933       aPrms.reverse();
3934     }
3935   }
3936   else {
3937     if ( aT2 > aT1 ) {
3938       aPrms.reverse();
3939     }
3940   }
3941
3942   // 3. Path Points
3943   SMESH_MeshEditor_PathPoint aPP;
3944   vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
3945   //
3946   aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
3947   //
3948   aItD = aPrms.begin();
3949   for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
3950     aT = *aItD;
3951     aC3D->D1( aT, aP3D, aVec );
3952     aL2 = aVec.SquareMagnitude();
3953     if ( aL2 < aTolVec2 )
3954       return EXTR_CANT_GET_TANGENT;
3955
3956     gp_Dir aTgt( aVec );
3957     aAngle = aAngles[j];
3958
3959     aPP.SetPnt( aP3D );
3960     aPP.SetTangent( aTgt );
3961     aPP.SetAngle( aAngle );
3962     aPP.SetParameter( aT );
3963     aPPs[j]=aPP;
3964   }
3965
3966   // 3. Center of rotation aV0
3967   aV0 = theRefPoint;
3968   if ( !theHasRefPoint ) {
3969     aNb = 0;
3970     aGC.SetCoord( 0.,0.,0. );
3971
3972     itElem = theElements.begin();
3973     for ( ; itElem != theElements.end(); itElem++ ) {
3974       const SMDS_MeshElement* elem = *itElem;
3975
3976       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3977       while ( itN->more() ) {
3978         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
3979         aX = node->X();
3980         aY = node->Y();
3981         aZ = node->Z();
3982
3983         if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
3984           list<const SMDS_MeshNode*> aLNx;
3985           mapNewNodes[node] = aLNx;
3986           //
3987           gp_XYZ aXYZ( aX, aY, aZ );
3988           aGC += aXYZ;
3989           ++aNb;
3990         }
3991       }
3992     }
3993     aGC /= aNb;
3994     aV0.SetXYZ( aGC );
3995   } // if (!theHasRefPoint) {
3996   mapNewNodes.clear();
3997
3998   // 4. Processing the elements
3999   SMESHDS_Mesh* aMesh = GetMeshDS();
4000
4001   for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
4002     // check element type
4003     const SMDS_MeshElement* elem = *itElem;
4004     aTypeE = elem->GetType();
4005     if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
4006       continue;
4007
4008     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
4009     newNodesItVec.reserve( elem->NbNodes() );
4010
4011     // loop on elem nodes
4012     int nodeIndex = -1;
4013     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4014     while ( itN->more() )
4015     {
4016       ++nodeIndex;
4017       // check if a node has been already processed
4018       const SMDS_MeshNode* node =
4019         static_cast<const SMDS_MeshNode*>( itN->next() );
4020       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
4021       if ( nIt == mapNewNodes.end() ) {
4022         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
4023         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
4024
4025         // make new nodes
4026         aX = node->X();  aY = node->Y(); aZ = node->Z();
4027
4028         Standard_Real aAngle1x, aAngleT1T0, aTolAng;
4029         gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
4030         gp_Ax1 anAx1, anAxT1T0;
4031         gp_Dir aDT1x, aDT0x, aDT1T0;
4032
4033         aTolAng=1.e-4;
4034
4035         aV0x = aV0;
4036         aPN0.SetCoord(aX, aY, aZ);
4037
4038         const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
4039         aP0x = aPP0.Pnt();
4040         aDT0x= aPP0.Tangent();
4041
4042         for ( j = 1; j < aNbTP; ++j ) {
4043           const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
4044           aP1x = aPP1.Pnt();
4045           aDT1x = aPP1.Tangent();
4046           aAngle1x = aPP1.Angle();
4047
4048           gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
4049           // Translation
4050           gp_Vec aV01x( aP0x, aP1x );
4051           aTrsf.SetTranslation( aV01x );
4052
4053           // traslated point
4054           aV1x = aV0x.Transformed( aTrsf );
4055           aPN1 = aPN0.Transformed( aTrsf );
4056
4057           // rotation 1 [ T1,T0 ]
4058           aAngleT1T0=-aDT1x.Angle( aDT0x );
4059           if (fabs(aAngleT1T0) > aTolAng) {
4060             aDT1T0=aDT1x^aDT0x;
4061             anAxT1T0.SetLocation( aV1x );
4062             anAxT1T0.SetDirection( aDT1T0 );
4063             aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
4064
4065             aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
4066           }
4067
4068           // rotation 2
4069           if ( theHasAngles ) {
4070             anAx1.SetLocation( aV1x );
4071             anAx1.SetDirection( aDT1x );
4072             aTrsfRot.SetRotation( anAx1, aAngle1x );
4073
4074             aPN1 = aPN1.Transformed( aTrsfRot );
4075           }
4076
4077           // make new node
4078           if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
4079             // create additional node
4080             double x = ( aPN1.X() + aPN0.X() )/2.;
4081             double y = ( aPN1.Y() + aPN0.Y() )/2.;
4082             double z = ( aPN1.Z() + aPN0.Z() )/2.;
4083             const SMDS_MeshNode* newNode = aMesh->AddNode(x,y,z);
4084             myLastCreatedNodes.Append(newNode);
4085             srcNodes.Append( node );
4086             listNewNodes.push_back( newNode );
4087           }
4088           aX = aPN1.X();
4089           aY = aPN1.Y();
4090           aZ = aPN1.Z();
4091           const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
4092           myLastCreatedNodes.Append(newNode);
4093           srcNodes.Append( node );
4094           listNewNodes.push_back( newNode );
4095
4096           aPN0 = aPN1;
4097           aP0x = aP1x;
4098           aV0x = aV1x;
4099           aDT0x = aDT1x;
4100         }
4101       }
4102
4103       else {
4104         // if current elem is quadratic and current node is not medium
4105         // we have to check - may be it is needed to insert additional nodes
4106         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
4107           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
4108           if(listNewNodes.size()==aNbTP-1) {
4109             vector<const SMDS_MeshNode*> aNodes(2*(aNbTP-1));
4110             gp_XYZ P(node->X(), node->Y(), node->Z());
4111             list< const SMDS_MeshNode* >::iterator it = listNewNodes.begin();
4112             int i;
4113             for(i=0; i<aNbTP-1; i++) {
4114               const SMDS_MeshNode* N = *it;
4115               double x = ( N->X() + P.X() )/2.;
4116               double y = ( N->Y() + P.Y() )/2.;
4117               double z = ( N->Z() + P.Z() )/2.;
4118               const SMDS_MeshNode* newN = aMesh->AddNode(x,y,z);
4119               srcNodes.Append( node );
4120               myLastCreatedNodes.Append(newN);
4121               aNodes[2*i] = newN;
4122               aNodes[2*i+1] = N;
4123               P = gp_XYZ(N->X(),N->Y(),N->Z());
4124             }
4125             listNewNodes.clear();
4126             for(i=0; i<2*(aNbTP-1); i++) {
4127               listNewNodes.push_back(aNodes[i]);
4128             }
4129           }
4130         }
4131       }
4132
4133       newNodesItVec.push_back( nIt );
4134     }
4135     // make new elements
4136     //sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem],
4137     //              newNodesItVec[0]->second.size(), myLastCreatedElems );
4138     sweepElement( elem, newNodesItVec, newElemsMap[elem], aNbTP-1, srcElems );
4139   }
4140
4141   makeWalls( mapNewNodes, newElemsMap, mapElemNewNodes, theElements, aNbTP-1, srcElems );
4142
4143   if ( theMakeGroups )
4144     generateGroups( srcNodes, srcElems, "extruded");
4145
4146   return EXTR_OK;
4147 }
4148
4149 //=======================================================================
4150 //function : Transform
4151 //purpose  :
4152 //=======================================================================
4153
4154 SMESH_MeshEditor::PGroupIDs
4155 SMESH_MeshEditor::Transform (TIDSortedElemSet & theElems,
4156                              const gp_Trsf&     theTrsf,
4157                              const bool         theCopy,
4158                              const bool         theMakeGroups,
4159                              SMESH_Mesh*        theTargetMesh)
4160 {
4161   myLastCreatedElems.Clear();
4162   myLastCreatedNodes.Clear();
4163
4164   bool needReverse = false;
4165   string groupPostfix;
4166   switch ( theTrsf.Form() ) {
4167   case gp_PntMirror:
4168   case gp_Ax1Mirror:
4169   case gp_Ax2Mirror:
4170     needReverse = true;
4171     groupPostfix = "mirrored";
4172     break;
4173   case gp_Rotation:
4174     groupPostfix = "rotated";
4175     break;
4176   case gp_Translation:
4177     groupPostfix = "translated";
4178     break;
4179   case gp_Scale:
4180     groupPostfix = "scaled";
4181     break;
4182   default:
4183     needReverse = false;
4184     groupPostfix = "transformed";
4185   }
4186
4187   SMESH_MeshEditor targetMeshEditor( theTargetMesh );
4188   SMESHDS_Mesh* aTgtMesh = theTargetMesh ? theTargetMesh->GetMeshDS() : 0;
4189   SMESHDS_Mesh* aMesh    = GetMeshDS();
4190   
4191
4192   // map old node to new one
4193   TNodeNodeMap nodeMap;
4194
4195   // elements sharing moved nodes; those of them which have all
4196   // nodes mirrored but are not in theElems are to be reversed
4197   TIDSortedElemSet inverseElemSet;
4198
4199   // source elements for each generated one
4200   SMESH_SequenceOfElemPtr srcElems, srcNodes;
4201
4202   // loop on theElems
4203   TIDSortedElemSet::iterator itElem;
4204   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
4205     const SMDS_MeshElement* elem = *itElem;
4206     if ( !elem )
4207       continue;
4208
4209     // loop on elem nodes
4210     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4211     while ( itN->more() ) {
4212
4213       // check if a node has been already transformed
4214       const SMDS_MeshNode* node = cast2Node( itN->next() );
4215       pair<TNodeNodeMap::iterator,bool> n2n_isnew =
4216         nodeMap.insert( make_pair ( node, node ));
4217       if ( !n2n_isnew.second )
4218         continue;
4219
4220       double coord[3];
4221       coord[0] = node->X();
4222       coord[1] = node->Y();
4223       coord[2] = node->Z();
4224       theTrsf.Transforms( coord[0], coord[1], coord[2] );
4225       if ( theTargetMesh ) {
4226         const SMDS_MeshNode * newNode = aTgtMesh->AddNode( coord[0], coord[1], coord[2] );
4227         n2n_isnew.first->second = newNode;
4228         myLastCreatedNodes.Append(newNode);
4229         srcNodes.Append( node );
4230       }
4231       else if ( theCopy ) {
4232         const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
4233         n2n_isnew.first->second = newNode;
4234         myLastCreatedNodes.Append(newNode);
4235         srcNodes.Append( node );
4236       }
4237       else {
4238         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
4239         // node position on shape becomes invalid
4240         const_cast< SMDS_MeshNode* > ( node )->SetPosition
4241           ( SMDS_SpacePosition::originSpacePosition() );
4242       }
4243
4244       // keep inverse elements
4245       if ( !theCopy && !theTargetMesh && needReverse ) {
4246         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
4247         while ( invElemIt->more() ) {
4248           const SMDS_MeshElement* iel = invElemIt->next();
4249           inverseElemSet.insert( iel );
4250         }
4251       }
4252     }
4253   }
4254
4255   // either create new elements or reverse mirrored ones
4256   if ( !theCopy && !needReverse && !theTargetMesh )
4257     return PGroupIDs();
4258
4259   TIDSortedElemSet::iterator invElemIt = inverseElemSet.begin();
4260   for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
4261     theElems.insert( *invElemIt );
4262
4263   // replicate or reverse elements
4264
4265   enum {
4266     REV_TETRA   = 0,  //  = nbNodes - 4
4267     REV_PYRAMID = 1,  //  = nbNodes - 4
4268     REV_PENTA   = 2,  //  = nbNodes - 4
4269     REV_FACE    = 3,
4270     REV_HEXA    = 4,  //  = nbNodes - 4
4271     FORWARD     = 5
4272     };
4273   int index[][8] = {
4274     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA
4275     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
4276     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA
4277     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE
4278     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA
4279     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD
4280   };
4281
4282   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
4283   {
4284     const SMDS_MeshElement* elem = *itElem;
4285     if ( !elem || elem->GetType() == SMDSAbs_Node )
4286       continue;
4287
4288     int nbNodes = elem->NbNodes();
4289     int elemType = elem->GetType();
4290
4291     if (elem->IsPoly()) {
4292       // Polygon or Polyhedral Volume
4293       switch ( elemType ) {
4294       case SMDSAbs_Face:
4295         {
4296           vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
4297           int iNode = 0;
4298           SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4299           while (itN->more()) {
4300             const SMDS_MeshNode* node =
4301               static_cast<const SMDS_MeshNode*>(itN->next());
4302             TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
4303             if (nodeMapIt == nodeMap.end())
4304               break; // not all nodes transformed
4305             if (needReverse) {
4306               // reverse mirrored faces and volumes
4307               poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
4308             } else {
4309               poly_nodes[iNode] = (*nodeMapIt).second;
4310             }
4311             iNode++;
4312           }
4313           if ( iNode != nbNodes )
4314             continue; // not all nodes transformed
4315
4316           if ( theTargetMesh ) {
4317             myLastCreatedElems.Append(aTgtMesh->AddPolygonalFace(poly_nodes));
4318             srcElems.Append( elem );
4319           }
4320           else if ( theCopy ) {
4321             myLastCreatedElems.Append(aMesh->AddPolygonalFace(poly_nodes));
4322             srcElems.Append( elem );
4323           }
4324           else {
4325             aMesh->ChangePolygonNodes(elem, poly_nodes);
4326           }
4327         }
4328         break;
4329       case SMDSAbs_Volume:
4330         {
4331           // ATTENTION: Reversing is not yet done!!!
4332           const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4333             dynamic_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
4334           if (!aPolyedre) {
4335             MESSAGE("Warning: bad volumic element");
4336             continue;
4337           }
4338
4339           vector<const SMDS_MeshNode*> poly_nodes;
4340           vector<int> quantities;
4341
4342           bool allTransformed = true;
4343           int nbFaces = aPolyedre->NbFaces();
4344           for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
4345             int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4346             for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
4347               const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
4348               TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
4349               if (nodeMapIt == nodeMap.end()) {
4350                 allTransformed = false; // not all nodes transformed
4351               } else {
4352                 poly_nodes.push_back((*nodeMapIt).second);
4353               }
4354             }
4355             quantities.push_back(nbFaceNodes);
4356           }
4357           if ( !allTransformed )
4358             continue; // not all nodes transformed
4359
4360           if ( theTargetMesh ) {
4361             myLastCreatedElems.Append(aTgtMesh->AddPolyhedralVolume(poly_nodes, quantities));
4362             srcElems.Append( elem );
4363           }
4364           else if ( theCopy ) {
4365             myLastCreatedElems.Append(aMesh->AddPolyhedralVolume(poly_nodes, quantities));
4366             srcElems.Append( elem );
4367           }
4368           else {
4369             aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4370           }
4371         }
4372         break;
4373     default:;
4374     }
4375     continue;
4376   }
4377
4378   // Regular elements
4379   int* i = index[ FORWARD ];
4380   if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
4381     if ( elemType == SMDSAbs_Face )
4382       i = index[ REV_FACE ];
4383     else
4384       i = index[ nbNodes - 4 ];
4385
4386     if(elem->IsQuadratic()) {
4387       static int anIds[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
4388       i = anIds;
4389       if(needReverse) {
4390         if(nbNodes==3) { // quadratic edge
4391           static int anIds[] = {1,0,2};
4392           i = anIds;
4393         }
4394         else if(nbNodes==6) { // quadratic triangle
4395           static int anIds[] = {0,2,1,5,4,3};
4396           i = anIds;
4397         }
4398         else if(nbNodes==8) { // quadratic quadrangle
4399           static int anIds[] = {0,3,2,1,7,6,5,4};
4400           i = anIds;
4401         }
4402         else if(nbNodes==10) { // quadratic tetrahedron of 10 nodes
4403           static int anIds[] = {0,2,1,3,6,5,4,7,9,8};
4404           i = anIds;
4405         }
4406         else if(nbNodes==13) { // quadratic pyramid of 13 nodes
4407           static int anIds[] = {0,3,2,1,4,8,7,6,5,9,12,11,10};
4408           i = anIds;
4409         }
4410         else if(nbNodes==15) { // quadratic pentahedron with 15 nodes
4411           static int anIds[] = {0,2,1,3,5,4,8,7,6,11,10,9,12,14,13};
4412           i = anIds;
4413         }
4414         else { // nbNodes==20 - quadratic hexahedron with 20 nodes
4415           static int anIds[] = {0,3,2,1,4,7,6,5,11,10,9,8,15,14,13,12,16,19,18,17};
4416           i = anIds;
4417         }
4418       }
4419     }
4420
4421     // find transformed nodes
4422     vector<const SMDS_MeshNode*> nodes(nbNodes);
4423     int iNode = 0;
4424     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4425     while ( itN->more() ) {
4426       const SMDS_MeshNode* node =
4427         static_cast<const SMDS_MeshNode*>( itN->next() );
4428       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
4429       if ( nodeMapIt == nodeMap.end() )
4430         break; // not all nodes transformed
4431       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
4432     }
4433     if ( iNode != nbNodes )
4434       continue; // not all nodes transformed
4435
4436     if ( theTargetMesh ) {
4437       if ( SMDS_MeshElement* copy =
4438            targetMeshEditor.AddElement( nodes, elem->GetType(), elem->IsPoly() )) {
4439         myLastCreatedElems.Append( copy );
4440         srcElems.Append( elem );
4441       }
4442     }
4443     else if ( theCopy ) {
4444       if ( SMDS_MeshElement* copy = AddElement( nodes, elem->GetType(), elem->IsPoly() )) {
4445         myLastCreatedElems.Append( copy );
4446         srcElems.Append( elem );
4447       }
4448     }
4449     else {
4450       // reverse element as it was reversed by transformation
4451       if ( nbNodes > 2 )
4452         aMesh->ChangeElementNodes( elem, &nodes[0], nbNodes );
4453     }
4454   }
4455
4456   PGroupIDs newGroupIDs;
4457
4458   if ( theMakeGroups && theCopy ||
4459        theMakeGroups && theTargetMesh )
4460     newGroupIDs = generateGroups( srcNodes, srcElems, groupPostfix, theTargetMesh );
4461
4462   return newGroupIDs;
4463 }
4464
4465 //=======================================================================
4466 /*!
4467  * \brief Create groups of elements made during transformation
4468  * \param nodeGens - nodes making corresponding myLastCreatedNodes
4469  * \param elemGens - elements making corresponding myLastCreatedElems
4470  * \param postfix - to append to names of new groups
4471  */
4472 //=======================================================================
4473
4474 SMESH_MeshEditor::PGroupIDs
4475 SMESH_MeshEditor::generateGroups(const SMESH_SequenceOfElemPtr& nodeGens,
4476                                  const SMESH_SequenceOfElemPtr& elemGens,
4477                                  const std::string&             postfix,
4478                                  SMESH_Mesh*                    targetMesh)
4479 {
4480   PGroupIDs newGroupIDs( new list<int> );
4481   SMESH_Mesh* mesh = targetMesh ? targetMesh : GetMesh();
4482
4483   // Sort existing groups by types and collect their names
4484
4485   // to store an old group and a generated new one
4486   typedef pair< SMESHDS_GroupBase*, SMDS_MeshGroup* > TOldNewGroup;
4487   vector< list< TOldNewGroup > > groupsByType( SMDSAbs_NbElementTypes );
4488   // group names
4489   set< string > groupNames;
4490   //
4491   SMDS_MeshGroup* nullNewGroup = (SMDS_MeshGroup*) 0;
4492   SMESH_Mesh::GroupIteratorPtr groupIt = GetMesh()->GetGroups();
4493   while ( groupIt->more() ) {
4494     SMESH_Group * group = groupIt->next();
4495     if ( !group ) continue;
4496     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
4497     if ( !groupDS || groupDS->IsEmpty() ) continue;
4498     groupNames.insert( group->GetName() );
4499     groupDS->SetStoreName( group->GetName() );
4500     groupsByType[ groupDS->GetType() ].push_back( make_pair( groupDS, nullNewGroup ));
4501   }
4502
4503   // Groups creation
4504
4505   // loop on nodes and elements
4506   for ( int isNodes = 0; isNodes < 2; ++isNodes )
4507   {
4508     const SMESH_SequenceOfElemPtr& gens  = isNodes ? nodeGens : elemGens;
4509     const SMESH_SequenceOfElemPtr& elems = isNodes ? myLastCreatedNodes : myLastCreatedElems;
4510     if ( gens.Length() != elems.Length() )
4511       throw SALOME_Exception(LOCALIZED("invalid args"));
4512
4513     // loop on created elements
4514     for (int iElem = 1; iElem <= elems.Length(); ++iElem )
4515     {
4516       const SMDS_MeshElement* sourceElem = gens( iElem );
4517       if ( !sourceElem ) {
4518         MESSAGE("generateGroups(): NULL source element");
4519         continue;
4520       }
4521       list< TOldNewGroup > & groupsOldNew = groupsByType[ sourceElem->GetType() ];
4522       if ( groupsOldNew.empty() ) {
4523         while ( iElem < gens.Length() && gens( iElem+1 ) == sourceElem )
4524           ++iElem; // skip all elements made by sourceElem
4525         continue;
4526       }
4527       // collect all elements made by sourceElem
4528       list< const SMDS_MeshElement* > resultElems;
4529       if ( const SMDS_MeshElement* resElem = elems( iElem ))
4530         if ( resElem != sourceElem )
4531           resultElems.push_back( resElem );
4532       while ( iElem < gens.Length() && gens( iElem+1 ) == sourceElem )
4533         if ( const SMDS_MeshElement* resElem = elems( ++iElem ))
4534           if ( resElem != sourceElem )
4535             resultElems.push_back( resElem );
4536       // do not generate element groups from node ones
4537       if ( sourceElem->GetType() == SMDSAbs_Node &&
4538            elems( iElem )->GetType() != SMDSAbs_Node )
4539         continue;
4540
4541       // add resultElems to groups made by ones the sourceElem belongs to
4542       list< TOldNewGroup >::iterator gOldNew, gLast = groupsOldNew.end();
4543       for ( gOldNew = groupsOldNew.begin(); gOldNew != gLast; ++gOldNew )
4544       {
4545         SMESHDS_GroupBase* oldGroup = gOldNew->first;
4546         if ( oldGroup->Contains( sourceElem )) // sourceElem in oldGroup
4547         {
4548           SMDS_MeshGroup* & newGroup = gOldNew->second;
4549           if ( !newGroup )// create a new group
4550           {
4551             // make a name
4552             string name = oldGroup->GetStoreName();
4553             if ( !targetMesh ) {
4554               name += "_";
4555               name += postfix;
4556               int nb = 0;
4557               while ( !groupNames.insert( name ).second ) // name exists
4558               {
4559                 if ( nb == 0 ) {
4560                   name += "_1";
4561                 }
4562                 else {
4563                   TCollection_AsciiString nbStr(nb+1);
4564                   name.resize( name.rfind('_')+1 );
4565                   name += nbStr.ToCString();
4566                 }
4567                 ++nb;
4568               }
4569             }
4570             // make a group
4571             int id;
4572             SMESH_Group* group = mesh->AddGroup( resultElems.back()->GetType(),
4573                                                  name.c_str(), id );
4574             SMESHDS_Group* groupDS = static_cast<SMESHDS_Group*>(group->GetGroupDS());
4575             newGroup = & groupDS->SMDSGroup();
4576             newGroupIDs->push_back( id );
4577           }
4578
4579           // fill in a new group
4580           list< const SMDS_MeshElement* >::iterator resLast = resultElems.end(), resElemIt;
4581           for ( resElemIt = resultElems.begin(); resElemIt != resLast; ++resElemIt )
4582             newGroup->Add( *resElemIt );
4583         }
4584       }
4585     } // loop on created elements
4586   }// loop on nodes and elements
4587
4588   return newGroupIDs;
4589 }
4590
4591 //=======================================================================
4592 //function : FindCoincidentNodes
4593 //purpose  : Return list of group of nodes close to each other within theTolerance
4594 //           Search among theNodes or in the whole mesh if theNodes is empty using
4595 //           an Octree algorithm
4596 //=======================================================================
4597
4598 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
4599                                             const double                theTolerance,
4600                                             TListOfListOfNodes &        theGroupsOfNodes)
4601 {
4602   myLastCreatedElems.Clear();
4603   myLastCreatedNodes.Clear();
4604
4605   set<const SMDS_MeshNode*> nodes;
4606   if ( theNodes.empty() )
4607   { // get all nodes in the mesh
4608     SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
4609     while ( nIt->more() )
4610       nodes.insert( nodes.end(),nIt->next());
4611   }
4612   else
4613     nodes=theNodes;
4614   SMESH_OctreeNode::FindCoincidentNodes ( nodes, &theGroupsOfNodes, theTolerance);
4615
4616 }
4617
4618 //=======================================================================
4619 /*!
4620  * \brief Implementation of search for the node closest to point
4621  */
4622 //=======================================================================
4623
4624 struct SMESH_NodeSearcherImpl: public SMESH_NodeSearcher
4625 {
4626   /*!
4627    * \brief Constructor
4628    */
4629   SMESH_NodeSearcherImpl( const SMESHDS_Mesh* theMesh )
4630   {
4631     set<const SMDS_MeshNode*> nodes;
4632     if ( theMesh ) {
4633       SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator();
4634       while ( nIt->more() )
4635         nodes.insert( nodes.end(), nIt->next() );
4636     }
4637     myOctreeNode = new SMESH_OctreeNode(nodes) ;
4638   }
4639   /*!
4640    * \brief Do it's job
4641    */
4642   const SMDS_MeshNode* FindClosestTo( const gp_Pnt& thePnt )
4643   {
4644     SMDS_MeshNode tgtNode( thePnt.X(), thePnt.Y(), thePnt.Z() );
4645     list<const SMDS_MeshNode*> nodes;
4646     const double precision = 1e-6;
4647     myOctreeNode->NodesAround( &tgtNode, &nodes, precision );
4648
4649     double minSqDist = DBL_MAX;
4650     Bnd_B3d box;
4651     if ( nodes.empty() )  // get all nodes of OctreeNode's closest to thePnt
4652     {
4653       // sort leafs by their distance from thePnt
4654       typedef map< double, SMESH_OctreeNode* > TDistTreeMap;
4655       TDistTreeMap treeMap;
4656       list< SMESH_OctreeNode* > treeList;
4657       list< SMESH_OctreeNode* >::iterator trIt;
4658       treeList.push_back( myOctreeNode );
4659       for ( trIt = treeList.begin(); trIt != treeList.end(); ++trIt)
4660       {
4661         SMESH_OctreeNode* tree = *trIt;
4662         if ( !tree->isLeaf() ) { // put children to the queue
4663           SMESH_OctreeNodeIteratorPtr cIt = tree->GetChildrenIterator();
4664           while ( cIt->more() )
4665             treeList.push_back( cIt->next() );
4666         }
4667         else if ( tree->NbNodes() ) { // put tree to treeMap
4668           tree->getBox( box );
4669           double sqDist = thePnt.SquareDistance( 0.5 * ( box.CornerMin() + box.CornerMax() ));
4670           pair<TDistTreeMap::iterator,bool> it_in = treeMap.insert( make_pair( sqDist, tree ));
4671           if ( !it_in.second ) // not unique distance to box center
4672             treeMap.insert( it_in.first, make_pair( sqDist - 1e-13*treeMap.size(), tree ));
4673         }
4674       }
4675       // find distance after which there is no sense to check tree's
4676       double sqLimit = DBL_MAX;
4677       TDistTreeMap::iterator sqDist_tree = treeMap.begin();
4678       if ( treeMap.size() > 5 ) {
4679         SMESH_OctreeNode* closestTree = sqDist_tree->second;
4680         closestTree->getBox( box );
4681         double limit = sqrt( sqDist_tree->first ) + sqrt ( box.SquareExtent() );
4682         sqLimit = limit * limit;
4683       }
4684       // get all nodes from trees
4685       for ( ; sqDist_tree != treeMap.end(); ++sqDist_tree) {
4686         if ( sqDist_tree->first > sqLimit )
4687           break;
4688         SMESH_OctreeNode* tree = sqDist_tree->second;
4689         tree->NodesAround( tree->GetNodeIterator()->next(), &nodes );
4690       }
4691     }
4692     // find closest among nodes
4693     minSqDist = DBL_MAX;
4694     const SMDS_MeshNode* closestNode = 0;
4695     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
4696     for ( ; nIt != nodes.end(); ++nIt ) {
4697       double sqDist = thePnt.SquareDistance( TNodeXYZ( *nIt ) );
4698       if ( minSqDist > sqDist ) {
4699         closestNode = *nIt;
4700         minSqDist = sqDist;
4701       }
4702     }
4703     return closestNode;
4704   }
4705   /*!
4706    * \brief Destructor
4707    */
4708   ~SMESH_NodeSearcherImpl() { delete myOctreeNode; }
4709 private:
4710   SMESH_OctreeNode* myOctreeNode;
4711 };
4712
4713 //=======================================================================
4714 /*!
4715  * \brief Return SMESH_NodeSearcher
4716  */
4717 //=======================================================================
4718
4719 SMESH_NodeSearcher* SMESH_MeshEditor::GetNodeSearcher() 
4720 {
4721   return new SMESH_NodeSearcherImpl( GetMeshDS() );
4722 }
4723
4724 //=======================================================================
4725 //function : SimplifyFace
4726 //purpose  :
4727 //=======================================================================
4728 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
4729                                     vector<const SMDS_MeshNode *>&      poly_nodes,
4730                                     vector<int>&                        quantities) const
4731 {
4732   int nbNodes = faceNodes.size();
4733
4734   if (nbNodes < 3)
4735     return 0;
4736
4737   set<const SMDS_MeshNode*> nodeSet;
4738
4739   // get simple seq of nodes
4740   //const SMDS_MeshNode* simpleNodes[ nbNodes ];
4741   vector<const SMDS_MeshNode*> simpleNodes( nbNodes );
4742   int iSimple = 0, nbUnique = 0;
4743
4744   simpleNodes[iSimple++] = faceNodes[0];
4745   nbUnique++;
4746   for (int iCur = 1; iCur < nbNodes; iCur++) {
4747     if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
4748       simpleNodes[iSimple++] = faceNodes[iCur];
4749       if (nodeSet.insert( faceNodes[iCur] ).second)
4750         nbUnique++;
4751     }
4752   }
4753   int nbSimple = iSimple;
4754   if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
4755     nbSimple--;
4756     iSimple--;
4757   }
4758
4759   if (nbUnique < 3)
4760     return 0;
4761
4762   // separate loops
4763   int nbNew = 0;
4764   bool foundLoop = (nbSimple > nbUnique);
4765   while (foundLoop) {
4766     foundLoop = false;
4767     set<const SMDS_MeshNode*> loopSet;
4768     for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
4769       const SMDS_MeshNode* n = simpleNodes[iSimple];
4770       if (!loopSet.insert( n ).second) {
4771         foundLoop = true;
4772
4773         // separate loop
4774         int iC = 0, curLast = iSimple;
4775         for (; iC < curLast; iC++) {
4776           if (simpleNodes[iC] == n) break;
4777         }
4778         int loopLen = curLast - iC;
4779         if (loopLen > 2) {
4780           // create sub-element
4781           nbNew++;
4782           quantities.push_back(loopLen);
4783           for (; iC < curLast; iC++) {
4784             poly_nodes.push_back(simpleNodes[iC]);
4785           }
4786         }
4787         // shift the rest nodes (place from the first loop position)
4788         for (iC = curLast + 1; iC < nbSimple; iC++) {
4789           simpleNodes[iC - loopLen] = simpleNodes[iC];
4790         }
4791         nbSimple -= loopLen;
4792         iSimple -= loopLen;
4793       }
4794     } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
4795   } // while (foundLoop)
4796
4797   if (iSimple > 2) {
4798     nbNew++;
4799     quantities.push_back(iSimple);
4800     for (int i = 0; i < iSimple; i++)
4801       poly_nodes.push_back(simpleNodes[i]);
4802   }
4803
4804   return nbNew;
4805 }
4806
4807 //=======================================================================
4808 //function : MergeNodes
4809 //purpose  : In each group, the cdr of nodes are substituted by the first one
4810 //           in all elements.
4811 //=======================================================================
4812
4813 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
4814 {
4815   myLastCreatedElems.Clear();
4816   myLastCreatedNodes.Clear();
4817
4818   SMESHDS_Mesh* aMesh = GetMeshDS();
4819
4820   TNodeNodeMap nodeNodeMap; // node to replace - new node
4821   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
4822   list< int > rmElemIds, rmNodeIds;
4823
4824   // Fill nodeNodeMap and elems
4825
4826   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
4827   for ( ; grIt != theGroupsOfNodes.end(); grIt++ ) {
4828     list<const SMDS_MeshNode*>& nodes = *grIt;
4829     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
4830     const SMDS_MeshNode* nToKeep = *nIt;
4831     for ( ++nIt; nIt != nodes.end(); nIt++ ) {
4832       const SMDS_MeshNode* nToRemove = *nIt;
4833       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
4834       if ( nToRemove != nToKeep ) {
4835         rmNodeIds.push_back( nToRemove->GetID() );
4836         AddToSameGroups( nToKeep, nToRemove, aMesh );
4837       }
4838
4839       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
4840       while ( invElemIt->more() ) {
4841         const SMDS_MeshElement* elem = invElemIt->next();
4842           elems.insert(elem);
4843       }
4844     }
4845   }
4846   // Change element nodes or remove an element
4847
4848   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
4849   for ( ; eIt != elems.end(); eIt++ ) {
4850     const SMDS_MeshElement* elem = *eIt;
4851     int nbNodes = elem->NbNodes();
4852     int aShapeId = FindShape( elem );
4853
4854     set<const SMDS_MeshNode*> nodeSet;
4855     vector< const SMDS_MeshNode*> curNodes( nbNodes ), uniqueNodes( nbNodes );
4856     int iUnique = 0, iCur = 0, nbRepl = 0;
4857     vector<int> iRepl( nbNodes );
4858
4859     // get new seq of nodes
4860     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4861     while ( itN->more() ) {
4862       const SMDS_MeshNode* n =
4863         static_cast<const SMDS_MeshNode*>( itN->next() );
4864
4865       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
4866       if ( nnIt != nodeNodeMap.end() ) { // n sticks
4867         n = (*nnIt).second;
4868         iRepl[ nbRepl++ ] = iCur;
4869       }
4870       curNodes[ iCur ] = n;
4871       bool isUnique = nodeSet.insert( n ).second;
4872       if ( isUnique )
4873         uniqueNodes[ iUnique++ ] = n;
4874       iCur++;
4875     }
4876
4877     // Analyse element topology after replacement
4878
4879     bool isOk = true;
4880     int nbUniqueNodes = nodeSet.size();
4881     if ( nbNodes != nbUniqueNodes ) { // some nodes stick
4882       // Polygons and Polyhedral volumes
4883       if (elem->IsPoly()) {
4884
4885         if (elem->GetType() == SMDSAbs_Face) {
4886           // Polygon
4887           vector<const SMDS_MeshNode *> face_nodes (nbNodes);
4888           int inode = 0;
4889           for (; inode < nbNodes; inode++) {
4890             face_nodes[inode] = curNodes[inode];
4891           }
4892
4893           vector<const SMDS_MeshNode *> polygons_nodes;
4894           vector<int> quantities;
4895           int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
4896
4897           if (nbNew > 0) {
4898             inode = 0;
4899             for (int iface = 0; iface < nbNew - 1; iface++) {
4900               int nbNodes = quantities[iface];
4901               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4902               for (int ii = 0; ii < nbNodes; ii++, inode++) {
4903                 poly_nodes[ii] = polygons_nodes[inode];
4904               }
4905               SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4906               myLastCreatedElems.Append(newElem);
4907               if (aShapeId)
4908                 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4909             }
4910             aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
4911           }
4912           else {
4913             rmElemIds.push_back(elem->GetID());
4914           }
4915
4916         }
4917         else if (elem->GetType() == SMDSAbs_Volume) {
4918           // Polyhedral volume
4919           if (nbUniqueNodes < 4) {
4920             rmElemIds.push_back(elem->GetID());
4921           }
4922           else {
4923             // each face has to be analized in order to check volume validity
4924             const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4925               static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
4926             if (aPolyedre) {
4927               int nbFaces = aPolyedre->NbFaces();
4928
4929               vector<const SMDS_MeshNode *> poly_nodes;
4930               vector<int> quantities;
4931
4932               for (int iface = 1; iface <= nbFaces; iface++) {
4933                 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4934                 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
4935
4936                 for (int inode = 1; inode <= nbFaceNodes; inode++) {
4937                   const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
4938                   TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
4939                   if (nnIt != nodeNodeMap.end()) { // faceNode sticks
4940                     faceNode = (*nnIt).second;
4941                   }
4942                   faceNodes[inode - 1] = faceNode;
4943                 }
4944
4945                 SimplifyFace(faceNodes, poly_nodes, quantities);
4946               }
4947
4948               if (quantities.size() > 3) {
4949                 // to be done: remove coincident faces
4950               }
4951
4952               if (quantities.size() > 3)
4953                 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4954               else
4955                 rmElemIds.push_back(elem->GetID());
4956
4957             }
4958             else {
4959               rmElemIds.push_back(elem->GetID());
4960             }
4961           }
4962         }
4963         else {
4964         }
4965
4966         continue;
4967       }
4968
4969       // Regular elements
4970       switch ( nbNodes ) {
4971       case 2: ///////////////////////////////////// EDGE
4972         isOk = false; break;
4973       case 3: ///////////////////////////////////// TRIANGLE
4974         isOk = false; break;
4975       case 4:
4976         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
4977           isOk = false;
4978         else { //////////////////////////////////// QUADRANGLE
4979           if ( nbUniqueNodes < 3 )
4980             isOk = false;
4981           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
4982             isOk = false; // opposite nodes stick
4983         }
4984         break;
4985       case 6: ///////////////////////////////////// PENTAHEDRON
4986         if ( nbUniqueNodes == 4 ) {
4987           // ---------------------------------> tetrahedron
4988           if (nbRepl == 3 &&
4989               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
4990             // all top nodes stick: reverse a bottom
4991             uniqueNodes[ 0 ] = curNodes [ 1 ];
4992             uniqueNodes[ 1 ] = curNodes [ 0 ];
4993           }
4994           else if (nbRepl == 3 &&
4995                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
4996             // all bottom nodes stick: set a top before
4997             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
4998             uniqueNodes[ 0 ] = curNodes [ 3 ];
4999             uniqueNodes[ 1 ] = curNodes [ 4 ];
5000             uniqueNodes[ 2 ] = curNodes [ 5 ];
5001           }
5002           else if (nbRepl == 4 &&
5003                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
5004             // a lateral face turns into a line: reverse a bottom
5005             uniqueNodes[ 0 ] = curNodes [ 1 ];
5006             uniqueNodes[ 1 ] = curNodes [ 0 ];
5007           }
5008           else
5009             isOk = false;
5010         }
5011         else if ( nbUniqueNodes == 5 ) {
5012           // PENTAHEDRON --------------------> 2 tetrahedrons
5013           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
5014             // a bottom node sticks with a linked top one
5015             // 1.
5016             SMDS_MeshElement* newElem =
5017               aMesh->AddVolume(curNodes[ 3 ],
5018                                curNodes[ 4 ],
5019                                curNodes[ 5 ],
5020                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
5021             myLastCreatedElems.Append(newElem);
5022             if ( aShapeId )
5023               aMesh->SetMeshElementOnShape( newElem, aShapeId );
5024             // 2. : reverse a bottom
5025             uniqueNodes[ 0 ] = curNodes [ 1 ];
5026             uniqueNodes[ 1 ] = curNodes [ 0 ];
5027             nbUniqueNodes = 4;
5028           }
5029           else
5030             isOk = false;
5031         }
5032         else
5033           isOk = false;
5034         break;
5035       case 8: {
5036         if(elem->IsQuadratic()) { // Quadratic quadrangle
5037           //   1    5    2
5038           //    +---+---+
5039           //    |       |
5040           //    |       |
5041           //   4+       +6
5042           //    |       |
5043           //    |       |
5044           //    +---+---+
5045           //   0    7    3
5046           isOk = false;
5047           if(nbRepl==3) {
5048             nbUniqueNodes = 6;
5049             if( iRepl[0]==0 && iRepl[1]==1 && iRepl[2]==4 ) {
5050               uniqueNodes[0] = curNodes[0];
5051               uniqueNodes[1] = curNodes[2];
5052               uniqueNodes[2] = curNodes[3];
5053               uniqueNodes[3] = curNodes[5];
5054               uniqueNodes[4] = curNodes[6];
5055               uniqueNodes[5] = curNodes[7];
5056               isOk = true;
5057             }
5058             if( iRepl[0]==0 && iRepl[1]==3 && iRepl[2]==7 ) {
5059               uniqueNodes[0] = curNodes[0];
5060               uniqueNodes[1] = curNodes[1];
5061               uniqueNodes[2] = curNodes[2];
5062               uniqueNodes[3] = curNodes[4];
5063               uniqueNodes[4] = curNodes[5];
5064               uniqueNodes[5] = curNodes[6];
5065               isOk = true;
5066             }
5067             if( iRepl[0]==0 && iRepl[1]==4 && iRepl[2]==7 ) {
5068               uniqueNodes[0] = curNodes[1];
5069               uniqueNodes[1] = curNodes[2];
5070               uniqueNodes[2] = curNodes[3];
5071               uniqueNodes[3] = curNodes[5];
5072               uniqueNodes[4] = curNodes[6];
5073               uniqueNodes[5] = curNodes[0];
5074               isOk = true;
5075             }
5076             if( iRepl[0]==1 && iRepl[1]==2 && iRepl[2]==5 ) {
5077               uniqueNodes[0] = curNodes[0];
5078               uniqueNodes[1] = curNodes[1];
5079               uniqueNodes[2] = curNodes[3];
5080               uniqueNodes[3] = curNodes[4];
5081               uniqueNodes[4] = curNodes[6];
5082               uniqueNodes[5] = curNodes[7];
5083               isOk = true;
5084             }
5085             if( iRepl[0]==1 && iRepl[1]==4 && iRepl[2]==5 ) {
5086               uniqueNodes[0] = curNodes[0];
5087               uniqueNodes[1] = curNodes[2];
5088               uniqueNodes[2] = curNodes[3];
5089               uniqueNodes[3] = curNodes[1];
5090               uniqueNodes[4] = curNodes[6];
5091               uniqueNodes[5] = curNodes[7];
5092               isOk = true;
5093             }
5094             if( iRepl[0]==2 && iRepl[1]==3 && iRepl[2]==6 ) {
5095               uniqueNodes[0] = curNodes[0];
5096               uniqueNodes[1] = curNodes[1];
5097               uniqueNodes[2] = curNodes[2];
5098               uniqueNodes[3] = curNodes[4];
5099               uniqueNodes[4] = curNodes[5];
5100               uniqueNodes[5] = curNodes[7];
5101               isOk = true;
5102             }
5103             if( iRepl[0]==2 && iRepl[1]==5 && iRepl[2]==6 ) {
5104               uniqueNodes[0] = curNodes[0];
5105               uniqueNodes[1] = curNodes[1];
5106               uniqueNodes[2] = curNodes[3];
5107               uniqueNodes[3] = curNodes[4];
5108               uniqueNodes[4] = curNodes[2];
5109               uniqueNodes[5] = curNodes[7];
5110               isOk = true;
5111             }
5112             if( iRepl[0]==3 && iRepl[1]==6 && iRepl[2]==7 ) {
5113               uniqueNodes[0] = curNodes[0];
5114               uniqueNodes[1] = curNodes[1];
5115               uniqueNodes[2] = curNodes[2];
5116               uniqueNodes[3] = curNodes[4];
5117               uniqueNodes[4] = curNodes[5];
5118               uniqueNodes[5] = curNodes[3];
5119               isOk = true;
5120             }
5121           }
5122           break;
5123         }
5124         //////////////////////////////////// HEXAHEDRON
5125         isOk = false;
5126         SMDS_VolumeTool hexa (elem);
5127         hexa.SetExternalNormal();
5128         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
5129           //////////////////////// ---> tetrahedron
5130           for ( int iFace = 0; iFace < 6; iFace++ ) {
5131             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
5132             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
5133                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
5134                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
5135               // one face turns into a point ...
5136               int iOppFace = hexa.GetOppFaceIndex( iFace );
5137               ind = hexa.GetFaceNodesIndices( iOppFace );
5138               int nbStick = 0;
5139               iUnique = 2; // reverse a tetrahedron bottom
5140               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
5141                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
5142                   nbStick++;
5143                 else if ( iUnique >= 0 )
5144                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
5145               }
5146               if ( nbStick == 1 ) {
5147                 // ... and the opposite one - into a triangle.
5148                 // set a top node
5149                 ind = hexa.GetFaceNodesIndices( iFace );
5150                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
5151                 isOk = true;
5152               }
5153               break;
5154             }
5155           }
5156         }
5157         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
5158           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
5159           for ( int iFace = 0; iFace < 6; iFace++ ) {
5160             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
5161             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
5162                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
5163                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
5164               // one face turns into a point ...
5165               int iOppFace = hexa.GetOppFaceIndex( iFace );
5166               ind = hexa.GetFaceNodesIndices( iOppFace );
5167               int nbStick = 0;
5168               iUnique = 2;  // reverse a tetrahedron 1 bottom
5169               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
5170                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
5171                   nbStick++;
5172                 else if ( iUnique >= 0 )
5173                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
5174               }
5175               if ( nbStick == 0 ) {
5176                 // ... and the opposite one is a quadrangle
5177                 // set a top node
5178                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
5179                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
5180                 nbUniqueNodes = 4;
5181                 // tetrahedron 2
5182                 SMDS_MeshElement* newElem =
5183                   aMesh->AddVolume(curNodes[ind[ 0 ]],
5184                                    curNodes[ind[ 3 ]],
5185                                    curNodes[ind[ 2 ]],
5186                                    curNodes[indTop[ 0 ]]);
5187                 myLastCreatedElems.Append(newElem);
5188                 if ( aShapeId )
5189                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
5190                 isOk = true;
5191               }
5192               break;
5193             }
5194           }
5195         }
5196         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
5197           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
5198           // find indices of quad and tri faces
5199           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
5200           for ( iFace = 0; iFace < 6; iFace++ ) {
5201             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
5202             nodeSet.clear();
5203             for ( iCur = 0; iCur < 4; iCur++ )
5204               nodeSet.insert( curNodes[ind[ iCur ]] );
5205             nbUniqueNodes = nodeSet.size();
5206             if ( nbUniqueNodes == 3 )
5207               iTriFace[ nbTri++ ] = iFace;
5208             else if ( nbUniqueNodes == 4 )
5209               iQuadFace[ nbQuad++ ] = iFace;
5210           }
5211           if (nbQuad == 2 && nbTri == 4 &&
5212               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
5213             // 2 opposite quadrangles stuck with a diagonal;
5214             // sample groups of merged indices: (0-4)(2-6)
5215             // --------------------------------------------> 2 tetrahedrons
5216             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
5217             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
5218             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
5219             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
5220                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
5221               // stuck with 0-2 diagonal
5222               i0  = ind1[ 3 ];
5223               i1d = ind1[ 0 ];
5224               i2  = ind1[ 1 ];
5225               i3d = ind1[ 2 ];
5226               i0t = ind2[ 1 ];
5227               i2t = ind2[ 3 ];
5228             }
5229             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
5230                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
5231               // stuck with 1-3 diagonal
5232               i0  = ind1[ 0 ];
5233               i1d = ind1[ 1 ];
5234               i2  = ind1[ 2 ];
5235               i3d = ind1[ 3 ];
5236               i0t = ind2[ 0 ];
5237               i2t = ind2[ 1 ];
5238             }
5239             else {
5240               ASSERT(0);
5241             }
5242             // tetrahedron 1
5243             uniqueNodes[ 0 ] = curNodes [ i0 ];
5244             uniqueNodes[ 1 ] = curNodes [ i1d ];
5245             uniqueNodes[ 2 ] = curNodes [ i3d ];
5246             uniqueNodes[ 3 ] = curNodes [ i0t ];
5247             nbUniqueNodes = 4;
5248             // tetrahedron 2
5249             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
5250                                                          curNodes[ i2 ],
5251                                                          curNodes[ i3d ],
5252                                                          curNodes[ i2t ]);
5253             myLastCreatedElems.Append(newElem);
5254             if ( aShapeId )
5255               aMesh->SetMeshElementOnShape( newElem, aShapeId );
5256             isOk = true;
5257           }
5258           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
5259                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
5260             // --------------------------------------------> prism
5261             // find 2 opposite triangles
5262             nbUniqueNodes = 6;
5263             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
5264               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
5265                 // find indices of kept and replaced nodes
5266                 // and fill unique nodes of 2 opposite triangles
5267                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
5268                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
5269                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
5270                 // fill unique nodes
5271                 iUnique = 0;
5272                 isOk = true;
5273                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
5274                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
5275                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
5276                   if ( n == nInit ) {
5277                     // iCur of a linked node of the opposite face (make normals co-directed):
5278                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
5279                     // check that correspondent corners of triangles are linked
5280                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
5281                       isOk = false;
5282                     else {
5283                       uniqueNodes[ iUnique ] = n;
5284                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
5285                       iUnique++;
5286                     }
5287                   }
5288                 }
5289                 break;
5290               }
5291             }
5292           }
5293         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
5294         break;
5295       } // HEXAHEDRON
5296
5297       default:
5298         isOk = false;
5299       } // switch ( nbNodes )
5300
5301     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
5302
5303     if ( isOk ) {
5304       if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
5305         // Change nodes of polyedre
5306         const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
5307           static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
5308         if (aPolyedre) {
5309           int nbFaces = aPolyedre->NbFaces();
5310
5311           vector<const SMDS_MeshNode *> poly_nodes;
5312           vector<int> quantities (nbFaces);
5313
5314           for (int iface = 1; iface <= nbFaces; iface++) {
5315             int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
5316             quantities[iface - 1] = nbFaceNodes;
5317
5318             for (inode = 1; inode <= nbFaceNodes; inode++) {
5319               const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
5320
5321               TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
5322               if (nnIt != nodeNodeMap.end()) { // curNode sticks
5323                 curNode = (*nnIt).second;
5324               }
5325               poly_nodes.push_back(curNode);
5326             }
5327           }
5328           aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
5329         }
5330       }
5331       else {
5332         // Change regular element or polygon
5333         aMesh->ChangeElementNodes( elem, & uniqueNodes[0], nbUniqueNodes );
5334       }
5335     }
5336     else {
5337       // Remove invalid regular element or invalid polygon
5338       rmElemIds.push_back( elem->GetID() );
5339     }
5340
5341   } // loop on elements
5342
5343   // Remove equal nodes and bad elements
5344
5345   Remove( rmNodeIds, true );
5346   Remove( rmElemIds, false );
5347
5348 }
5349
5350
5351 // ========================================================
5352 // class   : SortableElement
5353 // purpose : allow sorting elements basing on their nodes
5354 // ========================================================
5355 class SortableElement : public set <const SMDS_MeshElement*>
5356 {
5357  public:
5358
5359   SortableElement( const SMDS_MeshElement* theElem )
5360     {
5361       myElem = theElem;
5362       SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
5363       while ( nodeIt->more() )
5364         this->insert( nodeIt->next() );
5365     }
5366
5367   const SMDS_MeshElement* Get() const
5368     { return myElem; }
5369
5370   void Set(const SMDS_MeshElement* e) const
5371     { myElem = e; }
5372
5373
5374  private:
5375   mutable const SMDS_MeshElement* myElem;
5376 };
5377
5378 //=======================================================================
5379 //function : FindEqualElements
5380 //purpose  : Return list of group of elements built on the same nodes.
5381 //           Search among theElements or in the whole mesh if theElements is empty
5382 //=======================================================================
5383 void SMESH_MeshEditor::FindEqualElements(set<const SMDS_MeshElement*> & theElements,
5384                                          TListOfListOfElementsID &      theGroupsOfElementsID)
5385 {
5386   myLastCreatedElems.Clear();
5387   myLastCreatedNodes.Clear();
5388
5389   typedef set<const SMDS_MeshElement*> TElemsSet;
5390   typedef map< SortableElement, int > TMapOfNodeSet;
5391   typedef list<int> TGroupOfElems;
5392
5393   TElemsSet elems;
5394   if ( theElements.empty() )
5395   { // get all elements in the mesh
5396     SMDS_ElemIteratorPtr eIt = GetMeshDS()->elementsIterator();
5397     while ( eIt->more() )
5398       elems.insert( elems.end(), eIt->next());
5399   }
5400   else
5401     elems = theElements;
5402
5403   vector< TGroupOfElems > arrayOfGroups;
5404   TGroupOfElems groupOfElems;
5405   TMapOfNodeSet mapOfNodeSet;
5406
5407   TElemsSet::iterator elemIt = elems.begin();
5408   for ( int i = 0, j=0; elemIt != elems.end(); ++elemIt, ++j ) {
5409     const SMDS_MeshElement* curElem = *elemIt;
5410     SortableElement SE(curElem);
5411     int ind = -1;
5412     // check uniqueness
5413     pair< TMapOfNodeSet::iterator, bool> pp = mapOfNodeSet.insert(make_pair(SE, i));
5414     if( !(pp.second) ) {
5415       TMapOfNodeSet::iterator& itSE = pp.first;
5416       ind = (*itSE).second;
5417       arrayOfGroups[ind].push_back(curElem->GetID());
5418     }
5419     else {
5420       groupOfElems.clear();
5421       groupOfElems.push_back(curElem->GetID());
5422       arrayOfGroups.push_back(groupOfElems);
5423       i++;
5424     }
5425   }
5426
5427   vector< TGroupOfElems >::iterator groupIt = arrayOfGroups.begin();
5428   for ( ; groupIt != arrayOfGroups.end(); ++groupIt ) {
5429     groupOfElems = *groupIt;
5430     if ( groupOfElems.size() > 1 ) {
5431       groupOfElems.sort();
5432       theGroupsOfElementsID.push_back(groupOfElems);
5433     }
5434   }
5435 }
5436
5437 //=======================================================================
5438 //function : MergeElements
5439 //purpose  : In each given group, substitute all elements by the first one.
5440 //=======================================================================
5441
5442 void SMESH_MeshEditor::MergeElements(TListOfListOfElementsID & theGroupsOfElementsID)
5443 {
5444   myLastCreatedElems.Clear();
5445   myLastCreatedNodes.Clear();
5446
5447   typedef list<int> TListOfIDs;
5448   TListOfIDs rmElemIds; // IDs of elems to remove
5449
5450   SMESHDS_Mesh* aMesh = GetMeshDS();
5451
5452   TListOfListOfElementsID::iterator groupsIt = theGroupsOfElementsID.begin();
5453   while ( groupsIt != theGroupsOfElementsID.end() ) {
5454     TListOfIDs& aGroupOfElemID = *groupsIt;
5455     aGroupOfElemID.sort();
5456     int elemIDToKeep = aGroupOfElemID.front();
5457     const SMDS_MeshElement* elemToKeep = aMesh->FindElement(elemIDToKeep);
5458     aGroupOfElemID.pop_front();
5459     TListOfIDs::iterator idIt = aGroupOfElemID.begin();
5460     while ( idIt != aGroupOfElemID.end() ) {
5461       int elemIDToRemove = *idIt;
5462       const SMDS_MeshElement* elemToRemove = aMesh->FindElement(elemIDToRemove);
5463       // add the kept element in groups of removed one (PAL15188)
5464       AddToSameGroups( elemToKeep, elemToRemove, aMesh );
5465       rmElemIds.push_back( elemIDToRemove );
5466       ++idIt;
5467     }
5468     ++groupsIt;
5469   }
5470
5471   Remove( rmElemIds, false );
5472 }
5473
5474 //=======================================================================
5475 //function : MergeEqualElements
5476 //purpose  : Remove all but one of elements built on the same nodes.
5477 //=======================================================================
5478
5479 void SMESH_MeshEditor::MergeEqualElements()
5480 {
5481   set<const SMDS_MeshElement*> aMeshElements; /* empty input -
5482                                                  to merge equal elements in the whole mesh */
5483   TListOfListOfElementsID aGroupsOfElementsID;
5484   FindEqualElements(aMeshElements, aGroupsOfElementsID);
5485   MergeElements(aGroupsOfElementsID);
5486 }
5487
5488 //=======================================================================
5489 //function : FindFaceInSet
5490 //purpose  : Return a face having linked nodes n1 and n2 and which is
5491 //           - not in avoidSet,
5492 //           - in elemSet provided that !elemSet.empty()
5493 //=======================================================================
5494
5495 const SMDS_MeshElement*
5496   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*    n1,
5497                                   const SMDS_MeshNode*    n2,
5498                                   const TIDSortedElemSet& elemSet,
5499                                   const TIDSortedElemSet& avoidSet)
5500
5501 {
5502   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
5503   while ( invElemIt->more() ) { // loop on inverse elements of n1
5504     const SMDS_MeshElement* elem = invElemIt->next();
5505     if (avoidSet.find( elem ) != avoidSet.end() )
5506       continue;
5507     if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
5508       continue;
5509     // get face nodes and find index of n1
5510     int i1, nbN = elem->NbNodes(), iNode = 0;
5511     //const SMDS_MeshNode* faceNodes[ nbN ], *n;
5512     vector<const SMDS_MeshNode*> faceNodes( nbN );
5513     const SMDS_MeshNode* n;
5514     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
5515     while ( nIt->more() ) {
5516       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5517       if ( faceNodes[ iNode++ ] == n1 )
5518         i1 = iNode - 1;
5519     }
5520     // find a n2 linked to n1
5521     if(!elem->IsQuadratic()) {
5522       for ( iNode = 0; iNode < 2; iNode++ ) {
5523         if ( iNode ) // node before n1
5524           n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
5525         else         // node after n1
5526           n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
5527         if ( n == n2 )
5528           return elem;
5529       }
5530     }
5531     else { // analysis for quadratic elements
5532       bool IsFind = false;
5533       // check using only corner nodes
5534       for ( iNode = 0; iNode < 2; iNode++ ) {
5535         if ( iNode ) // node before n1
5536           n = faceNodes[ i1 == 0 ? nbN/2 - 1 : i1 - 1 ];
5537         else         // node after n1
5538           n = faceNodes[ i1 + 1 == nbN/2 ? 0 : i1 + 1 ];
5539         if ( n == n2 )
5540           IsFind = true;
5541       }
5542       if(IsFind) {
5543         return elem;
5544       }
5545       else {
5546         // check using all nodes
5547         const SMDS_QuadraticFaceOfNodes* F =
5548           static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5549         // use special nodes iterator
5550         iNode = 0;
5551         SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5552         while ( anIter->more() ) {
5553           faceNodes[iNode] = static_cast<const SMDS_MeshNode*>(anIter->next());
5554           if ( faceNodes[ iNode++ ] == n1 )
5555             i1 = iNode - 1;
5556         }
5557         for ( iNode = 0; iNode < 2; iNode++ ) {
5558           if ( iNode ) // node before n1
5559             n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
5560           else         // node after n1
5561             n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
5562           if ( n == n2 ) {
5563             return elem;
5564           }
5565         }
5566       }
5567     } // end analysis for quadratic elements
5568   }
5569   return 0;
5570 }
5571
5572 //=======================================================================
5573 //function : findAdjacentFace
5574 //purpose  :
5575 //=======================================================================
5576
5577 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
5578                                                 const SMDS_MeshNode* n2,
5579                                                 const SMDS_MeshElement* elem)
5580 {
5581   TIDSortedElemSet elemSet, avoidSet;
5582   if ( elem )
5583     avoidSet.insert ( elem );
5584   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
5585 }
5586
5587 //=======================================================================
5588 //function : FindFreeBorder
5589 //purpose  :
5590 //=======================================================================
5591
5592 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
5593
5594 bool SMESH_MeshEditor::FindFreeBorder (const SMDS_MeshNode*             theFirstNode,
5595                                        const SMDS_MeshNode*             theSecondNode,
5596                                        const SMDS_MeshNode*             theLastNode,
5597                                        list< const SMDS_MeshNode* > &   theNodes,
5598                                        list< const SMDS_MeshElement* >& theFaces)
5599 {
5600   if ( !theFirstNode || !theSecondNode )
5601     return false;
5602   // find border face between theFirstNode and theSecondNode
5603   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
5604   if ( !curElem )
5605     return false;
5606
5607   theFaces.push_back( curElem );
5608   theNodes.push_back( theFirstNode );
5609   theNodes.push_back( theSecondNode );
5610
5611   //vector<const SMDS_MeshNode*> nodes;
5612   const SMDS_MeshNode *nIgnore = theFirstNode, *nStart = theSecondNode;
5613   set < const SMDS_MeshElement* > foundElems;
5614   bool needTheLast = ( theLastNode != 0 );
5615
5616   while ( nStart != theLastNode ) {
5617     if ( nStart == theFirstNode )
5618       return !needTheLast;
5619
5620     // find all free border faces sharing form nStart
5621
5622     list< const SMDS_MeshElement* > curElemList;
5623     list< const SMDS_MeshNode* > nStartList;
5624     SMDS_ElemIteratorPtr invElemIt = nStart->GetInverseElementIterator(SMDSAbs_Face);
5625     while ( invElemIt->more() ) {
5626       const SMDS_MeshElement* e = invElemIt->next();
5627       if ( e == curElem || foundElems.insert( e ).second ) {
5628         // get nodes
5629         int iNode = 0, nbNodes = e->NbNodes();
5630         //const SMDS_MeshNode* nodes[nbNodes+1];
5631         vector<const SMDS_MeshNode*> nodes(nbNodes+1);
5632         
5633         if(e->IsQuadratic()) {
5634           const SMDS_QuadraticFaceOfNodes* F =
5635             static_cast<const SMDS_QuadraticFaceOfNodes*>(e);
5636           // use special nodes iterator
5637           SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5638           while( anIter->more() ) {
5639             nodes[ iNode++ ] = anIter->next();
5640           }
5641         }
5642         else {
5643           SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5644           while ( nIt->more() )
5645             nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5646         }
5647         nodes[ iNode ] = nodes[ 0 ];
5648         // check 2 links
5649         for ( iNode = 0; iNode < nbNodes; iNode++ )
5650           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
5651                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
5652               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
5653           {
5654             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
5655             curElemList.push_back( e );
5656           }
5657       }
5658     }
5659     // analyse the found
5660
5661     int nbNewBorders = curElemList.size();
5662     if ( nbNewBorders == 0 ) {
5663       // no free border furthermore
5664       return !needTheLast;
5665     }
5666     else if ( nbNewBorders == 1 ) {
5667       // one more element found
5668       nIgnore = nStart;
5669       nStart = nStartList.front();
5670       curElem = curElemList.front();
5671       theFaces.push_back( curElem );
5672       theNodes.push_back( nStart );
5673     }
5674     else {
5675       // several continuations found
5676       list< const SMDS_MeshElement* >::iterator curElemIt;
5677       list< const SMDS_MeshNode* >::iterator nStartIt;
5678       // check if one of them reached the last node
5679       if ( needTheLast ) {
5680         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5681              curElemIt!= curElemList.end();
5682              curElemIt++, nStartIt++ )
5683           if ( *nStartIt == theLastNode ) {
5684             theFaces.push_back( *curElemIt );
5685             theNodes.push_back( *nStartIt );
5686             return true;
5687           }
5688       }
5689       // find the best free border by the continuations
5690       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
5691       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
5692       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5693            curElemIt!= curElemList.end();
5694            curElemIt++, nStartIt++ )
5695       {
5696         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
5697         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
5698         // find one more free border
5699         if ( ! FindFreeBorder( nStart, *nStartIt, theLastNode, *cNL, *cFL )) {
5700           cNL->clear();
5701           cFL->clear();
5702         }
5703         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
5704           // choice: clear a worse one
5705           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
5706           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
5707           contNodes[ iWorse ].clear();
5708           contFaces[ iWorse ].clear();
5709         }
5710       }
5711       if ( contNodes[0].empty() && contNodes[1].empty() )
5712         return false;
5713
5714       // append the best free border
5715       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
5716       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
5717       theNodes.pop_back(); // remove nIgnore
5718       theNodes.pop_back(); // remove nStart
5719       theFaces.pop_back(); // remove curElem
5720       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
5721       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
5722       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
5723       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
5724       return true;
5725
5726     } // several continuations found
5727   } // while ( nStart != theLastNode )
5728
5729   return true;
5730 }
5731
5732 //=======================================================================
5733 //function : CheckFreeBorderNodes
5734 //purpose  : Return true if the tree nodes are on a free border
5735 //=======================================================================
5736
5737 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
5738                                             const SMDS_MeshNode* theNode2,
5739                                             const SMDS_MeshNode* theNode3)
5740 {
5741   list< const SMDS_MeshNode* > nodes;
5742   list< const SMDS_MeshElement* > faces;
5743   return FindFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
5744 }
5745
5746 //=======================================================================
5747 //function : SewFreeBorder
5748 //purpose  :
5749 //=======================================================================
5750
5751 SMESH_MeshEditor::Sew_Error
5752   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
5753                                    const SMDS_MeshNode* theBordSecondNode,
5754                                    const SMDS_MeshNode* theBordLastNode,
5755                                    const SMDS_MeshNode* theSideFirstNode,
5756                                    const SMDS_MeshNode* theSideSecondNode,
5757                                    const SMDS_MeshNode* theSideThirdNode,
5758                                    const bool           theSideIsFreeBorder,
5759                                    const bool           toCreatePolygons,
5760                                    const bool           toCreatePolyedrs)
5761 {
5762   myLastCreatedElems.Clear();
5763   myLastCreatedNodes.Clear();
5764
5765   MESSAGE("::SewFreeBorder()");
5766   Sew_Error aResult = SEW_OK;
5767
5768   // ====================================
5769   //    find side nodes and elements
5770   // ====================================
5771
5772   list< const SMDS_MeshNode* > nSide[ 2 ];
5773   list< const SMDS_MeshElement* > eSide[ 2 ];
5774   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
5775   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
5776
5777   // Free border 1
5778   // --------------
5779   if (!FindFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
5780                       nSide[0], eSide[0])) {
5781     MESSAGE(" Free Border 1 not found " );
5782     aResult = SEW_BORDER1_NOT_FOUND;
5783   }
5784   if (theSideIsFreeBorder) {
5785     // Free border 2
5786     // --------------
5787     if (!FindFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
5788                         nSide[1], eSide[1])) {
5789       MESSAGE(" Free Border 2 not found " );
5790       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
5791     }
5792   }
5793   if ( aResult != SEW_OK )
5794     return aResult;
5795
5796   if (!theSideIsFreeBorder) {
5797     // Side 2
5798     // --------------
5799
5800     // -------------------------------------------------------------------------
5801     // Algo:
5802     // 1. If nodes to merge are not coincident, move nodes of the free border
5803     //    from the coord sys defined by the direction from the first to last
5804     //    nodes of the border to the correspondent sys of the side 2
5805     // 2. On the side 2, find the links most co-directed with the correspondent
5806     //    links of the free border
5807     // -------------------------------------------------------------------------
5808
5809     // 1. Since sewing may brake if there are volumes to split on the side 2,
5810     //    we wont move nodes but just compute new coordinates for them
5811     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
5812     TNodeXYZMap nBordXYZ;
5813     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
5814     list< const SMDS_MeshNode* >::iterator nBordIt;
5815
5816     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
5817     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
5818     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
5819     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
5820     double tol2 = 1.e-8;
5821     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
5822     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 ) {
5823       // Need node movement.
5824
5825       // find X and Z axes to create trsf
5826       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
5827       gp_Vec X = Zs ^ Zb;
5828       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
5829         // Zb || Zs
5830         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
5831
5832       // coord systems
5833       gp_Ax3 toBordAx( Pb1, Zb, X );
5834       gp_Ax3 fromSideAx( Ps1, Zs, X );
5835       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
5836       // set trsf
5837       gp_Trsf toBordSys, fromSide2Sys;
5838       toBordSys.SetTransformation( toBordAx );
5839       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
5840       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
5841
5842       // move
5843       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5844         const SMDS_MeshNode* n = *nBordIt;
5845         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
5846         toBordSys.Transforms( xyz );
5847         fromSide2Sys.Transforms( xyz );
5848         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
5849       }
5850     }
5851     else {
5852       // just insert nodes XYZ in the nBordXYZ map
5853       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5854         const SMDS_MeshNode* n = *nBordIt;
5855         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
5856       }
5857     }
5858
5859     // 2. On the side 2, find the links most co-directed with the correspondent
5860     //    links of the free border
5861
5862     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
5863     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
5864     sideNodes.push_back( theSideFirstNode );
5865
5866     bool hasVolumes = false;
5867     LinkID_Gen aLinkID_Gen( GetMeshDS() );
5868     set<long> foundSideLinkIDs, checkedLinkIDs;
5869     SMDS_VolumeTool volume;
5870     //const SMDS_MeshNode* faceNodes[ 4 ];
5871
5872     const SMDS_MeshNode*    sideNode;
5873     const SMDS_MeshElement* sideElem;
5874     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
5875     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
5876     nBordIt = bordNodes.begin();
5877     nBordIt++;
5878     // border node position and border link direction to compare with
5879     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
5880     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
5881     // choose next side node by link direction or by closeness to
5882     // the current border node:
5883     bool searchByDir = ( *nBordIt != theBordLastNode );
5884     do {
5885       // find the next node on the Side 2
5886       sideNode = 0;
5887       double maxDot = -DBL_MAX, minDist = DBL_MAX;
5888       long linkID;
5889       checkedLinkIDs.clear();
5890       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
5891
5892       // loop on inverse elements of current node (prevSideNode) on the Side 2
5893       SMDS_ElemIteratorPtr invElemIt = prevSideNode->GetInverseElementIterator();
5894       while ( invElemIt->more() )
5895       {
5896         const SMDS_MeshElement* elem = invElemIt->next();
5897         // prepare data for a loop on links coming to prevSideNode, of a face or a volume
5898         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
5899         vector< const SMDS_MeshNode* > faceNodes( nbNodes, (const SMDS_MeshNode*)0 );
5900         bool isVolume = volume.Set( elem );
5901         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : & faceNodes[0];
5902         if ( isVolume ) // --volume
5903           hasVolumes = true;
5904         else if ( elem->GetType()==SMDSAbs_Face ) { // --face
5905           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
5906           if(elem->IsQuadratic()) {
5907             const SMDS_QuadraticFaceOfNodes* F =
5908               static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5909             // use special nodes iterator
5910             SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5911             while( anIter->more() ) {
5912               nodes[ iNode ] = anIter->next();
5913               if ( nodes[ iNode++ ] == prevSideNode )
5914                 iPrevNode = iNode - 1;
5915             }
5916           }
5917           else {
5918             SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
5919             while ( nIt->more() ) {
5920               nodes[ iNode ] = cast2Node( nIt->next() );
5921               if ( nodes[ iNode++ ] == prevSideNode )
5922                 iPrevNode = iNode - 1;
5923             }
5924           }
5925           // there are 2 links to check
5926           nbNodes = 2;
5927         }
5928         else // --edge
5929           continue;
5930         // loop on links, to be precise, on the second node of links
5931         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
5932           const SMDS_MeshNode* n = nodes[ iNode ];
5933           if ( isVolume ) {
5934             if ( !volume.IsLinked( n, prevSideNode ))
5935               continue;
5936           }
5937           else {
5938             if ( iNode ) // a node before prevSideNode
5939               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
5940             else         // a node after prevSideNode
5941               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
5942           }
5943           // check if this link was already used
5944           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
5945           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
5946           if (!isJustChecked &&
5947               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() )
5948           {
5949             // test a link geometrically
5950             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
5951             bool linkIsBetter = false;
5952             double dot = 0.0, dist = 0.0;
5953             if ( searchByDir ) { // choose most co-directed link
5954               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
5955               linkIsBetter = ( dot > maxDot );
5956             }
5957             else { // choose link with the node closest to bordPos
5958               dist = ( nextXYZ - bordPos ).SquareModulus();
5959               linkIsBetter = ( dist < minDist );
5960             }
5961             if ( linkIsBetter ) {
5962               maxDot = dot;
5963               minDist = dist;
5964               linkID = iLink;
5965               sideNode = n;
5966               sideElem = elem;
5967             }
5968           }
5969         }
5970       } // loop on inverse elements of prevSideNode
5971
5972       if ( !sideNode ) {
5973         MESSAGE(" Cant find path by links of the Side 2 ");
5974         return SEW_BAD_SIDE_NODES;
5975       }
5976       sideNodes.push_back( sideNode );
5977       sideElems.push_back( sideElem );
5978       foundSideLinkIDs.insert ( linkID );
5979       prevSideNode = sideNode;
5980
5981       if ( *nBordIt == theBordLastNode )
5982         searchByDir = false;
5983       else {
5984         // find the next border link to compare with
5985         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
5986         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5987         // move to next border node if sideNode is before forward border node (bordPos)
5988         while ( *nBordIt != theBordLastNode && !searchByDir ) {
5989           prevBordNode = *nBordIt;
5990           nBordIt++;
5991           bordPos = nBordXYZ[ *nBordIt ];
5992           bordDir = bordPos - nBordXYZ[ prevBordNode ];
5993           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5994         }
5995       }
5996     }
5997     while ( sideNode != theSideSecondNode );
5998
5999     if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
6000       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
6001       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
6002     }
6003   } // end nodes search on the side 2
6004
6005   // ============================
6006   // sew the border to the side 2
6007   // ============================
6008
6009   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
6010   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
6011
6012   TListOfListOfNodes nodeGroupsToMerge;
6013   if ( nbNodes[0] == nbNodes[1] ||
6014       ( theSideIsFreeBorder && !theSideThirdNode)) {
6015
6016     // all nodes are to be merged
6017
6018     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
6019          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
6020          nIt[0]++, nIt[1]++ )
6021     {
6022       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
6023       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
6024       nodeGroupsToMerge.back().push_back( *nIt[0] ); // to remove
6025     }
6026   }
6027   else {
6028
6029     // insert new nodes into the border and the side to get equal nb of segments
6030
6031     // get normalized parameters of nodes on the borders
6032     //double param[ 2 ][ maxNbNodes ];
6033     double* param[ 2 ];
6034     param[0] = new double [ maxNbNodes ];
6035     param[1] = new double [ maxNbNodes ];
6036     int iNode, iBord;
6037     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
6038       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
6039       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
6040       const SMDS_MeshNode* nPrev = *nIt;
6041       double bordLength = 0;
6042       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
6043         const SMDS_MeshNode* nCur = *nIt;
6044         gp_XYZ segment (nCur->X() - nPrev->X(),
6045                         nCur->Y() - nPrev->Y(),
6046                         nCur->Z() - nPrev->Z());
6047         double segmentLen = segment.Modulus();
6048         bordLength += segmentLen;
6049         param[ iBord ][ iNode ] = bordLength;
6050         nPrev = nCur;
6051       }
6052       // normalize within [0,1]
6053       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
6054         param[ iBord ][ iNode ] /= bordLength;
6055       }
6056     }
6057
6058     // loop on border segments
6059     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
6060     int i[ 2 ] = { 0, 0 };
6061     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
6062     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
6063
6064     TElemOfNodeListMap insertMap;
6065     TElemOfNodeListMap::iterator insertMapIt;
6066     // insertMap is
6067     // key:   elem to insert nodes into
6068     // value: 2 nodes to insert between + nodes to be inserted
6069     do {
6070       bool next[ 2 ] = { false, false };
6071
6072       // find min adjacent segment length after sewing
6073       double nextParam = 10., prevParam = 0;
6074       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
6075         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
6076           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
6077         if ( i[ iBord ] > 0 )
6078           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
6079       }
6080       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
6081       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
6082       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
6083
6084       // choose to insert or to merge nodes
6085       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
6086       if ( Abs( du ) <= minSegLen * 0.2 ) {
6087         // merge
6088         // ------
6089         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
6090         const SMDS_MeshNode* n0 = *nIt[0];
6091         const SMDS_MeshNode* n1 = *nIt[1];
6092         nodeGroupsToMerge.back().push_back( n1 );
6093         nodeGroupsToMerge.back().push_back( n0 );
6094         // position of node of the border changes due to merge
6095         param[ 0 ][ i[0] ] += du;
6096         // move n1 for the sake of elem shape evaluation during insertion.
6097         // n1 will be removed by MergeNodes() anyway
6098         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
6099         next[0] = next[1] = true;
6100       }
6101       else {
6102         // insert
6103         // ------
6104         int intoBord = ( du < 0 ) ? 0 : 1;
6105         const SMDS_MeshElement* elem = *eIt[ intoBord ];
6106         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
6107         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
6108         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
6109         if ( intoBord == 1 ) {
6110           // move node of the border to be on a link of elem of the side
6111           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
6112           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
6113           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
6114           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
6115           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
6116         }
6117         insertMapIt = insertMap.find( elem );
6118         bool notFound = ( insertMapIt == insertMap.end() );
6119         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
6120         if ( otherLink ) {
6121           // insert into another link of the same element:
6122           // 1. perform insertion into the other link of the elem
6123           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
6124           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
6125           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
6126           InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
6127           // 2. perform insertion into the link of adjacent faces
6128           while (true) {
6129             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
6130             if ( adjElem )
6131               InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
6132             else
6133               break;
6134           }
6135           if (toCreatePolyedrs) {
6136             // perform insertion into the links of adjacent volumes
6137             UpdateVolumes(n12, n22, nodeList);
6138           }
6139           // 3. find an element appeared on n1 and n2 after the insertion
6140           insertMap.erase( elem );
6141           elem = findAdjacentFace( n1, n2, 0 );
6142         }
6143         if ( notFound || otherLink ) {
6144           // add element and nodes of the side into the insertMap
6145           insertMapIt = insertMap.insert
6146             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
6147           (*insertMapIt).second.push_back( n1 );
6148           (*insertMapIt).second.push_back( n2 );
6149         }
6150         // add node to be inserted into elem
6151         (*insertMapIt).second.push_back( nIns );
6152         next[ 1 - intoBord ] = true;
6153       }
6154
6155       // go to the next segment
6156       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
6157         if ( next[ iBord ] ) {
6158           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
6159             eIt[ iBord ]++;
6160           nPrev[ iBord ] = *nIt[ iBord ];
6161           nIt[ iBord ]++; i[ iBord ]++;
6162         }
6163       }
6164     }
6165     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
6166
6167     // perform insertion of nodes into elements
6168
6169     for (insertMapIt = insertMap.begin();
6170          insertMapIt != insertMap.end();
6171          insertMapIt++ )
6172     {
6173       const SMDS_MeshElement* elem = (*insertMapIt).first;
6174       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
6175       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
6176       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
6177
6178       InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
6179
6180       if ( !theSideIsFreeBorder ) {
6181         // look for and insert nodes into the faces adjacent to elem
6182         while (true) {
6183           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
6184           if ( adjElem )
6185             InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
6186           else
6187             break;
6188         }
6189       }
6190       if (toCreatePolyedrs) {
6191         // perform insertion into the links of adjacent volumes
6192         UpdateVolumes(n1, n2, nodeList);
6193       }
6194     }
6195
6196     delete param[0];
6197     delete param[1];
6198   } // end: insert new nodes
6199
6200   MergeNodes ( nodeGroupsToMerge );
6201
6202   return aResult;
6203 }
6204
6205 //=======================================================================
6206 //function : InsertNodesIntoLink
6207 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
6208 //           and theBetweenNode2 and split theElement
6209 //=======================================================================
6210
6211 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
6212                                            const SMDS_MeshNode*        theBetweenNode1,
6213                                            const SMDS_MeshNode*        theBetweenNode2,
6214                                            list<const SMDS_MeshNode*>& theNodesToInsert,
6215                                            const bool                  toCreatePoly)
6216 {
6217   if ( theFace->GetType() != SMDSAbs_Face ) return;
6218
6219   // find indices of 2 link nodes and of the rest nodes
6220   int iNode = 0, il1, il2, i3, i4;
6221   il1 = il2 = i3 = i4 = -1;
6222   //const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
6223   vector<const SMDS_MeshNode*> nodes( theFace->NbNodes() );
6224
6225   if(theFace->IsQuadratic()) {
6226     const SMDS_QuadraticFaceOfNodes* F =
6227       static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
6228     // use special nodes iterator
6229     SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
6230     while( anIter->more() ) {
6231       const SMDS_MeshNode* n = anIter->next();
6232       if ( n == theBetweenNode1 )
6233         il1 = iNode;
6234       else if ( n == theBetweenNode2 )
6235         il2 = iNode;
6236       else if ( i3 < 0 )
6237         i3 = iNode;
6238       else
6239         i4 = iNode;
6240       nodes[ iNode++ ] = n;
6241     }
6242   }
6243   else {
6244     SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
6245     while ( nodeIt->more() ) {
6246       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6247       if ( n == theBetweenNode1 )
6248         il1 = iNode;
6249       else if ( n == theBetweenNode2 )
6250         il2 = iNode;
6251       else if ( i3 < 0 )
6252         i3 = iNode;
6253       else
6254         i4 = iNode;
6255       nodes[ iNode++ ] = n;
6256     }
6257   }
6258   if ( il1 < 0 || il2 < 0 || i3 < 0 )
6259     return ;
6260
6261   // arrange link nodes to go one after another regarding the face orientation
6262   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
6263   list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
6264   if ( reverse ) {
6265     iNode = il1;
6266     il1 = il2;
6267     il2 = iNode;
6268     aNodesToInsert.reverse();
6269   }
6270   // check that not link nodes of a quadrangles are in good order
6271   int nbFaceNodes = theFace->NbNodes();
6272   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
6273     iNode = i3;
6274     i3 = i4;
6275     i4 = iNode;
6276   }
6277
6278   if (toCreatePoly || theFace->IsPoly()) {
6279
6280     iNode = 0;
6281     vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
6282
6283     // add nodes of face up to first node of link
6284     bool isFLN = false;
6285
6286     if(theFace->IsQuadratic()) {
6287       const SMDS_QuadraticFaceOfNodes* F =
6288         static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
6289       // use special nodes iterator
6290       SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
6291       while( anIter->more()  && !isFLN ) {
6292         const SMDS_MeshNode* n = anIter->next();
6293         poly_nodes[iNode++] = n;
6294         if (n == nodes[il1]) {
6295           isFLN = true;
6296         }
6297       }
6298       // add nodes to insert
6299       list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
6300       for (; nIt != aNodesToInsert.end(); nIt++) {
6301         poly_nodes[iNode++] = *nIt;
6302       }
6303       // add nodes of face starting from last node of link
6304       while ( anIter->more() ) {
6305         poly_nodes[iNode++] = anIter->next();
6306       }
6307     }
6308     else {
6309       SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
6310       while ( nodeIt->more() && !isFLN ) {
6311         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6312         poly_nodes[iNode++] = n;
6313         if (n == nodes[il1]) {
6314           isFLN = true;
6315         }
6316       }
6317       // add nodes to insert
6318       list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
6319       for (; nIt != aNodesToInsert.end(); nIt++) {
6320         poly_nodes[iNode++] = *nIt;
6321       }
6322       // add nodes of face starting from last node of link
6323       while ( nodeIt->more() ) {
6324         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6325         poly_nodes[iNode++] = n;
6326       }
6327     }
6328
6329     // edit or replace the face
6330     SMESHDS_Mesh *aMesh = GetMeshDS();
6331
6332     if (theFace->IsPoly()) {
6333       aMesh->ChangePolygonNodes(theFace, poly_nodes);
6334     }
6335     else {
6336       int aShapeId = FindShape( theFace );
6337
6338       SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
6339       myLastCreatedElems.Append(newElem);
6340       if ( aShapeId && newElem )
6341         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6342
6343       aMesh->RemoveElement(theFace);
6344     }
6345     return;
6346   }
6347
6348   if( !theFace->IsQuadratic() ) {
6349
6350     // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
6351     int nbLinkNodes = 2 + aNodesToInsert.size();
6352     //const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
6353     vector<const SMDS_MeshNode*> linkNodes( nbLinkNodes );
6354     linkNodes[ 0 ] = nodes[ il1 ];
6355     linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
6356     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
6357     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
6358       linkNodes[ iNode++ ] = *nIt;
6359     }
6360     // decide how to split a quadrangle: compare possible variants
6361     // and choose which of splits to be a quadrangle
6362     int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
6363     if ( nbFaceNodes == 3 ) {
6364       iBestQuad = nbSplits;
6365       i4 = i3;
6366     }
6367     else if ( nbFaceNodes == 4 ) {
6368       SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
6369       double aBestRate = DBL_MAX;
6370       for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
6371         i1 = 0; i2 = 1;
6372         double aBadRate = 0;
6373         // evaluate elements quality
6374         for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
6375           if ( iSplit == iQuad ) {
6376             SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
6377                                    linkNodes[ i2++ ],
6378                                    nodes[ i3 ],
6379                                    nodes[ i4 ]);
6380             aBadRate += getBadRate( &quad, aCrit );
6381           }
6382           else {
6383             SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
6384                                    linkNodes[ i2++ ],
6385                                    nodes[ iSplit < iQuad ? i4 : i3 ]);
6386             aBadRate += getBadRate( &tria, aCrit );
6387           }
6388         }
6389         // choice
6390         if ( aBadRate < aBestRate ) {
6391           iBestQuad = iQuad;
6392           aBestRate = aBadRate;
6393         }
6394       }
6395     }
6396
6397     // create new elements
6398     SMESHDS_Mesh *aMesh = GetMeshDS();
6399     int aShapeId = FindShape( theFace );
6400
6401     i1 = 0; i2 = 1;
6402     for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
6403       SMDS_MeshElement* newElem = 0;
6404       if ( iSplit == iBestQuad )
6405         newElem = aMesh->AddFace (linkNodes[ i1++ ],
6406                                   linkNodes[ i2++ ],
6407                                   nodes[ i3 ],
6408                                   nodes[ i4 ]);
6409       else
6410         newElem = aMesh->AddFace (linkNodes[ i1++ ],
6411                                   linkNodes[ i2++ ],
6412                                   nodes[ iSplit < iBestQuad ? i4 : i3 ]);
6413       myLastCreatedElems.Append(newElem);
6414       if ( aShapeId && newElem )
6415         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6416     }
6417
6418     // change nodes of theFace
6419     const SMDS_MeshNode* newNodes[ 4 ];
6420     newNodes[ 0 ] = linkNodes[ i1 ];
6421     newNodes[ 1 ] = linkNodes[ i2 ];
6422     newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
6423     newNodes[ 3 ] = nodes[ i4 ];
6424     aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
6425   } // end if(!theFace->IsQuadratic())
6426   else { // theFace is quadratic
6427     // we have to split theFace on simple triangles and one simple quadrangle
6428     int tmp = il1/2;
6429     int nbshift = tmp*2;
6430     // shift nodes in nodes[] by nbshift
6431     int i,j;
6432     for(i=0; i<nbshift; i++) {
6433       const SMDS_MeshNode* n = nodes[0];
6434       for(j=0; j<nbFaceNodes-1; j++) {
6435         nodes[j] = nodes[j+1];
6436       }
6437       nodes[nbFaceNodes-1] = n;
6438     }
6439     il1 = il1 - nbshift;
6440     // now have to insert nodes between n0 and n1 or n1 and n2 (see below)
6441     //   n0      n1     n2    n0      n1     n2
6442     //     +-----+-----+        +-----+-----+
6443     //      \         /         |           |
6444     //       \       /          |           |
6445     //      n5+     +n3       n7+           +n3
6446     //         \   /            |           |
6447     //          \ /             |           |
6448     //           +              +-----+-----+
6449     //           n4           n6      n5     n4
6450
6451     // create new elements
6452     SMESHDS_Mesh *aMesh = GetMeshDS();
6453     int aShapeId = FindShape( theFace );
6454
6455     int n1,n2,n3;
6456     if(nbFaceNodes==6) { // quadratic triangle
6457       SMDS_MeshElement* newElem =
6458         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
6459       myLastCreatedElems.Append(newElem);
6460       if ( aShapeId && newElem )
6461         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6462       if(theFace->IsMediumNode(nodes[il1])) {
6463         // create quadrangle
6464         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[5]);
6465         myLastCreatedElems.Append(newElem);
6466         if ( aShapeId && newElem )
6467           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6468         n1 = 1;
6469         n2 = 2;
6470         n3 = 3;
6471       }
6472       else {
6473         // create quadrangle
6474         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[5]);
6475         myLastCreatedElems.Append(newElem);
6476         if ( aShapeId && newElem )
6477           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6478         n1 = 0;
6479         n2 = 1;
6480         n3 = 5;
6481       }
6482     }
6483     else { // nbFaceNodes==8 - quadratic quadrangle
6484       SMDS_MeshElement* newElem =
6485         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
6486       myLastCreatedElems.Append(newElem);
6487       if ( aShapeId && newElem )
6488         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6489       newElem = aMesh->AddFace(nodes[5],nodes[6],nodes[7]);
6490       myLastCreatedElems.Append(newElem);
6491       if ( aShapeId && newElem )
6492         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6493       newElem = aMesh->AddFace(nodes[5],nodes[7],nodes[3]);
6494       myLastCreatedElems.Append(newElem);
6495       if ( aShapeId && newElem )
6496         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6497       if(theFace->IsMediumNode(nodes[il1])) {
6498         // create quadrangle
6499         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[7]);
6500         myLastCreatedElems.Append(newElem);
6501         if ( aShapeId && newElem )
6502           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6503         n1 = 1;
6504         n2 = 2;
6505         n3 = 3;
6506       }
6507       else {
6508         // create quadrangle
6509         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[7]);
6510         myLastCreatedElems.Append(newElem);
6511         if ( aShapeId && newElem )
6512           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6513         n1 = 0;
6514         n2 = 1;
6515         n3 = 7;
6516       }
6517     }
6518     // create needed triangles using n1,n2,n3 and inserted nodes
6519     int nbn = 2 + aNodesToInsert.size();
6520     //const SMDS_MeshNode* aNodes[nbn];
6521     vector<const SMDS_MeshNode*> aNodes(nbn);
6522     aNodes[0] = nodes[n1];
6523     aNodes[nbn-1] = nodes[n2];
6524     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
6525     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
6526       aNodes[iNode++] = *nIt;
6527     }
6528     for(i=1; i<nbn; i++) {
6529       SMDS_MeshElement* newElem =
6530         aMesh->AddFace(aNodes[i-1],aNodes[i],nodes[n3]);
6531       myLastCreatedElems.Append(newElem);
6532       if ( aShapeId && newElem )
6533         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6534     }
6535     // remove old quadratic face
6536     aMesh->RemoveElement(theFace);
6537   }
6538 }
6539
6540 //=======================================================================
6541 //function : UpdateVolumes
6542 //purpose  :
6543 //=======================================================================
6544 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode*        theBetweenNode1,
6545                                       const SMDS_MeshNode*        theBetweenNode2,
6546                                       list<const SMDS_MeshNode*>& theNodesToInsert)
6547 {
6548   myLastCreatedElems.Clear();
6549   myLastCreatedNodes.Clear();
6550
6551   SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator(SMDSAbs_Volume);
6552   while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
6553     const SMDS_MeshElement* elem = invElemIt->next();
6554
6555     // check, if current volume has link theBetweenNode1 - theBetweenNode2
6556     SMDS_VolumeTool aVolume (elem);
6557     if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
6558       continue;
6559
6560     // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
6561     int iface, nbFaces = aVolume.NbFaces();
6562     vector<const SMDS_MeshNode *> poly_nodes;
6563     vector<int> quantities (nbFaces);
6564
6565     for (iface = 0; iface < nbFaces; iface++) {
6566       int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
6567       // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
6568       const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
6569
6570       for (int inode = 0; inode < nbFaceNodes; inode++) {
6571         poly_nodes.push_back(faceNodes[inode]);
6572
6573         if (nbInserted == 0) {
6574           if (faceNodes[inode] == theBetweenNode1) {
6575             if (faceNodes[inode + 1] == theBetweenNode2) {
6576               nbInserted = theNodesToInsert.size();
6577
6578               // add nodes to insert
6579               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
6580               for (; nIt != theNodesToInsert.end(); nIt++) {
6581                 poly_nodes.push_back(*nIt);
6582               }
6583             }
6584           }
6585           else if (faceNodes[inode] == theBetweenNode2) {
6586             if (faceNodes[inode + 1] == theBetweenNode1) {
6587               nbInserted = theNodesToInsert.size();
6588
6589               // add nodes to insert in reversed order
6590               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
6591               nIt--;
6592               for (; nIt != theNodesToInsert.begin(); nIt--) {
6593                 poly_nodes.push_back(*nIt);
6594               }
6595               poly_nodes.push_back(*nIt);
6596             }
6597           }
6598           else {
6599           }
6600         }
6601       }
6602       quantities[iface] = nbFaceNodes + nbInserted;
6603     }
6604
6605     // Replace or update the volume
6606     SMESHDS_Mesh *aMesh = GetMeshDS();
6607
6608     if (elem->IsPoly()) {
6609       aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
6610
6611     }
6612     else {
6613       int aShapeId = FindShape( elem );
6614
6615       SMDS_MeshElement* newElem =
6616         aMesh->AddPolyhedralVolume(poly_nodes, quantities);
6617       myLastCreatedElems.Append(newElem);
6618       if (aShapeId && newElem)
6619         aMesh->SetMeshElementOnShape(newElem, aShapeId);
6620
6621       aMesh->RemoveElement(elem);
6622     }
6623   }
6624 }
6625
6626 //=======================================================================
6627 /*!
6628  * \brief Convert elements contained in a submesh to quadratic
6629  * \retval int - nb of checked elements
6630  */
6631 //=======================================================================
6632
6633 int SMESH_MeshEditor::convertElemToQuadratic(SMESHDS_SubMesh *   theSm,
6634                                              SMESH_MesherHelper& theHelper,
6635                                              const bool          theForce3d)
6636 {
6637   int nbElem = 0;
6638   if( !theSm ) return nbElem;
6639
6640   const bool notFromGroups = false;
6641   SMDS_ElemIteratorPtr ElemItr = theSm->GetElements();
6642   while(ElemItr->more())
6643   {
6644     nbElem++;
6645     const SMDS_MeshElement* elem = ElemItr->next();
6646     if( !elem || elem->IsQuadratic() ) continue;
6647
6648     int id = elem->GetID();
6649     int nbNodes = elem->NbNodes();
6650     vector<const SMDS_MeshNode *> aNds (nbNodes);
6651
6652     for(int i = 0; i < nbNodes; i++)
6653     {
6654       aNds[i] = elem->GetNode(i);
6655     }
6656     SMDSAbs_ElementType aType = elem->GetType();
6657
6658     GetMeshDS()->RemoveFreeElement(elem, theSm, notFromGroups);
6659
6660     const SMDS_MeshElement* NewElem = 0;
6661
6662     switch( aType )
6663     {
6664     case SMDSAbs_Edge :
6665     {
6666       NewElem = theHelper.AddEdge(aNds[0], aNds[1], id, theForce3d);
6667       break;
6668     }
6669     case SMDSAbs_Face :
6670     {
6671       switch(nbNodes)
6672       {
6673       case 3:
6674         NewElem = theHelper.AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6675         break;
6676       case 4:
6677         NewElem = theHelper.AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6678         break;
6679       default:
6680         continue;
6681       }
6682       break;
6683     }
6684     case SMDSAbs_Volume :
6685     {
6686       switch(nbNodes)
6687       {
6688       case 4:
6689         NewElem = theHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6690         break;
6691       case 6:
6692         NewElem = theHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], aNds[4], aNds[5], id, theForce3d);
6693         break;
6694       case 8:
6695         NewElem = theHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6696                                       aNds[4], aNds[5], aNds[6], aNds[7], id, theForce3d);
6697         break;
6698       default:
6699         continue;
6700       }
6701       break;
6702     }
6703     default :
6704       continue;
6705     }
6706     ReplaceElemInGroups( elem, NewElem, GetMeshDS());
6707     if( NewElem )
6708       theSm->AddElement( NewElem );
6709   }
6710   return nbElem;
6711 }
6712
6713 //=======================================================================
6714 //function : ConvertToQuadratic
6715 //purpose  :
6716 //=======================================================================
6717 void SMESH_MeshEditor::ConvertToQuadratic(const bool theForce3d)
6718 {
6719   SMESHDS_Mesh* meshDS = GetMeshDS();
6720
6721   SMESH_MesherHelper aHelper(*myMesh);
6722   aHelper.SetIsQuadratic( true );
6723   const bool notFromGroups = false;
6724
6725   int nbCheckedElems = 0;
6726   if ( myMesh->HasShapeToMesh() )
6727   {
6728     if ( SMESH_subMesh *aSubMesh = myMesh->GetSubMeshContaining(myMesh->GetShapeToMesh()))
6729     {
6730       SMESH_subMeshIteratorPtr smIt = aSubMesh->getDependsOnIterator(true,false);
6731       while ( smIt->more() ) {
6732         SMESH_subMesh* sm = smIt->next();
6733         if ( SMESHDS_SubMesh *smDS = sm->GetSubMeshDS() ) {
6734           aHelper.SetSubShape( sm->GetSubShape() );
6735           nbCheckedElems += convertElemToQuadratic(smDS, aHelper, theForce3d);
6736         }
6737       }
6738     }
6739   }
6740   int totalNbElems = meshDS->NbEdges() + meshDS->NbFaces() + meshDS->NbVolumes();
6741   if ( nbCheckedElems < totalNbElems ) // not all elements are in submeshes
6742   {
6743     SMESHDS_SubMesh *smDS = 0;
6744     SMDS_EdgeIteratorPtr aEdgeItr = meshDS->edgesIterator();
6745     while(aEdgeItr->more())
6746     {
6747       const SMDS_MeshEdge* edge = aEdgeItr->next();
6748       if(edge && !edge->IsQuadratic())
6749       {
6750         int id = edge->GetID();
6751         const SMDS_MeshNode* n1 = edge->GetNode(0);
6752         const SMDS_MeshNode* n2 = edge->GetNode(1);
6753
6754         meshDS->RemoveFreeElement(edge, smDS, notFromGroups);
6755
6756         const SMDS_MeshEdge* NewEdge = aHelper.AddEdge(n1, n2, id, theForce3d);
6757         ReplaceElemInGroups( edge, NewEdge, GetMeshDS());
6758       }
6759     }
6760     SMDS_FaceIteratorPtr aFaceItr = meshDS->facesIterator();
6761     while(aFaceItr->more())
6762     {
6763       const SMDS_MeshFace* face = aFaceItr->next();
6764       if(!face || face->IsQuadratic() ) continue;
6765
6766       int id = face->GetID();
6767       int nbNodes = face->NbNodes();
6768       vector<const SMDS_MeshNode *> aNds (nbNodes);
6769
6770       for(int i = 0; i < nbNodes; i++)
6771       {
6772         aNds[i] = face->GetNode(i);
6773       }
6774
6775       meshDS->RemoveFreeElement(face, smDS, notFromGroups);
6776
6777       SMDS_MeshFace * NewFace = 0;
6778       switch(nbNodes)
6779       {
6780       case 3:
6781         NewFace = aHelper.AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6782         break;
6783       case 4:
6784         NewFace = aHelper.AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6785         break;
6786       default:
6787         continue;
6788       }
6789       ReplaceElemInGroups( face, NewFace, GetMeshDS());
6790     }
6791     SMDS_VolumeIteratorPtr aVolumeItr = meshDS->volumesIterator();
6792     while(aVolumeItr->more())
6793     {
6794       const SMDS_MeshVolume* volume = aVolumeItr->next();
6795       if(!volume || volume->IsQuadratic() ) continue;
6796
6797       int id = volume->GetID();
6798       int nbNodes = volume->NbNodes();
6799       vector<const SMDS_MeshNode *> aNds (nbNodes);
6800
6801       for(int i = 0; i < nbNodes; i++)
6802       {
6803         aNds[i] = volume->GetNode(i);
6804       }
6805
6806       meshDS->RemoveFreeElement(volume, smDS, notFromGroups);
6807
6808       SMDS_MeshVolume * NewVolume = 0;
6809       switch(nbNodes)
6810       {
6811       case 4:
6812         NewVolume = aHelper.AddVolume(aNds[0], aNds[1], aNds[2],
6813                                       aNds[3], id, theForce3d );
6814         break;
6815       case 6:
6816         NewVolume = aHelper.AddVolume(aNds[0], aNds[1], aNds[2],
6817                                       aNds[3], aNds[4], aNds[5], id, theForce3d);
6818         break;
6819       case 8:
6820         NewVolume = aHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6821                                       aNds[4], aNds[5], aNds[6], aNds[7], id, theForce3d);
6822         break;
6823       default:
6824         continue;
6825       }
6826       ReplaceElemInGroups(volume, NewVolume, meshDS);
6827     }
6828   }
6829 }
6830
6831 //=======================================================================
6832 /*!
6833  * \brief Convert quadratic elements to linear ones and remove quadratic nodes
6834  * \retval int - nb of checked elements
6835  */
6836 //=======================================================================
6837
6838 int SMESH_MeshEditor::removeQuadElem(SMESHDS_SubMesh *    theSm,
6839                                      SMDS_ElemIteratorPtr theItr,
6840                                      const int            theShapeID)
6841 {
6842   int nbElem = 0;
6843   SMESHDS_Mesh* meshDS = GetMeshDS();
6844   const bool notFromGroups = false;
6845
6846   while( theItr->more() )
6847   {
6848     const SMDS_MeshElement* elem = theItr->next();
6849     nbElem++;
6850     if( elem && elem->IsQuadratic())
6851     {
6852       int id = elem->GetID();
6853       int nbNodes = elem->NbNodes();
6854       vector<const SMDS_MeshNode *> aNds, mediumNodes;
6855       aNds.reserve( nbNodes );
6856       mediumNodes.reserve( nbNodes );
6857
6858       for(int i = 0; i < nbNodes; i++)
6859       {
6860         const SMDS_MeshNode* n = elem->GetNode(i);
6861
6862         if( elem->IsMediumNode( n ) )
6863           mediumNodes.push_back( n );
6864         else
6865           aNds.push_back( n );
6866       }
6867       if( aNds.empty() ) continue;
6868       SMDSAbs_ElementType aType = elem->GetType();
6869
6870       //remove old quadratic element
6871       meshDS->RemoveFreeElement( elem, theSm, notFromGroups );
6872
6873       SMDS_MeshElement * NewElem = AddElement( aNds, aType, false, id );
6874       ReplaceElemInGroups(elem, NewElem, meshDS);
6875       if( theSm && NewElem )
6876         theSm->AddElement( NewElem );
6877
6878       // remove medium nodes
6879       vector<const SMDS_MeshNode*>::iterator nIt = mediumNodes.begin();
6880       for ( ; nIt != mediumNodes.end(); ++nIt ) {
6881         const SMDS_MeshNode* n = *nIt;
6882         if ( n->NbInverseElements() == 0 ) {
6883           if ( n->GetPosition()->GetShapeId() != theShapeID )
6884             meshDS->RemoveFreeNode( n, meshDS->MeshElements
6885                                     ( n->GetPosition()->GetShapeId() ));
6886           else
6887             meshDS->RemoveFreeNode( n, theSm );
6888         }
6889       }
6890     }
6891   }
6892   return nbElem;
6893 }
6894
6895 //=======================================================================
6896 //function : ConvertFromQuadratic
6897 //purpose  :
6898 //=======================================================================
6899 bool  SMESH_MeshEditor::ConvertFromQuadratic()
6900 {
6901   int nbCheckedElems = 0;
6902   if ( myMesh->HasShapeToMesh() )
6903   {
6904     if ( SMESH_subMesh *aSubMesh = myMesh->GetSubMeshContaining(myMesh->GetShapeToMesh()))
6905     {
6906       SMESH_subMeshIteratorPtr smIt = aSubMesh->getDependsOnIterator(true,false);
6907       while ( smIt->more() ) {
6908         SMESH_subMesh* sm = smIt->next();
6909         if ( SMESHDS_SubMesh *smDS = sm->GetSubMeshDS() )
6910           nbCheckedElems += removeQuadElem( smDS, smDS->GetElements(), sm->GetId() );
6911       }
6912     }
6913   }
6914   
6915   int totalNbElems =
6916     GetMeshDS()->NbEdges() + GetMeshDS()->NbFaces() + GetMeshDS()->NbVolumes();
6917   if ( nbCheckedElems < totalNbElems ) // not all elements are in submeshes
6918   {
6919     SMESHDS_SubMesh *aSM = 0;
6920     removeQuadElem( aSM, GetMeshDS()->elementsIterator(), 0 );
6921   }
6922
6923   return true;
6924 }
6925
6926 //=======================================================================
6927 //function : SewSideElements
6928 //purpose  :
6929 //=======================================================================
6930
6931 SMESH_MeshEditor::Sew_Error
6932   SMESH_MeshEditor::SewSideElements (TIDSortedElemSet&    theSide1,
6933                                      TIDSortedElemSet&    theSide2,
6934                                      const SMDS_MeshNode* theFirstNode1,
6935                                      const SMDS_MeshNode* theFirstNode2,
6936                                      const SMDS_MeshNode* theSecondNode1,
6937                                      const SMDS_MeshNode* theSecondNode2)
6938 {
6939   myLastCreatedElems.Clear();
6940   myLastCreatedNodes.Clear();
6941
6942   MESSAGE ("::::SewSideElements()");
6943   if ( theSide1.size() != theSide2.size() )
6944     return SEW_DIFF_NB_OF_ELEMENTS;
6945
6946   Sew_Error aResult = SEW_OK;
6947   // Algo:
6948   // 1. Build set of faces representing each side
6949   // 2. Find which nodes of the side 1 to merge with ones on the side 2
6950   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
6951
6952   // =======================================================================
6953   // 1. Build set of faces representing each side:
6954   // =======================================================================
6955   // a. build set of nodes belonging to faces
6956   // b. complete set of faces: find missing fices whose nodes are in set of nodes
6957   // c. create temporary faces representing side of volumes if correspondent
6958   //    face does not exist
6959
6960   SMESHDS_Mesh* aMesh = GetMeshDS();
6961   SMDS_Mesh aTmpFacesMesh;
6962   set<const SMDS_MeshElement*> faceSet1, faceSet2;
6963   set<const SMDS_MeshElement*> volSet1,  volSet2;
6964   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
6965   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
6966   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
6967   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
6968   TIDSortedElemSet * elemSetPtr[] = { &theSide1, &theSide2 };
6969   int iSide, iFace, iNode;
6970
6971   for ( iSide = 0; iSide < 2; iSide++ ) {
6972     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
6973     TIDSortedElemSet * elemSet = elemSetPtr[ iSide ];
6974     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
6975     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
6976     set<const SMDS_MeshElement*>::iterator vIt;
6977     TIDSortedElemSet::iterator eIt;
6978     set<const SMDS_MeshNode*>::iterator    nIt;
6979
6980     // check that given nodes belong to given elements
6981     const SMDS_MeshNode* n1 = ( iSide == 0 ) ? theFirstNode1 : theFirstNode2;
6982     const SMDS_MeshNode* n2 = ( iSide == 0 ) ? theSecondNode1 : theSecondNode2;
6983     int firstIndex = -1, secondIndex = -1;
6984     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
6985       const SMDS_MeshElement* elem = *eIt;
6986       if ( firstIndex  < 0 ) firstIndex  = elem->GetNodeIndex( n1 );
6987       if ( secondIndex < 0 ) secondIndex = elem->GetNodeIndex( n2 );
6988       if ( firstIndex > -1 && secondIndex > -1 ) break;
6989     }
6990     if ( firstIndex < 0 || secondIndex < 0 ) {
6991       // we can simply return until temporary faces created
6992       return (iSide == 0 ) ? SEW_BAD_SIDE1_NODES : SEW_BAD_SIDE2_NODES;
6993     }
6994
6995     // -----------------------------------------------------------
6996     // 1a. Collect nodes of existing faces
6997     //     and build set of face nodes in order to detect missing
6998     //     faces corresponing to sides of volumes
6999     // -----------------------------------------------------------
7000
7001     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
7002
7003     // loop on the given element of a side
7004     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
7005       //const SMDS_MeshElement* elem = *eIt;
7006       const SMDS_MeshElement* elem = *eIt;
7007       if ( elem->GetType() == SMDSAbs_Face ) {
7008         faceSet->insert( elem );
7009         set <const SMDS_MeshNode*> faceNodeSet;
7010         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
7011         while ( nodeIt->more() ) {
7012           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7013           nodeSet->insert( n );
7014           faceNodeSet.insert( n );
7015         }
7016         setOfFaceNodeSet.insert( faceNodeSet );
7017       }
7018       else if ( elem->GetType() == SMDSAbs_Volume )
7019         volSet->insert( elem );
7020     }
7021     // ------------------------------------------------------------------------------
7022     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
7023     // ------------------------------------------------------------------------------
7024
7025     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
7026       SMDS_ElemIteratorPtr fIt = (*nIt)->GetInverseElementIterator(SMDSAbs_Face);
7027       while ( fIt->more() ) { // loop on faces sharing a node
7028         const SMDS_MeshElement* f = fIt->next();
7029         if ( faceSet->find( f ) == faceSet->end() ) {
7030           // check if all nodes are in nodeSet and
7031           // complete setOfFaceNodeSet if they are
7032           set <const SMDS_MeshNode*> faceNodeSet;
7033           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
7034           bool allInSet = true;
7035           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
7036             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7037             if ( nodeSet->find( n ) == nodeSet->end() )
7038               allInSet = false;
7039             else
7040               faceNodeSet.insert( n );
7041           }
7042           if ( allInSet ) {
7043             faceSet->insert( f );
7044             setOfFaceNodeSet.insert( faceNodeSet );
7045           }
7046         }
7047       }
7048     }
7049
7050     // -------------------------------------------------------------------------
7051     // 1c. Create temporary faces representing sides of volumes if correspondent
7052     //     face does not exist
7053     // -------------------------------------------------------------------------
7054
7055     if ( !volSet->empty() ) {
7056       //int nodeSetSize = nodeSet->size();
7057
7058       // loop on given volumes
7059       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
7060         SMDS_VolumeTool vol (*vIt);
7061         // loop on volume faces: find free faces
7062         // --------------------------------------
7063         list<const SMDS_MeshElement* > freeFaceList;
7064         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
7065           if ( !vol.IsFreeFace( iFace ))
7066             continue;
7067           // check if there is already a face with same nodes in a face set
7068           const SMDS_MeshElement* aFreeFace = 0;
7069           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
7070           int nbNodes = vol.NbFaceNodes( iFace );
7071           set <const SMDS_MeshNode*> faceNodeSet;
7072           vol.GetFaceNodes( iFace, faceNodeSet );
7073           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
7074           if ( isNewFace ) {
7075             // no such a face is given but it still can exist, check it
7076             if ( nbNodes == 3 ) {
7077               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
7078             }
7079             else if ( nbNodes == 4 ) {
7080               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
7081             }
7082             else {
7083               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
7084               aFreeFace = aMesh->FindFace(poly_nodes);
7085             }
7086           }
7087           if ( !aFreeFace ) {
7088             // create a temporary face
7089             if ( nbNodes == 3 ) {
7090               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
7091             }
7092             else if ( nbNodes == 4 ) {
7093               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
7094             }
7095             else {
7096               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
7097               aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
7098             }
7099           }
7100           if ( aFreeFace )
7101             freeFaceList.push_back( aFreeFace );
7102
7103         } // loop on faces of a volume
7104
7105         // choose one of several free faces
7106         // --------------------------------------
7107         if ( freeFaceList.size() > 1 ) {
7108           // choose a face having max nb of nodes shared by other elems of a side
7109           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
7110           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
7111           while ( fIt != freeFaceList.end() ) { // loop on free faces
7112             int nbSharedNodes = 0;
7113             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
7114             while ( nodeIt->more() ) { // loop on free face nodes
7115               const SMDS_MeshNode* n =
7116                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7117               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
7118               while ( invElemIt->more() ) {
7119                 const SMDS_MeshElement* e = invElemIt->next();
7120                 if ( faceSet->find( e ) != faceSet->end() )
7121                   nbSharedNodes++;
7122                 if ( elemSet->find( e ) != elemSet->end() )
7123                   nbSharedNodes++;
7124               }
7125             }
7126             if ( nbSharedNodes >= maxNbNodes ) {
7127               maxNbNodes = nbSharedNodes;
7128               fIt++;
7129             }
7130             else
7131               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
7132           }
7133           if ( freeFaceList.size() > 1 )
7134           {
7135             // could not choose one face, use another way
7136             // choose a face most close to the bary center of the opposite side
7137             gp_XYZ aBC( 0., 0., 0. );
7138             set <const SMDS_MeshNode*> addedNodes;
7139             TIDSortedElemSet * elemSet2 = elemSetPtr[ 1 - iSide ];
7140             eIt = elemSet2->begin();
7141             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
7142               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
7143               while ( nodeIt->more() ) { // loop on free face nodes
7144                 const SMDS_MeshNode* n =
7145                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7146                 if ( addedNodes.insert( n ).second )
7147                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
7148               }
7149             }
7150             aBC /= addedNodes.size();
7151             double minDist = DBL_MAX;
7152             fIt = freeFaceList.begin();
7153             while ( fIt != freeFaceList.end() ) { // loop on free faces
7154               double dist = 0;
7155               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
7156               while ( nodeIt->more() ) { // loop on free face nodes
7157                 const SMDS_MeshNode* n =
7158                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7159                 gp_XYZ p( n->X(),n->Y(),n->Z() );
7160                 dist += ( aBC - p ).SquareModulus();
7161               }
7162               if ( dist < minDist ) {
7163                 minDist = dist;
7164                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
7165               }
7166               else
7167                 fIt = freeFaceList.erase( fIt++ );
7168             }
7169           }
7170         } // choose one of several free faces of a volume
7171
7172         if ( freeFaceList.size() == 1 ) {
7173           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
7174           faceSet->insert( aFreeFace );
7175           // complete a node set with nodes of a found free face
7176 //           for ( iNode = 0; iNode < ; iNode++ )
7177 //             nodeSet->insert( fNodes[ iNode ] );
7178         }
7179
7180       } // loop on volumes of a side
7181
7182 //       // complete a set of faces if new nodes in a nodeSet appeared
7183 //       // ----------------------------------------------------------
7184 //       if ( nodeSetSize != nodeSet->size() ) {
7185 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
7186 //           SMDS_ElemIteratorPtr fIt = (*nIt)->GetInverseElementIterator(SMDSAbs_Face);
7187 //           while ( fIt->more() ) { // loop on faces sharing a node
7188 //             const SMDS_MeshElement* f = fIt->next();
7189 //             if ( faceSet->find( f ) == faceSet->end() ) {
7190 //               // check if all nodes are in nodeSet and
7191 //               // complete setOfFaceNodeSet if they are
7192 //               set <const SMDS_MeshNode*> faceNodeSet;
7193 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
7194 //               bool allInSet = true;
7195 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
7196 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7197 //                 if ( nodeSet->find( n ) == nodeSet->end() )
7198 //                   allInSet = false;
7199 //                 else
7200 //                   faceNodeSet.insert( n );
7201 //               }
7202 //               if ( allInSet ) {
7203 //                 faceSet->insert( f );
7204 //                 setOfFaceNodeSet.insert( faceNodeSet );
7205 //               }
7206 //             }
7207 //           }
7208 //         }
7209 //       }
7210     } // Create temporary faces, if there are volumes given
7211   } // loop on sides
7212
7213   if ( faceSet1.size() != faceSet2.size() ) {
7214     // delete temporary faces: they are in reverseElements of actual nodes
7215     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
7216     while ( tmpFaceIt->more() )
7217       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
7218     MESSAGE("Diff nb of faces");
7219     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7220   }
7221
7222   // ============================================================
7223   // 2. Find nodes to merge:
7224   //              bind a node to remove to a node to put instead
7225   // ============================================================
7226
7227   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
7228   if ( theFirstNode1 != theFirstNode2 )
7229     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
7230   if ( theSecondNode1 != theSecondNode2 )
7231     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
7232
7233   LinkID_Gen aLinkID_Gen( GetMeshDS() );
7234   set< long > linkIdSet; // links to process
7235   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
7236
7237   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > NLink;
7238   list< NLink > linkList[2];
7239   linkList[0].push_back( NLink( theFirstNode1, theSecondNode1 ));
7240   linkList[1].push_back( NLink( theFirstNode2, theSecondNode2 ));
7241   // loop on links in linkList; find faces by links and append links
7242   // of the found faces to linkList
7243   list< NLink >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
7244   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ ) {
7245     NLink link[] = { *linkIt[0], *linkIt[1] };
7246     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
7247     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
7248       continue;
7249
7250     // by links, find faces in the face sets,
7251     // and find indices of link nodes in the found faces;
7252     // in a face set, there is only one or no face sharing a link
7253     // ---------------------------------------------------------------
7254
7255     const SMDS_MeshElement* face[] = { 0, 0 };
7256     //const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
7257     vector<const SMDS_MeshNode*> fnodes1(9);
7258     vector<const SMDS_MeshNode*> fnodes2(9);
7259     //const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
7260     vector<const SMDS_MeshNode*> notLinkNodes1(6);
7261     vector<const SMDS_MeshNode*> notLinkNodes2(6);
7262     int iLinkNode[2][2];
7263     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
7264       const SMDS_MeshNode* n1 = link[iSide].first;
7265       const SMDS_MeshNode* n2 = link[iSide].second;
7266       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
7267       set< const SMDS_MeshElement* > fMap;
7268       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
7269         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
7270         SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
7271         while ( fIt->more() ) { // loop on faces sharing a node
7272           const SMDS_MeshElement* f = fIt->next();
7273           if (faceSet->find( f ) != faceSet->end() && // f is in face set
7274               ! fMap.insert( f ).second ) // f encounters twice
7275           {
7276             if ( face[ iSide ] ) {
7277               MESSAGE( "2 faces per link " );
7278               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
7279               break;
7280             }
7281             face[ iSide ] = f;
7282             faceSet->erase( f );
7283             // get face nodes and find ones of a link
7284             iNode = 0;
7285             int nbl = -1;
7286             if(f->IsPoly()) {
7287               if(iSide==0) {
7288                 fnodes1.resize(f->NbNodes()+1);
7289                 notLinkNodes1.resize(f->NbNodes()-2);
7290               }
7291               else {
7292                 fnodes2.resize(f->NbNodes()+1);
7293                 notLinkNodes2.resize(f->NbNodes()-2);
7294               }
7295             }
7296             if(!f->IsQuadratic()) {
7297               SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7298               while ( nIt->more() ) {
7299                 const SMDS_MeshNode* n =
7300                   static_cast<const SMDS_MeshNode*>( nIt->next() );
7301                 if ( n == n1 ) {
7302                   iLinkNode[ iSide ][ 0 ] = iNode;
7303                 }
7304                 else if ( n == n2 ) {
7305                   iLinkNode[ iSide ][ 1 ] = iNode;
7306                 }
7307                 //else if ( notLinkNodes[ iSide ][ 0 ] )
7308                 //  notLinkNodes[ iSide ][ 1 ] = n;
7309                 //else
7310                 //  notLinkNodes[ iSide ][ 0 ] = n;
7311                 else {
7312                   nbl++;
7313                   if(iSide==0)
7314                     notLinkNodes1[nbl] = n;
7315                     //notLinkNodes1.push_back(n);
7316                   else
7317                     notLinkNodes2[nbl] = n;
7318                     //notLinkNodes2.push_back(n);
7319                 }
7320                 //faceNodes[ iSide ][ iNode++ ] = n;
7321                 if(iSide==0) {
7322                   fnodes1[iNode++] = n;
7323                 }
7324                 else {
7325                   fnodes2[iNode++] = n;
7326                 }
7327               }
7328             }
7329             else { // f->IsQuadratic()
7330               const SMDS_QuadraticFaceOfNodes* F =
7331                 static_cast<const SMDS_QuadraticFaceOfNodes*>(f);
7332               // use special nodes iterator
7333               SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
7334               while ( anIter->more() ) {
7335                 const SMDS_MeshNode* n =
7336                   static_cast<const SMDS_MeshNode*>( anIter->next() );
7337                 if ( n == n1 ) {
7338                   iLinkNode[ iSide ][ 0 ] = iNode;
7339                 }
7340                 else if ( n == n2 ) {
7341                   iLinkNode[ iSide ][ 1 ] = iNode;
7342                 }
7343                 else {
7344                   nbl++;
7345                   if(iSide==0) {
7346                     notLinkNodes1[nbl] = n;
7347                   }
7348                   else {
7349                     notLinkNodes2[nbl] = n;
7350                   }
7351                 }
7352                 if(iSide==0) {
7353                   fnodes1[iNode++] = n;
7354                 }
7355                 else {
7356                   fnodes2[iNode++] = n;
7357                 }
7358               }
7359             }
7360             //faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
7361             if(iSide==0) {
7362               fnodes1[iNode] = fnodes1[0];
7363             }
7364             else {
7365               fnodes2[iNode] = fnodes1[0];
7366             }
7367           }
7368         }
7369       }
7370     }
7371
7372     // check similarity of elements of the sides
7373     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
7374       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
7375       if ( nReplaceMap.size() == 2 ) { // faces on input nodes not found
7376         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7377       }
7378       else {
7379         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7380       }
7381       break; // do not return because it s necessary to remove tmp faces
7382     }
7383
7384     // set nodes to merge
7385     // -------------------
7386
7387     if ( face[0] && face[1] )  {
7388       int nbNodes = face[0]->NbNodes();
7389       if ( nbNodes != face[1]->NbNodes() ) {
7390         MESSAGE("Diff nb of face nodes");
7391         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7392         break; // do not return because it s necessary to remove tmp faces
7393       }
7394       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
7395       if ( nbNodes == 3 ) {
7396         //nReplaceMap.insert( TNodeNodeMap::value_type
7397         //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
7398         nReplaceMap.insert( TNodeNodeMap::value_type
7399                            ( notLinkNodes1[0], notLinkNodes2[0] ));
7400       }
7401       else {
7402         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
7403           // analyse link orientation in faces
7404           int i1 = iLinkNode[ iSide ][ 0 ];
7405           int i2 = iLinkNode[ iSide ][ 1 ];
7406           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
7407           // if notLinkNodes are the first and the last ones, then
7408           // their order does not correspond to the link orientation
7409           if (( i1 == 1 && i2 == 2 ) ||
7410               ( i1 == 2 && i2 == 1 ))
7411             reverse[ iSide ] = !reverse[ iSide ];
7412         }
7413         if ( reverse[0] == reverse[1] ) {
7414           //nReplaceMap.insert( TNodeNodeMap::value_type
7415           //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
7416           //nReplaceMap.insert( TNodeNodeMap::value_type
7417           //                   ( notLinkNodes[0][1], notLinkNodes[1][1] ));
7418           for(int nn=0; nn<nbNodes-2; nn++) {
7419             nReplaceMap.insert( TNodeNodeMap::value_type
7420                              ( notLinkNodes1[nn], notLinkNodes2[nn] ));
7421           }
7422         }
7423         else {
7424           //nReplaceMap.insert( TNodeNodeMap::value_type
7425           //                   ( notLinkNodes[0][0], notLinkNodes[1][1] ));
7426           //nReplaceMap.insert( TNodeNodeMap::value_type
7427           //                   ( notLinkNodes[0][1], notLinkNodes[1][0] ));
7428           for(int nn=0; nn<nbNodes-2; nn++) {
7429             nReplaceMap.insert( TNodeNodeMap::value_type
7430                              ( notLinkNodes1[nn], notLinkNodes2[nbNodes-3-nn] ));
7431           }
7432         }
7433       }
7434
7435       // add other links of the faces to linkList
7436       // -----------------------------------------
7437
7438       //const SMDS_MeshNode** nodes = faceNodes[ 0 ];
7439       for ( iNode = 0; iNode < nbNodes; iNode++ )  {
7440         //linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
7441         linkID = aLinkID_Gen.GetLinkID( fnodes1[iNode], fnodes1[iNode+1] );
7442         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
7443         if ( !iter_isnew.second ) { // already in a set: no need to process
7444           linkIdSet.erase( iter_isnew.first );
7445         }
7446         else // new in set == encountered for the first time: add
7447         {
7448           //const SMDS_MeshNode* n1 = nodes[ iNode ];
7449           //const SMDS_MeshNode* n2 = nodes[ iNode + 1];
7450           const SMDS_MeshNode* n1 = fnodes1[ iNode ];
7451           const SMDS_MeshNode* n2 = fnodes1[ iNode + 1];
7452           linkList[0].push_back ( NLink( n1, n2 ));
7453           linkList[1].push_back ( NLink( nReplaceMap[n1], nReplaceMap[n2] ));
7454         }
7455       }
7456     } // 2 faces found
7457   } // loop on link lists
7458
7459   if ( aResult == SEW_OK &&
7460       ( linkIt[0] != linkList[0].end() ||
7461        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
7462     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
7463             " " << (faceSetPtr[1]->empty()));
7464     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7465   }
7466
7467   // ====================================================================
7468   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
7469   // ====================================================================
7470
7471   // delete temporary faces: they are in reverseElements of actual nodes
7472   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
7473   while ( tmpFaceIt->more() )
7474     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
7475
7476   if ( aResult != SEW_OK)
7477     return aResult;
7478
7479   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
7480   // loop on nodes replacement map
7481   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
7482   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
7483     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second ) {
7484       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
7485       nodeIDsToRemove.push_back( nToRemove->GetID() );
7486       // loop on elements sharing nToRemove
7487       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
7488       while ( invElemIt->more() ) {
7489         const SMDS_MeshElement* e = invElemIt->next();
7490         // get a new suite of nodes: make replacement
7491         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
7492         vector< const SMDS_MeshNode*> nodes( nbNodes );
7493         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7494         while ( nIt->more() ) {
7495           const SMDS_MeshNode* n =
7496             static_cast<const SMDS_MeshNode*>( nIt->next() );
7497           nnIt = nReplaceMap.find( n );
7498           if ( nnIt != nReplaceMap.end() ) {
7499             nbReplaced++;
7500             n = (*nnIt).second;
7501           }
7502           nodes[ i++ ] = n;
7503         }
7504         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
7505         //         elemIDsToRemove.push_back( e->GetID() );
7506         //       else
7507         if ( nbReplaced )
7508           aMesh->ChangeElementNodes( e, & nodes[0], nbNodes );
7509       }
7510     }
7511
7512   Remove( nodeIDsToRemove, true );
7513
7514   return aResult;
7515 }
7516
7517 //================================================================================
7518   /*!
7519    * \brief Find corresponding nodes in two sets of faces
7520     * \param theSide1 - first face set
7521     * \param theSide2 - second first face
7522     * \param theFirstNode1 - a boundary node of set 1
7523     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
7524     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
7525     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
7526     * \param nReplaceMap - output map of corresponding nodes
7527     * \retval bool  - is a success or not
7528    */
7529 //================================================================================
7530
7531 #ifdef _DEBUG_
7532 //#define DEBUG_MATCHING_NODES
7533 #endif
7534
7535 SMESH_MeshEditor::Sew_Error
7536 SMESH_MeshEditor::FindMatchingNodes(set<const SMDS_MeshElement*>& theSide1,
7537                                     set<const SMDS_MeshElement*>& theSide2,
7538                                     const SMDS_MeshNode*          theFirstNode1,
7539                                     const SMDS_MeshNode*          theFirstNode2,
7540                                     const SMDS_MeshNode*          theSecondNode1,
7541                                     const SMDS_MeshNode*          theSecondNode2,
7542                                     TNodeNodeMap &                nReplaceMap)
7543 {
7544   set<const SMDS_MeshElement*> * faceSetPtr[] = { &theSide1, &theSide2 };
7545
7546   nReplaceMap.clear();
7547   if ( theFirstNode1 != theFirstNode2 )
7548     nReplaceMap.insert( make_pair( theFirstNode1, theFirstNode2 ));
7549   if ( theSecondNode1 != theSecondNode2 )
7550     nReplaceMap.insert( make_pair( theSecondNode1, theSecondNode2 ));
7551
7552   set< TLink > linkSet; // set of nodes where order of nodes is ignored
7553   linkSet.insert( TLink( theFirstNode1, theSecondNode1 ));
7554
7555   list< NLink > linkList[2];
7556   linkList[0].push_back( NLink( theFirstNode1, theSecondNode1 ));
7557   linkList[1].push_back( NLink( theFirstNode2, theSecondNode2 ));
7558
7559   // loop on links in linkList; find faces by links and append links
7560   // of the found faces to linkList
7561   list< NLink >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
7562   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ ) {
7563     NLink link[] = { *linkIt[0], *linkIt[1] };
7564     if ( linkSet.find( link[0] ) == linkSet.end() )
7565       continue;
7566
7567     // by links, find faces in the face sets,
7568     // and find indices of link nodes in the found faces;
7569     // in a face set, there is only one or no face sharing a link
7570     // ---------------------------------------------------------------
7571
7572     const SMDS_MeshElement* face[] = { 0, 0 };
7573     list<const SMDS_MeshNode*> notLinkNodes[2];
7574     //bool reverse[] = { false, false }; // order of notLinkNodes
7575     int nbNodes[2];
7576     for ( int iSide = 0; iSide < 2; iSide++ ) // loop on 2 sides
7577     {
7578       const SMDS_MeshNode* n1 = link[iSide].first;
7579       const SMDS_MeshNode* n2 = link[iSide].second;
7580       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
7581       set< const SMDS_MeshElement* > facesOfNode1;
7582       for ( int iNode = 0; iNode < 2; iNode++ ) // loop on 2 nodes of a link
7583       {
7584         // during a loop of the first node, we find all faces around n1,
7585         // during a loop of the second node, we find one face sharing both n1 and n2
7586         const SMDS_MeshNode* n = iNode ? n1 : n2; // a node of a link
7587         SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
7588         while ( fIt->more() ) { // loop on faces sharing a node
7589           const SMDS_MeshElement* f = fIt->next();
7590           if (faceSet->find( f ) != faceSet->end() && // f is in face set
7591               ! facesOfNode1.insert( f ).second ) // f encounters twice
7592           {
7593             if ( face[ iSide ] ) {
7594               MESSAGE( "2 faces per link " );
7595               return ( iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7596             }
7597             face[ iSide ] = f;
7598             faceSet->erase( f );
7599
7600             // get not link nodes
7601             int nbN = f->NbNodes();
7602             if ( f->IsQuadratic() )
7603               nbN /= 2;
7604             nbNodes[ iSide ] = nbN;
7605             list< const SMDS_MeshNode* > & nodes = notLinkNodes[ iSide ];
7606             int i1 = f->GetNodeIndex( n1 );
7607             int i2 = f->GetNodeIndex( n2 );
7608             int iEnd = nbN, iBeg = -1, iDelta = 1;
7609             bool reverse = ( Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1 );
7610             if ( reverse ) {
7611               std::swap( iEnd, iBeg ); iDelta = -1;
7612             }
7613             int i = i2;
7614             while ( true ) {
7615               i += iDelta;
7616               if ( i == iEnd ) i = iBeg + iDelta;
7617               if ( i == i1 ) break;
7618               nodes.push_back ( f->GetNode( i ) );
7619             }
7620           }
7621         }
7622       }
7623     }
7624     // check similarity of elements of the sides
7625     if (( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
7626       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
7627       if ( nReplaceMap.size() == 2 ) { // faces on input nodes not found
7628         return ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7629       }
7630       else {
7631         return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7632       }
7633     }
7634
7635     // set nodes to merge
7636     // -------------------
7637
7638     if ( face[0] && face[1] )  {
7639       if ( nbNodes[0] != nbNodes[1] ) {
7640         MESSAGE("Diff nb of face nodes");
7641         return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7642       }
7643 #ifdef DEBUG_MATCHING_NODES
7644       MESSAGE ( " Link 1: " << link[0].first->GetID() <<" "<< link[0].second->GetID()
7645              << " F 1: " << face[0] << "| Link 2: " << link[1].first->GetID() <<" "
7646              << link[1].second->GetID() << " F 2: " << face[1] << " | Bind: " ) ;
7647 #endif
7648       int nbN = nbNodes[0];
7649       {
7650         list<const SMDS_MeshNode*>::iterator n1 = notLinkNodes[0].begin();
7651         list<const SMDS_MeshNode*>::iterator n2 = notLinkNodes[1].begin();
7652         for ( int i = 0 ; i < nbN - 2; ++i ) {
7653 #ifdef DEBUG_MATCHING_NODES
7654           MESSAGE ( (*n1)->GetID() << " to " << (*n2)->GetID() );
7655 #endif
7656           nReplaceMap.insert( make_pair( *(n1++), *(n2++) ));
7657         }
7658       }
7659
7660       // add other links of the face 1 to linkList
7661       // -----------------------------------------
7662
7663       const SMDS_MeshElement* f0 = face[0];
7664       const SMDS_MeshNode* n1 = f0->GetNode( nbN - 1 );
7665       for ( int i = 0; i < nbN; i++ )
7666       {
7667         const SMDS_MeshNode* n2 = f0->GetNode( i );
7668         pair< set< TLink >::iterator, bool > iter_isnew =
7669           linkSet.insert( TLink( n1, n2 ));
7670         if ( !iter_isnew.second ) { // already in a set: no need to process
7671           linkSet.erase( iter_isnew.first );
7672         }
7673         else // new in set == encountered for the first time: add
7674         {
7675 #ifdef DEBUG_MATCHING_NODES
7676           MESSAGE ( "Add link 1: " << n1->GetID() << " " << n2->GetID() << " "
7677           << " | link 2: " << nReplaceMap[n1]->GetID() << " " << nReplaceMap[n2]->GetID() << " " );
7678 #endif
7679           linkList[0].push_back ( NLink( n1, n2 ));
7680           linkList[1].push_back ( NLink( nReplaceMap[n1], nReplaceMap[n2] ));
7681         }
7682         n1 = n2;
7683       }
7684     } // 2 faces found
7685   } // loop on link lists
7686
7687   return SEW_OK;
7688 }