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