Salome HOME
487646ed9813c9d02aedb1e27294c9d13367ebf6
[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         iRepl[ nbRepl++ ] = iCur;
4867       }
4868       curNodes[ iCur ] = n;
4869       bool isUnique = nodeSet.insert( n ).second;
4870       if ( isUnique )
4871         uniqueNodes[ iUnique++ ] = n;
4872       iCur++;
4873     }
4874
4875     // Analyse element topology after replacement
4876
4877     bool isOk = true;
4878     int nbUniqueNodes = nodeSet.size();
4879     if ( nbNodes != nbUniqueNodes ) { // some nodes stick
4880       // Polygons and Polyhedral volumes
4881       if (elem->IsPoly()) {
4882
4883         if (elem->GetType() == SMDSAbs_Face) {
4884           // Polygon
4885           vector<const SMDS_MeshNode *> face_nodes (nbNodes);
4886           int inode = 0;
4887           for (; inode < nbNodes; inode++) {
4888             face_nodes[inode] = curNodes[inode];
4889           }
4890
4891           vector<const SMDS_MeshNode *> polygons_nodes;
4892           vector<int> quantities;
4893           int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
4894
4895           if (nbNew > 0) {
4896             inode = 0;
4897             for (int iface = 0; iface < nbNew - 1; iface++) {
4898               int nbNodes = quantities[iface];
4899               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4900               for (int ii = 0; ii < nbNodes; ii++, inode++) {
4901                 poly_nodes[ii] = polygons_nodes[inode];
4902               }
4903               SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4904               myLastCreatedElems.Append(newElem);
4905               if (aShapeId)
4906                 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4907             }
4908             aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
4909           }
4910           else {
4911             rmElemIds.push_back(elem->GetID());
4912           }
4913
4914         }
4915         else if (elem->GetType() == SMDSAbs_Volume) {
4916           // Polyhedral volume
4917           if (nbUniqueNodes < 4) {
4918             rmElemIds.push_back(elem->GetID());
4919           }
4920           else {
4921             // each face has to be analized in order to check volume validity
4922             const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4923               static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
4924             if (aPolyedre) {
4925               int nbFaces = aPolyedre->NbFaces();
4926
4927               vector<const SMDS_MeshNode *> poly_nodes;
4928               vector<int> quantities;
4929
4930               for (int iface = 1; iface <= nbFaces; iface++) {
4931                 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4932                 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
4933
4934                 for (int inode = 1; inode <= nbFaceNodes; inode++) {
4935                   const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
4936                   TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
4937                   if (nnIt != nodeNodeMap.end()) { // faceNode sticks
4938                     faceNode = (*nnIt).second;
4939                   }
4940                   faceNodes[inode - 1] = faceNode;
4941                 }
4942
4943                 SimplifyFace(faceNodes, poly_nodes, quantities);
4944               }
4945
4946               if (quantities.size() > 3) {
4947                 // to be done: remove coincident faces
4948               }
4949
4950               if (quantities.size() > 3)
4951                 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4952               else
4953                 rmElemIds.push_back(elem->GetID());
4954
4955             }
4956             else {
4957               rmElemIds.push_back(elem->GetID());
4958             }
4959           }
4960         }
4961         else {
4962         }
4963
4964         continue;
4965       }
4966
4967       // Regular elements
4968       switch ( nbNodes ) {
4969       case 2: ///////////////////////////////////// EDGE
4970         isOk = false; break;
4971       case 3: ///////////////////////////////////// TRIANGLE
4972         isOk = false; break;
4973       case 4:
4974         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
4975           isOk = false;
4976         else { //////////////////////////////////// QUADRANGLE
4977           if ( nbUniqueNodes < 3 )
4978             isOk = false;
4979           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
4980             isOk = false; // opposite nodes stick
4981         }
4982         break;
4983       case 6: ///////////////////////////////////// PENTAHEDRON
4984         if ( nbUniqueNodes == 4 ) {
4985           // ---------------------------------> tetrahedron
4986           if (nbRepl == 3 &&
4987               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
4988             // all top nodes stick: reverse a bottom
4989             uniqueNodes[ 0 ] = curNodes [ 1 ];
4990             uniqueNodes[ 1 ] = curNodes [ 0 ];
4991           }
4992           else if (nbRepl == 3 &&
4993                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
4994             // all bottom nodes stick: set a top before
4995             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
4996             uniqueNodes[ 0 ] = curNodes [ 3 ];
4997             uniqueNodes[ 1 ] = curNodes [ 4 ];
4998             uniqueNodes[ 2 ] = curNodes [ 5 ];
4999           }
5000           else if (nbRepl == 4 &&
5001                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
5002             // a lateral face turns into a line: reverse a bottom
5003             uniqueNodes[ 0 ] = curNodes [ 1 ];
5004             uniqueNodes[ 1 ] = curNodes [ 0 ];
5005           }
5006           else
5007             isOk = false;
5008         }
5009         else if ( nbUniqueNodes == 5 ) {
5010           // PENTAHEDRON --------------------> 2 tetrahedrons
5011           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
5012             // a bottom node sticks with a linked top one
5013             // 1.
5014             SMDS_MeshElement* newElem =
5015               aMesh->AddVolume(curNodes[ 3 ],
5016                                curNodes[ 4 ],
5017                                curNodes[ 5 ],
5018                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
5019             myLastCreatedElems.Append(newElem);
5020             if ( aShapeId )
5021               aMesh->SetMeshElementOnShape( newElem, aShapeId );
5022             // 2. : reverse a bottom
5023             uniqueNodes[ 0 ] = curNodes [ 1 ];
5024             uniqueNodes[ 1 ] = curNodes [ 0 ];
5025             nbUniqueNodes = 4;
5026           }
5027           else
5028             isOk = false;
5029         }
5030         else
5031           isOk = false;
5032         break;
5033       case 8: {
5034         if(elem->IsQuadratic()) { // Quadratic quadrangle
5035           //   1    5    2
5036           //    +---+---+
5037           //    |       |
5038           //    |       |
5039           //   4+       +6
5040           //    |       |
5041           //    |       |
5042           //    +---+---+
5043           //   0    7    3
5044           isOk = false;
5045           if(nbRepl==3) {
5046             nbUniqueNodes = 6;
5047             if( iRepl[0]==0 && iRepl[1]==1 && iRepl[2]==4 ) {
5048               uniqueNodes[0] = curNodes[0];
5049               uniqueNodes[1] = curNodes[2];
5050               uniqueNodes[2] = curNodes[3];
5051               uniqueNodes[3] = curNodes[5];
5052               uniqueNodes[4] = curNodes[6];
5053               uniqueNodes[5] = curNodes[7];
5054               isOk = true;
5055             }
5056             if( iRepl[0]==0 && iRepl[1]==3 && iRepl[2]==7 ) {
5057               uniqueNodes[0] = curNodes[0];
5058               uniqueNodes[1] = curNodes[1];
5059               uniqueNodes[2] = curNodes[2];
5060               uniqueNodes[3] = curNodes[4];
5061               uniqueNodes[4] = curNodes[5];
5062               uniqueNodes[5] = curNodes[6];
5063               isOk = true;
5064             }
5065             if( iRepl[0]==0 && iRepl[1]==4 && iRepl[2]==7 ) {
5066               uniqueNodes[0] = curNodes[1];
5067               uniqueNodes[1] = curNodes[2];
5068               uniqueNodes[2] = curNodes[3];
5069               uniqueNodes[3] = curNodes[5];
5070               uniqueNodes[4] = curNodes[6];
5071               uniqueNodes[5] = curNodes[0];
5072               isOk = true;
5073             }
5074             if( iRepl[0]==1 && iRepl[1]==2 && iRepl[2]==5 ) {
5075               uniqueNodes[0] = curNodes[0];
5076               uniqueNodes[1] = curNodes[1];
5077               uniqueNodes[2] = curNodes[3];
5078               uniqueNodes[3] = curNodes[4];
5079               uniqueNodes[4] = curNodes[6];
5080               uniqueNodes[5] = curNodes[7];
5081               isOk = true;
5082             }
5083             if( iRepl[0]==1 && iRepl[1]==4 && iRepl[2]==5 ) {
5084               uniqueNodes[0] = curNodes[0];
5085               uniqueNodes[1] = curNodes[2];
5086               uniqueNodes[2] = curNodes[3];
5087               uniqueNodes[3] = curNodes[1];
5088               uniqueNodes[4] = curNodes[6];
5089               uniqueNodes[5] = curNodes[7];
5090               isOk = true;
5091             }
5092             if( iRepl[0]==2 && iRepl[1]==3 && iRepl[2]==6 ) {
5093               uniqueNodes[0] = curNodes[0];
5094               uniqueNodes[1] = curNodes[1];
5095               uniqueNodes[2] = curNodes[2];
5096               uniqueNodes[3] = curNodes[4];
5097               uniqueNodes[4] = curNodes[5];
5098               uniqueNodes[5] = curNodes[7];
5099               isOk = true;
5100             }
5101             if( iRepl[0]==2 && iRepl[1]==5 && iRepl[2]==6 ) {
5102               uniqueNodes[0] = curNodes[0];
5103               uniqueNodes[1] = curNodes[1];
5104               uniqueNodes[2] = curNodes[3];
5105               uniqueNodes[3] = curNodes[4];
5106               uniqueNodes[4] = curNodes[2];
5107               uniqueNodes[5] = curNodes[7];
5108               isOk = true;
5109             }
5110             if( iRepl[0]==3 && iRepl[1]==6 && iRepl[2]==7 ) {
5111               uniqueNodes[0] = curNodes[0];
5112               uniqueNodes[1] = curNodes[1];
5113               uniqueNodes[2] = curNodes[2];
5114               uniqueNodes[3] = curNodes[4];
5115               uniqueNodes[4] = curNodes[5];
5116               uniqueNodes[5] = curNodes[3];
5117               isOk = true;
5118             }
5119           }
5120           break;
5121         }
5122         //////////////////////////////////// HEXAHEDRON
5123         isOk = false;
5124         SMDS_VolumeTool hexa (elem);
5125         hexa.SetExternalNormal();
5126         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
5127           //////////////////////// ---> tetrahedron
5128           for ( int iFace = 0; iFace < 6; iFace++ ) {
5129             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
5130             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
5131                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
5132                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
5133               // one face turns into a point ...
5134               int iOppFace = hexa.GetOppFaceIndex( iFace );
5135               ind = hexa.GetFaceNodesIndices( iOppFace );
5136               int nbStick = 0;
5137               iUnique = 2; // reverse a tetrahedron bottom
5138               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
5139                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
5140                   nbStick++;
5141                 else if ( iUnique >= 0 )
5142                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
5143               }
5144               if ( nbStick == 1 ) {
5145                 // ... and the opposite one - into a triangle.
5146                 // set a top node
5147                 ind = hexa.GetFaceNodesIndices( iFace );
5148                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
5149                 isOk = true;
5150               }
5151               break;
5152             }
5153           }
5154         }
5155         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
5156           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
5157           for ( int iFace = 0; iFace < 6; iFace++ ) {
5158             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
5159             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
5160                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
5161                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
5162               // one face turns into a point ...
5163               int iOppFace = hexa.GetOppFaceIndex( iFace );
5164               ind = hexa.GetFaceNodesIndices( iOppFace );
5165               int nbStick = 0;
5166               iUnique = 2;  // reverse a tetrahedron 1 bottom
5167               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
5168                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
5169                   nbStick++;
5170                 else if ( iUnique >= 0 )
5171                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
5172               }
5173               if ( nbStick == 0 ) {
5174                 // ... and the opposite one is a quadrangle
5175                 // set a top node
5176                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
5177                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
5178                 nbUniqueNodes = 4;
5179                 // tetrahedron 2
5180                 SMDS_MeshElement* newElem =
5181                   aMesh->AddVolume(curNodes[ind[ 0 ]],
5182                                    curNodes[ind[ 3 ]],
5183                                    curNodes[ind[ 2 ]],
5184                                    curNodes[indTop[ 0 ]]);
5185                 myLastCreatedElems.Append(newElem);
5186                 if ( aShapeId )
5187                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
5188                 isOk = true;
5189               }
5190               break;
5191             }
5192           }
5193         }
5194         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
5195           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
5196           // find indices of quad and tri faces
5197           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
5198           for ( iFace = 0; iFace < 6; iFace++ ) {
5199             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
5200             nodeSet.clear();
5201             for ( iCur = 0; iCur < 4; iCur++ )
5202               nodeSet.insert( curNodes[ind[ iCur ]] );
5203             nbUniqueNodes = nodeSet.size();
5204             if ( nbUniqueNodes == 3 )
5205               iTriFace[ nbTri++ ] = iFace;
5206             else if ( nbUniqueNodes == 4 )
5207               iQuadFace[ nbQuad++ ] = iFace;
5208           }
5209           if (nbQuad == 2 && nbTri == 4 &&
5210               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
5211             // 2 opposite quadrangles stuck with a diagonal;
5212             // sample groups of merged indices: (0-4)(2-6)
5213             // --------------------------------------------> 2 tetrahedrons
5214             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
5215             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
5216             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
5217             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
5218                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
5219               // stuck with 0-2 diagonal
5220               i0  = ind1[ 3 ];
5221               i1d = ind1[ 0 ];
5222               i2  = ind1[ 1 ];
5223               i3d = ind1[ 2 ];
5224               i0t = ind2[ 1 ];
5225               i2t = ind2[ 3 ];
5226             }
5227             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
5228                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
5229               // stuck with 1-3 diagonal
5230               i0  = ind1[ 0 ];
5231               i1d = ind1[ 1 ];
5232               i2  = ind1[ 2 ];
5233               i3d = ind1[ 3 ];
5234               i0t = ind2[ 0 ];
5235               i2t = ind2[ 1 ];
5236             }
5237             else {
5238               ASSERT(0);
5239             }
5240             // tetrahedron 1
5241             uniqueNodes[ 0 ] = curNodes [ i0 ];
5242             uniqueNodes[ 1 ] = curNodes [ i1d ];
5243             uniqueNodes[ 2 ] = curNodes [ i3d ];
5244             uniqueNodes[ 3 ] = curNodes [ i0t ];
5245             nbUniqueNodes = 4;
5246             // tetrahedron 2
5247             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
5248                                                          curNodes[ i2 ],
5249                                                          curNodes[ i3d ],
5250                                                          curNodes[ i2t ]);
5251             myLastCreatedElems.Append(newElem);
5252             if ( aShapeId )
5253               aMesh->SetMeshElementOnShape( newElem, aShapeId );
5254             isOk = true;
5255           }
5256           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
5257                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
5258             // --------------------------------------------> prism
5259             // find 2 opposite triangles
5260             nbUniqueNodes = 6;
5261             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
5262               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
5263                 // find indices of kept and replaced nodes
5264                 // and fill unique nodes of 2 opposite triangles
5265                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
5266                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
5267                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
5268                 // fill unique nodes
5269                 iUnique = 0;
5270                 isOk = true;
5271                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
5272                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
5273                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
5274                   if ( n == nInit ) {
5275                     // iCur of a linked node of the opposite face (make normals co-directed):
5276                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
5277                     // check that correspondent corners of triangles are linked
5278                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
5279                       isOk = false;
5280                     else {
5281                       uniqueNodes[ iUnique ] = n;
5282                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
5283                       iUnique++;
5284                     }
5285                   }
5286                 }
5287                 break;
5288               }
5289             }
5290           }
5291         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
5292         break;
5293       } // HEXAHEDRON
5294
5295       default:
5296         isOk = false;
5297       } // switch ( nbNodes )
5298
5299     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
5300
5301     if ( isOk ) {
5302       if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
5303         // Change nodes of polyedre
5304         const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
5305           static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
5306         if (aPolyedre) {
5307           int nbFaces = aPolyedre->NbFaces();
5308
5309           vector<const SMDS_MeshNode *> poly_nodes;
5310           vector<int> quantities (nbFaces);
5311
5312           for (int iface = 1; iface <= nbFaces; iface++) {
5313             int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
5314             quantities[iface - 1] = nbFaceNodes;
5315
5316             for (inode = 1; inode <= nbFaceNodes; inode++) {
5317               const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
5318
5319               TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
5320               if (nnIt != nodeNodeMap.end()) { // curNode sticks
5321                 curNode = (*nnIt).second;
5322               }
5323               poly_nodes.push_back(curNode);
5324             }
5325           }
5326           aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
5327         }
5328       }
5329       else {
5330         // Change regular element or polygon
5331         aMesh->ChangeElementNodes( elem, & uniqueNodes[0], nbUniqueNodes );
5332       }
5333     }
5334     else {
5335       // Remove invalid regular element or invalid polygon
5336       rmElemIds.push_back( elem->GetID() );
5337     }
5338
5339   } // loop on elements
5340
5341   // Remove equal nodes and bad elements
5342
5343   Remove( rmNodeIds, true );
5344   Remove( rmElemIds, false );
5345
5346 }
5347
5348
5349 // ========================================================
5350 // class   : SortableElement
5351 // purpose : allow sorting elements basing on their nodes
5352 // ========================================================
5353 class SortableElement : public set <const SMDS_MeshElement*>
5354 {
5355  public:
5356
5357   SortableElement( const SMDS_MeshElement* theElem )
5358     {
5359       myElem = theElem;
5360       SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
5361       while ( nodeIt->more() )
5362         this->insert( nodeIt->next() );
5363     }
5364
5365   const SMDS_MeshElement* Get() const
5366     { return myElem; }
5367
5368   void Set(const SMDS_MeshElement* e) const
5369     { myElem = e; }
5370
5371
5372  private:
5373   mutable const SMDS_MeshElement* myElem;
5374 };
5375
5376 //=======================================================================
5377 //function : FindEqualElements
5378 //purpose  : Return list of group of elements built on the same nodes.
5379 //           Search among theElements or in the whole mesh if theElements is empty
5380 //=======================================================================
5381 void SMESH_MeshEditor::FindEqualElements(set<const SMDS_MeshElement*> & theElements,
5382                                          TListOfListOfElementsID &      theGroupsOfElementsID)
5383 {
5384   myLastCreatedElems.Clear();
5385   myLastCreatedNodes.Clear();
5386
5387   typedef set<const SMDS_MeshElement*> TElemsSet;
5388   typedef map< SortableElement, int > TMapOfNodeSet;
5389   typedef list<int> TGroupOfElems;
5390
5391   TElemsSet elems;
5392   if ( theElements.empty() )
5393   { // get all elements in the mesh
5394     SMDS_ElemIteratorPtr eIt = GetMeshDS()->elementsIterator();
5395     while ( eIt->more() )
5396       elems.insert( elems.end(), eIt->next());
5397   }
5398   else
5399     elems = theElements;
5400
5401   vector< TGroupOfElems > arrayOfGroups;
5402   TGroupOfElems groupOfElems;
5403   TMapOfNodeSet mapOfNodeSet;
5404
5405   TElemsSet::iterator elemIt = elems.begin();
5406   for ( int i = 0, j=0; elemIt != elems.end(); ++elemIt, ++j ) {
5407     const SMDS_MeshElement* curElem = *elemIt;
5408     SortableElement SE(curElem);
5409     int ind = -1;
5410     // check uniqueness
5411     pair< TMapOfNodeSet::iterator, bool> pp = mapOfNodeSet.insert(make_pair(SE, i));
5412     if( !(pp.second) ) {
5413       TMapOfNodeSet::iterator& itSE = pp.first;
5414       ind = (*itSE).second;
5415       arrayOfGroups[ind].push_back(curElem->GetID());
5416     }
5417     else {
5418       groupOfElems.clear();
5419       groupOfElems.push_back(curElem->GetID());
5420       arrayOfGroups.push_back(groupOfElems);
5421       i++;
5422     }
5423   }
5424
5425   vector< TGroupOfElems >::iterator groupIt = arrayOfGroups.begin();
5426   for ( ; groupIt != arrayOfGroups.end(); ++groupIt ) {
5427     groupOfElems = *groupIt;
5428     if ( groupOfElems.size() > 1 ) {
5429       groupOfElems.sort();
5430       theGroupsOfElementsID.push_back(groupOfElems);
5431     }
5432   }
5433 }
5434
5435 //=======================================================================
5436 //function : MergeElements
5437 //purpose  : In each given group, substitute all elements by the first one.
5438 //=======================================================================
5439
5440 void SMESH_MeshEditor::MergeElements(TListOfListOfElementsID & theGroupsOfElementsID)
5441 {
5442   myLastCreatedElems.Clear();
5443   myLastCreatedNodes.Clear();
5444
5445   typedef list<int> TListOfIDs;
5446   TListOfIDs rmElemIds; // IDs of elems to remove
5447
5448   SMESHDS_Mesh* aMesh = GetMeshDS();
5449
5450   TListOfListOfElementsID::iterator groupsIt = theGroupsOfElementsID.begin();
5451   while ( groupsIt != theGroupsOfElementsID.end() ) {
5452     TListOfIDs& aGroupOfElemID = *groupsIt;
5453     aGroupOfElemID.sort();
5454     int elemIDToKeep = aGroupOfElemID.front();
5455     const SMDS_MeshElement* elemToKeep = aMesh->FindElement(elemIDToKeep);
5456     aGroupOfElemID.pop_front();
5457     TListOfIDs::iterator idIt = aGroupOfElemID.begin();
5458     while ( idIt != aGroupOfElemID.end() ) {
5459       int elemIDToRemove = *idIt;
5460       const SMDS_MeshElement* elemToRemove = aMesh->FindElement(elemIDToRemove);
5461       // add the kept element in groups of removed one (PAL15188)
5462       AddToSameGroups( elemToKeep, elemToRemove, aMesh );
5463       rmElemIds.push_back( elemIDToRemove );
5464       ++idIt;
5465     }
5466     ++groupsIt;
5467   }
5468
5469   Remove( rmElemIds, false );
5470 }
5471
5472 //=======================================================================
5473 //function : MergeEqualElements
5474 //purpose  : Remove all but one of elements built on the same nodes.
5475 //=======================================================================
5476
5477 void SMESH_MeshEditor::MergeEqualElements()
5478 {
5479   set<const SMDS_MeshElement*> aMeshElements; /* empty input -
5480                                                  to merge equal elements in the whole mesh */
5481   TListOfListOfElementsID aGroupsOfElementsID;
5482   FindEqualElements(aMeshElements, aGroupsOfElementsID);
5483   MergeElements(aGroupsOfElementsID);
5484 }
5485
5486 //=======================================================================
5487 //function : FindFaceInSet
5488 //purpose  : Return a face having linked nodes n1 and n2 and which is
5489 //           - not in avoidSet,
5490 //           - in elemSet provided that !elemSet.empty()
5491 //=======================================================================
5492
5493 const SMDS_MeshElement*
5494   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*    n1,
5495                                   const SMDS_MeshNode*    n2,
5496                                   const TIDSortedElemSet& elemSet,
5497                                   const TIDSortedElemSet& avoidSet)
5498
5499 {
5500   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
5501   while ( invElemIt->more() ) { // loop on inverse elements of n1
5502     const SMDS_MeshElement* elem = invElemIt->next();
5503     if (avoidSet.find( elem ) != avoidSet.end() )
5504       continue;
5505     if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
5506       continue;
5507     // get face nodes and find index of n1
5508     int i1, nbN = elem->NbNodes(), iNode = 0;
5509     //const SMDS_MeshNode* faceNodes[ nbN ], *n;
5510     vector<const SMDS_MeshNode*> faceNodes( nbN );
5511     const SMDS_MeshNode* n;
5512     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
5513     while ( nIt->more() ) {
5514       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5515       if ( faceNodes[ iNode++ ] == n1 )
5516         i1 = iNode - 1;
5517     }
5518     // find a n2 linked to n1
5519     if(!elem->IsQuadratic()) {
5520       for ( iNode = 0; iNode < 2; iNode++ ) {
5521         if ( iNode ) // node before n1
5522           n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
5523         else         // node after n1
5524           n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
5525         if ( n == n2 )
5526           return elem;
5527       }
5528     }
5529     else { // analysis for quadratic elements
5530       bool IsFind = false;
5531       // check using only corner nodes
5532       for ( iNode = 0; iNode < 2; iNode++ ) {
5533         if ( iNode ) // node before n1
5534           n = faceNodes[ i1 == 0 ? nbN/2 - 1 : i1 - 1 ];
5535         else         // node after n1
5536           n = faceNodes[ i1 + 1 == nbN/2 ? 0 : i1 + 1 ];
5537         if ( n == n2 )
5538           IsFind = true;
5539       }
5540       if(IsFind) {
5541         return elem;
5542       }
5543       else {
5544         // check using all nodes
5545         const SMDS_QuadraticFaceOfNodes* F =
5546           static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5547         // use special nodes iterator
5548         iNode = 0;
5549         SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5550         while ( anIter->more() ) {
5551           faceNodes[iNode] = static_cast<const SMDS_MeshNode*>(anIter->next());
5552           if ( faceNodes[ iNode++ ] == n1 )
5553             i1 = iNode - 1;
5554         }
5555         for ( iNode = 0; iNode < 2; iNode++ ) {
5556           if ( iNode ) // node before n1
5557             n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
5558           else         // node after n1
5559             n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
5560           if ( n == n2 ) {
5561             return elem;
5562           }
5563         }
5564       }
5565     } // end analysis for quadratic elements
5566   }
5567   return 0;
5568 }
5569
5570 //=======================================================================
5571 //function : findAdjacentFace
5572 //purpose  :
5573 //=======================================================================
5574
5575 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
5576                                                 const SMDS_MeshNode* n2,
5577                                                 const SMDS_MeshElement* elem)
5578 {
5579   TIDSortedElemSet elemSet, avoidSet;
5580   if ( elem )
5581     avoidSet.insert ( elem );
5582   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
5583 }
5584
5585 //=======================================================================
5586 //function : FindFreeBorder
5587 //purpose  :
5588 //=======================================================================
5589
5590 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
5591
5592 bool SMESH_MeshEditor::FindFreeBorder (const SMDS_MeshNode*             theFirstNode,
5593                                        const SMDS_MeshNode*             theSecondNode,
5594                                        const SMDS_MeshNode*             theLastNode,
5595                                        list< const SMDS_MeshNode* > &   theNodes,
5596                                        list< const SMDS_MeshElement* >& theFaces)
5597 {
5598   if ( !theFirstNode || !theSecondNode )
5599     return false;
5600   // find border face between theFirstNode and theSecondNode
5601   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
5602   if ( !curElem )
5603     return false;
5604
5605   theFaces.push_back( curElem );
5606   theNodes.push_back( theFirstNode );
5607   theNodes.push_back( theSecondNode );
5608
5609   //vector<const SMDS_MeshNode*> nodes;
5610   const SMDS_MeshNode *nIgnore = theFirstNode, *nStart = theSecondNode;
5611   set < const SMDS_MeshElement* > foundElems;
5612   bool needTheLast = ( theLastNode != 0 );
5613
5614   while ( nStart != theLastNode ) {
5615     if ( nStart == theFirstNode )
5616       return !needTheLast;
5617
5618     // find all free border faces sharing form nStart
5619
5620     list< const SMDS_MeshElement* > curElemList;
5621     list< const SMDS_MeshNode* > nStartList;
5622     SMDS_ElemIteratorPtr invElemIt = nStart->GetInverseElementIterator(SMDSAbs_Face);
5623     while ( invElemIt->more() ) {
5624       const SMDS_MeshElement* e = invElemIt->next();
5625       if ( e == curElem || foundElems.insert( e ).second ) {
5626         // get nodes
5627         int iNode = 0, nbNodes = e->NbNodes();
5628         //const SMDS_MeshNode* nodes[nbNodes+1];
5629         vector<const SMDS_MeshNode*> nodes(nbNodes+1);
5630         
5631         if(e->IsQuadratic()) {
5632           const SMDS_QuadraticFaceOfNodes* F =
5633             static_cast<const SMDS_QuadraticFaceOfNodes*>(e);
5634           // use special nodes iterator
5635           SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5636           while( anIter->more() ) {
5637             nodes[ iNode++ ] = anIter->next();
5638           }
5639         }
5640         else {
5641           SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5642           while ( nIt->more() )
5643             nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5644         }
5645         nodes[ iNode ] = nodes[ 0 ];
5646         // check 2 links
5647         for ( iNode = 0; iNode < nbNodes; iNode++ )
5648           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
5649                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
5650               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
5651           {
5652             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
5653             curElemList.push_back( e );
5654           }
5655       }
5656     }
5657     // analyse the found
5658
5659     int nbNewBorders = curElemList.size();
5660     if ( nbNewBorders == 0 ) {
5661       // no free border furthermore
5662       return !needTheLast;
5663     }
5664     else if ( nbNewBorders == 1 ) {
5665       // one more element found
5666       nIgnore = nStart;
5667       nStart = nStartList.front();
5668       curElem = curElemList.front();
5669       theFaces.push_back( curElem );
5670       theNodes.push_back( nStart );
5671     }
5672     else {
5673       // several continuations found
5674       list< const SMDS_MeshElement* >::iterator curElemIt;
5675       list< const SMDS_MeshNode* >::iterator nStartIt;
5676       // check if one of them reached the last node
5677       if ( needTheLast ) {
5678         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5679              curElemIt!= curElemList.end();
5680              curElemIt++, nStartIt++ )
5681           if ( *nStartIt == theLastNode ) {
5682             theFaces.push_back( *curElemIt );
5683             theNodes.push_back( *nStartIt );
5684             return true;
5685           }
5686       }
5687       // find the best free border by the continuations
5688       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
5689       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
5690       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5691            curElemIt!= curElemList.end();
5692            curElemIt++, nStartIt++ )
5693       {
5694         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
5695         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
5696         // find one more free border
5697         if ( ! FindFreeBorder( nStart, *nStartIt, theLastNode, *cNL, *cFL )) {
5698           cNL->clear();
5699           cFL->clear();
5700         }
5701         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
5702           // choice: clear a worse one
5703           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
5704           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
5705           contNodes[ iWorse ].clear();
5706           contFaces[ iWorse ].clear();
5707         }
5708       }
5709       if ( contNodes[0].empty() && contNodes[1].empty() )
5710         return false;
5711
5712       // append the best free border
5713       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
5714       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
5715       theNodes.pop_back(); // remove nIgnore
5716       theNodes.pop_back(); // remove nStart
5717       theFaces.pop_back(); // remove curElem
5718       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
5719       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
5720       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
5721       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
5722       return true;
5723
5724     } // several continuations found
5725   } // while ( nStart != theLastNode )
5726
5727   return true;
5728 }
5729
5730 //=======================================================================
5731 //function : CheckFreeBorderNodes
5732 //purpose  : Return true if the tree nodes are on a free border
5733 //=======================================================================
5734
5735 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
5736                                             const SMDS_MeshNode* theNode2,
5737                                             const SMDS_MeshNode* theNode3)
5738 {
5739   list< const SMDS_MeshNode* > nodes;
5740   list< const SMDS_MeshElement* > faces;
5741   return FindFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
5742 }
5743
5744 //=======================================================================
5745 //function : SewFreeBorder
5746 //purpose  :
5747 //=======================================================================
5748
5749 SMESH_MeshEditor::Sew_Error
5750   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
5751                                    const SMDS_MeshNode* theBordSecondNode,
5752                                    const SMDS_MeshNode* theBordLastNode,
5753                                    const SMDS_MeshNode* theSideFirstNode,
5754                                    const SMDS_MeshNode* theSideSecondNode,
5755                                    const SMDS_MeshNode* theSideThirdNode,
5756                                    const bool           theSideIsFreeBorder,
5757                                    const bool           toCreatePolygons,
5758                                    const bool           toCreatePolyedrs)
5759 {
5760   myLastCreatedElems.Clear();
5761   myLastCreatedNodes.Clear();
5762
5763   MESSAGE("::SewFreeBorder()");
5764   Sew_Error aResult = SEW_OK;
5765
5766   // ====================================
5767   //    find side nodes and elements
5768   // ====================================
5769
5770   list< const SMDS_MeshNode* > nSide[ 2 ];
5771   list< const SMDS_MeshElement* > eSide[ 2 ];
5772   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
5773   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
5774
5775   // Free border 1
5776   // --------------
5777   if (!FindFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
5778                       nSide[0], eSide[0])) {
5779     MESSAGE(" Free Border 1 not found " );
5780     aResult = SEW_BORDER1_NOT_FOUND;
5781   }
5782   if (theSideIsFreeBorder) {
5783     // Free border 2
5784     // --------------
5785     if (!FindFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
5786                         nSide[1], eSide[1])) {
5787       MESSAGE(" Free Border 2 not found " );
5788       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
5789     }
5790   }
5791   if ( aResult != SEW_OK )
5792     return aResult;
5793
5794   if (!theSideIsFreeBorder) {
5795     // Side 2
5796     // --------------
5797
5798     // -------------------------------------------------------------------------
5799     // Algo:
5800     // 1. If nodes to merge are not coincident, move nodes of the free border
5801     //    from the coord sys defined by the direction from the first to last
5802     //    nodes of the border to the correspondent sys of the side 2
5803     // 2. On the side 2, find the links most co-directed with the correspondent
5804     //    links of the free border
5805     // -------------------------------------------------------------------------
5806
5807     // 1. Since sewing may brake if there are volumes to split on the side 2,
5808     //    we wont move nodes but just compute new coordinates for them
5809     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
5810     TNodeXYZMap nBordXYZ;
5811     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
5812     list< const SMDS_MeshNode* >::iterator nBordIt;
5813
5814     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
5815     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
5816     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
5817     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
5818     double tol2 = 1.e-8;
5819     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
5820     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 ) {
5821       // Need node movement.
5822
5823       // find X and Z axes to create trsf
5824       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
5825       gp_Vec X = Zs ^ Zb;
5826       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
5827         // Zb || Zs
5828         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
5829
5830       // coord systems
5831       gp_Ax3 toBordAx( Pb1, Zb, X );
5832       gp_Ax3 fromSideAx( Ps1, Zs, X );
5833       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
5834       // set trsf
5835       gp_Trsf toBordSys, fromSide2Sys;
5836       toBordSys.SetTransformation( toBordAx );
5837       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
5838       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
5839
5840       // move
5841       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5842         const SMDS_MeshNode* n = *nBordIt;
5843         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
5844         toBordSys.Transforms( xyz );
5845         fromSide2Sys.Transforms( xyz );
5846         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
5847       }
5848     }
5849     else {
5850       // just insert nodes XYZ in the nBordXYZ map
5851       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5852         const SMDS_MeshNode* n = *nBordIt;
5853         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
5854       }
5855     }
5856
5857     // 2. On the side 2, find the links most co-directed with the correspondent
5858     //    links of the free border
5859
5860     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
5861     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
5862     sideNodes.push_back( theSideFirstNode );
5863
5864     bool hasVolumes = false;
5865     LinkID_Gen aLinkID_Gen( GetMeshDS() );
5866     set<long> foundSideLinkIDs, checkedLinkIDs;
5867     SMDS_VolumeTool volume;
5868     //const SMDS_MeshNode* faceNodes[ 4 ];
5869
5870     const SMDS_MeshNode*    sideNode;
5871     const SMDS_MeshElement* sideElem;
5872     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
5873     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
5874     nBordIt = bordNodes.begin();
5875     nBordIt++;
5876     // border node position and border link direction to compare with
5877     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
5878     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
5879     // choose next side node by link direction or by closeness to
5880     // the current border node:
5881     bool searchByDir = ( *nBordIt != theBordLastNode );
5882     do {
5883       // find the next node on the Side 2
5884       sideNode = 0;
5885       double maxDot = -DBL_MAX, minDist = DBL_MAX;
5886       long linkID;
5887       checkedLinkIDs.clear();
5888       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
5889
5890       // loop on inverse elements of current node (prevSideNode) on the Side 2
5891       SMDS_ElemIteratorPtr invElemIt = prevSideNode->GetInverseElementIterator();
5892       while ( invElemIt->more() )
5893       {
5894         const SMDS_MeshElement* elem = invElemIt->next();
5895         // prepare data for a loop on links coming to prevSideNode, of a face or a volume
5896         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
5897         vector< const SMDS_MeshNode* > faceNodes( nbNodes, (const SMDS_MeshNode*)0 );
5898         bool isVolume = volume.Set( elem );
5899         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : & faceNodes[0];
5900         if ( isVolume ) // --volume
5901           hasVolumes = true;
5902         else if ( elem->GetType()==SMDSAbs_Face ) { // --face
5903           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
5904           if(elem->IsQuadratic()) {
5905             const SMDS_QuadraticFaceOfNodes* F =
5906               static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5907             // use special nodes iterator
5908             SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5909             while( anIter->more() ) {
5910               nodes[ iNode ] = anIter->next();
5911               if ( nodes[ iNode++ ] == prevSideNode )
5912                 iPrevNode = iNode - 1;
5913             }
5914           }
5915           else {
5916             SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
5917             while ( nIt->more() ) {
5918               nodes[ iNode ] = cast2Node( nIt->next() );
5919               if ( nodes[ iNode++ ] == prevSideNode )
5920                 iPrevNode = iNode - 1;
5921             }
5922           }
5923           // there are 2 links to check
5924           nbNodes = 2;
5925         }
5926         else // --edge
5927           continue;
5928         // loop on links, to be precise, on the second node of links
5929         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
5930           const SMDS_MeshNode* n = nodes[ iNode ];
5931           if ( isVolume ) {
5932             if ( !volume.IsLinked( n, prevSideNode ))
5933               continue;
5934           }
5935           else {
5936             if ( iNode ) // a node before prevSideNode
5937               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
5938             else         // a node after prevSideNode
5939               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
5940           }
5941           // check if this link was already used
5942           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
5943           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
5944           if (!isJustChecked &&
5945               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() )
5946           {
5947             // test a link geometrically
5948             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
5949             bool linkIsBetter = false;
5950             double dot = 0.0, dist = 0.0;
5951             if ( searchByDir ) { // choose most co-directed link
5952               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
5953               linkIsBetter = ( dot > maxDot );
5954             }
5955             else { // choose link with the node closest to bordPos
5956               dist = ( nextXYZ - bordPos ).SquareModulus();
5957               linkIsBetter = ( dist < minDist );
5958             }
5959             if ( linkIsBetter ) {
5960               maxDot = dot;
5961               minDist = dist;
5962               linkID = iLink;
5963               sideNode = n;
5964               sideElem = elem;
5965             }
5966           }
5967         }
5968       } // loop on inverse elements of prevSideNode
5969
5970       if ( !sideNode ) {
5971         MESSAGE(" Cant find path by links of the Side 2 ");
5972         return SEW_BAD_SIDE_NODES;
5973       }
5974       sideNodes.push_back( sideNode );
5975       sideElems.push_back( sideElem );
5976       foundSideLinkIDs.insert ( linkID );
5977       prevSideNode = sideNode;
5978
5979       if ( *nBordIt == theBordLastNode )
5980         searchByDir = false;
5981       else {
5982         // find the next border link to compare with
5983         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
5984         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5985         // move to next border node if sideNode is before forward border node (bordPos)
5986         while ( *nBordIt != theBordLastNode && !searchByDir ) {
5987           prevBordNode = *nBordIt;
5988           nBordIt++;
5989           bordPos = nBordXYZ[ *nBordIt ];
5990           bordDir = bordPos - nBordXYZ[ prevBordNode ];
5991           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5992         }
5993       }
5994     }
5995     while ( sideNode != theSideSecondNode );
5996
5997     if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
5998       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
5999       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
6000     }
6001   } // end nodes search on the side 2
6002
6003   // ============================
6004   // sew the border to the side 2
6005   // ============================
6006
6007   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
6008   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
6009
6010   TListOfListOfNodes nodeGroupsToMerge;
6011   if ( nbNodes[0] == nbNodes[1] ||
6012       ( theSideIsFreeBorder && !theSideThirdNode)) {
6013
6014     // all nodes are to be merged
6015
6016     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
6017          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
6018          nIt[0]++, nIt[1]++ )
6019     {
6020       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
6021       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
6022       nodeGroupsToMerge.back().push_back( *nIt[0] ); // to remove
6023     }
6024   }
6025   else {
6026
6027     // insert new nodes into the border and the side to get equal nb of segments
6028
6029     // get normalized parameters of nodes on the borders
6030     //double param[ 2 ][ maxNbNodes ];
6031     double* param[ 2 ];
6032     param[0] = new double [ maxNbNodes ];
6033     param[1] = new double [ maxNbNodes ];
6034     int iNode, iBord;
6035     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
6036       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
6037       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
6038       const SMDS_MeshNode* nPrev = *nIt;
6039       double bordLength = 0;
6040       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
6041         const SMDS_MeshNode* nCur = *nIt;
6042         gp_XYZ segment (nCur->X() - nPrev->X(),
6043                         nCur->Y() - nPrev->Y(),
6044                         nCur->Z() - nPrev->Z());
6045         double segmentLen = segment.Modulus();
6046         bordLength += segmentLen;
6047         param[ iBord ][ iNode ] = bordLength;
6048         nPrev = nCur;
6049       }
6050       // normalize within [0,1]
6051       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
6052         param[ iBord ][ iNode ] /= bordLength;
6053       }
6054     }
6055
6056     // loop on border segments
6057     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
6058     int i[ 2 ] = { 0, 0 };
6059     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
6060     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
6061
6062     TElemOfNodeListMap insertMap;
6063     TElemOfNodeListMap::iterator insertMapIt;
6064     // insertMap is
6065     // key:   elem to insert nodes into
6066     // value: 2 nodes to insert between + nodes to be inserted
6067     do {
6068       bool next[ 2 ] = { false, false };
6069
6070       // find min adjacent segment length after sewing
6071       double nextParam = 10., prevParam = 0;
6072       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
6073         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
6074           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
6075         if ( i[ iBord ] > 0 )
6076           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
6077       }
6078       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
6079       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
6080       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
6081
6082       // choose to insert or to merge nodes
6083       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
6084       if ( Abs( du ) <= minSegLen * 0.2 ) {
6085         // merge
6086         // ------
6087         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
6088         const SMDS_MeshNode* n0 = *nIt[0];
6089         const SMDS_MeshNode* n1 = *nIt[1];
6090         nodeGroupsToMerge.back().push_back( n1 );
6091         nodeGroupsToMerge.back().push_back( n0 );
6092         // position of node of the border changes due to merge
6093         param[ 0 ][ i[0] ] += du;
6094         // move n1 for the sake of elem shape evaluation during insertion.
6095         // n1 will be removed by MergeNodes() anyway
6096         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
6097         next[0] = next[1] = true;
6098       }
6099       else {
6100         // insert
6101         // ------
6102         int intoBord = ( du < 0 ) ? 0 : 1;
6103         const SMDS_MeshElement* elem = *eIt[ intoBord ];
6104         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
6105         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
6106         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
6107         if ( intoBord == 1 ) {
6108           // move node of the border to be on a link of elem of the side
6109           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
6110           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
6111           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
6112           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
6113           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
6114         }
6115         insertMapIt = insertMap.find( elem );
6116         bool notFound = ( insertMapIt == insertMap.end() );
6117         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
6118         if ( otherLink ) {
6119           // insert into another link of the same element:
6120           // 1. perform insertion into the other link of the elem
6121           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
6122           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
6123           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
6124           InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
6125           // 2. perform insertion into the link of adjacent faces
6126           while (true) {
6127             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
6128             if ( adjElem )
6129               InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
6130             else
6131               break;
6132           }
6133           if (toCreatePolyedrs) {
6134             // perform insertion into the links of adjacent volumes
6135             UpdateVolumes(n12, n22, nodeList);
6136           }
6137           // 3. find an element appeared on n1 and n2 after the insertion
6138           insertMap.erase( elem );
6139           elem = findAdjacentFace( n1, n2, 0 );
6140         }
6141         if ( notFound || otherLink ) {
6142           // add element and nodes of the side into the insertMap
6143           insertMapIt = insertMap.insert
6144             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
6145           (*insertMapIt).second.push_back( n1 );
6146           (*insertMapIt).second.push_back( n2 );
6147         }
6148         // add node to be inserted into elem
6149         (*insertMapIt).second.push_back( nIns );
6150         next[ 1 - intoBord ] = true;
6151       }
6152
6153       // go to the next segment
6154       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
6155         if ( next[ iBord ] ) {
6156           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
6157             eIt[ iBord ]++;
6158           nPrev[ iBord ] = *nIt[ iBord ];
6159           nIt[ iBord ]++; i[ iBord ]++;
6160         }
6161       }
6162     }
6163     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
6164
6165     // perform insertion of nodes into elements
6166
6167     for (insertMapIt = insertMap.begin();
6168          insertMapIt != insertMap.end();
6169          insertMapIt++ )
6170     {
6171       const SMDS_MeshElement* elem = (*insertMapIt).first;
6172       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
6173       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
6174       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
6175
6176       InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
6177
6178       if ( !theSideIsFreeBorder ) {
6179         // look for and insert nodes into the faces adjacent to elem
6180         while (true) {
6181           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
6182           if ( adjElem )
6183             InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
6184           else
6185             break;
6186         }
6187       }
6188       if (toCreatePolyedrs) {
6189         // perform insertion into the links of adjacent volumes
6190         UpdateVolumes(n1, n2, nodeList);
6191       }
6192     }
6193
6194     delete param[0];
6195     delete param[1];
6196   } // end: insert new nodes
6197
6198   MergeNodes ( nodeGroupsToMerge );
6199
6200   return aResult;
6201 }
6202
6203 //=======================================================================
6204 //function : InsertNodesIntoLink
6205 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
6206 //           and theBetweenNode2 and split theElement
6207 //=======================================================================
6208
6209 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
6210                                            const SMDS_MeshNode*        theBetweenNode1,
6211                                            const SMDS_MeshNode*        theBetweenNode2,
6212                                            list<const SMDS_MeshNode*>& theNodesToInsert,
6213                                            const bool                  toCreatePoly)
6214 {
6215   if ( theFace->GetType() != SMDSAbs_Face ) return;
6216
6217   // find indices of 2 link nodes and of the rest nodes
6218   int iNode = 0, il1, il2, i3, i4;
6219   il1 = il2 = i3 = i4 = -1;
6220   //const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
6221   vector<const SMDS_MeshNode*> nodes( theFace->NbNodes() );
6222
6223   if(theFace->IsQuadratic()) {
6224     const SMDS_QuadraticFaceOfNodes* F =
6225       static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
6226     // use special nodes iterator
6227     SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
6228     while( anIter->more() ) {
6229       const SMDS_MeshNode* n = anIter->next();
6230       if ( n == theBetweenNode1 )
6231         il1 = iNode;
6232       else if ( n == theBetweenNode2 )
6233         il2 = iNode;
6234       else if ( i3 < 0 )
6235         i3 = iNode;
6236       else
6237         i4 = iNode;
6238       nodes[ iNode++ ] = n;
6239     }
6240   }
6241   else {
6242     SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
6243     while ( nodeIt->more() ) {
6244       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6245       if ( n == theBetweenNode1 )
6246         il1 = iNode;
6247       else if ( n == theBetweenNode2 )
6248         il2 = iNode;
6249       else if ( i3 < 0 )
6250         i3 = iNode;
6251       else
6252         i4 = iNode;
6253       nodes[ iNode++ ] = n;
6254     }
6255   }
6256   if ( il1 < 0 || il2 < 0 || i3 < 0 )
6257     return ;
6258
6259   // arrange link nodes to go one after another regarding the face orientation
6260   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
6261   list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
6262   if ( reverse ) {
6263     iNode = il1;
6264     il1 = il2;
6265     il2 = iNode;
6266     aNodesToInsert.reverse();
6267   }
6268   // check that not link nodes of a quadrangles are in good order
6269   int nbFaceNodes = theFace->NbNodes();
6270   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
6271     iNode = i3;
6272     i3 = i4;
6273     i4 = iNode;
6274   }
6275
6276   if (toCreatePoly || theFace->IsPoly()) {
6277
6278     iNode = 0;
6279     vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
6280
6281     // add nodes of face up to first node of link
6282     bool isFLN = false;
6283
6284     if(theFace->IsQuadratic()) {
6285       const SMDS_QuadraticFaceOfNodes* F =
6286         static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
6287       // use special nodes iterator
6288       SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
6289       while( anIter->more()  && !isFLN ) {
6290         const SMDS_MeshNode* n = anIter->next();
6291         poly_nodes[iNode++] = n;
6292         if (n == nodes[il1]) {
6293           isFLN = true;
6294         }
6295       }
6296       // add nodes to insert
6297       list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
6298       for (; nIt != aNodesToInsert.end(); nIt++) {
6299         poly_nodes[iNode++] = *nIt;
6300       }
6301       // add nodes of face starting from last node of link
6302       while ( anIter->more() ) {
6303         poly_nodes[iNode++] = anIter->next();
6304       }
6305     }
6306     else {
6307       SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
6308       while ( nodeIt->more() && !isFLN ) {
6309         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->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 ( nodeIt->more() ) {
6322         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6323         poly_nodes[iNode++] = n;
6324       }
6325     }
6326
6327     // edit or replace the face
6328     SMESHDS_Mesh *aMesh = GetMeshDS();
6329
6330     if (theFace->IsPoly()) {
6331       aMesh->ChangePolygonNodes(theFace, poly_nodes);
6332     }
6333     else {
6334       int aShapeId = FindShape( theFace );
6335
6336       SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
6337       myLastCreatedElems.Append(newElem);
6338       if ( aShapeId && newElem )
6339         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6340
6341       aMesh->RemoveElement(theFace);
6342     }
6343     return;
6344   }
6345
6346   if( !theFace->IsQuadratic() ) {
6347
6348     // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
6349     int nbLinkNodes = 2 + aNodesToInsert.size();
6350     //const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
6351     vector<const SMDS_MeshNode*> linkNodes( nbLinkNodes );
6352     linkNodes[ 0 ] = nodes[ il1 ];
6353     linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
6354     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
6355     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
6356       linkNodes[ iNode++ ] = *nIt;
6357     }
6358     // decide how to split a quadrangle: compare possible variants
6359     // and choose which of splits to be a quadrangle
6360     int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
6361     if ( nbFaceNodes == 3 ) {
6362       iBestQuad = nbSplits;
6363       i4 = i3;
6364     }
6365     else if ( nbFaceNodes == 4 ) {
6366       SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
6367       double aBestRate = DBL_MAX;
6368       for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
6369         i1 = 0; i2 = 1;
6370         double aBadRate = 0;
6371         // evaluate elements quality
6372         for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
6373           if ( iSplit == iQuad ) {
6374             SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
6375                                    linkNodes[ i2++ ],
6376                                    nodes[ i3 ],
6377                                    nodes[ i4 ]);
6378             aBadRate += getBadRate( &quad, aCrit );
6379           }
6380           else {
6381             SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
6382                                    linkNodes[ i2++ ],
6383                                    nodes[ iSplit < iQuad ? i4 : i3 ]);
6384             aBadRate += getBadRate( &tria, aCrit );
6385           }
6386         }
6387         // choice
6388         if ( aBadRate < aBestRate ) {
6389           iBestQuad = iQuad;
6390           aBestRate = aBadRate;
6391         }
6392       }
6393     }
6394
6395     // create new elements
6396     SMESHDS_Mesh *aMesh = GetMeshDS();
6397     int aShapeId = FindShape( theFace );
6398
6399     i1 = 0; i2 = 1;
6400     for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
6401       SMDS_MeshElement* newElem = 0;
6402       if ( iSplit == iBestQuad )
6403         newElem = aMesh->AddFace (linkNodes[ i1++ ],
6404                                   linkNodes[ i2++ ],
6405                                   nodes[ i3 ],
6406                                   nodes[ i4 ]);
6407       else
6408         newElem = aMesh->AddFace (linkNodes[ i1++ ],
6409                                   linkNodes[ i2++ ],
6410                                   nodes[ iSplit < iBestQuad ? i4 : i3 ]);
6411       myLastCreatedElems.Append(newElem);
6412       if ( aShapeId && newElem )
6413         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6414     }
6415
6416     // change nodes of theFace
6417     const SMDS_MeshNode* newNodes[ 4 ];
6418     newNodes[ 0 ] = linkNodes[ i1 ];
6419     newNodes[ 1 ] = linkNodes[ i2 ];
6420     newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
6421     newNodes[ 3 ] = nodes[ i4 ];
6422     aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
6423   } // end if(!theFace->IsQuadratic())
6424   else { // theFace is quadratic
6425     // we have to split theFace on simple triangles and one simple quadrangle
6426     int tmp = il1/2;
6427     int nbshift = tmp*2;
6428     // shift nodes in nodes[] by nbshift
6429     int i,j;
6430     for(i=0; i<nbshift; i++) {
6431       const SMDS_MeshNode* n = nodes[0];
6432       for(j=0; j<nbFaceNodes-1; j++) {
6433         nodes[j] = nodes[j+1];
6434       }
6435       nodes[nbFaceNodes-1] = n;
6436     }
6437     il1 = il1 - nbshift;
6438     // now have to insert nodes between n0 and n1 or n1 and n2 (see below)
6439     //   n0      n1     n2    n0      n1     n2
6440     //     +-----+-----+        +-----+-----+
6441     //      \         /         |           |
6442     //       \       /          |           |
6443     //      n5+     +n3       n7+           +n3
6444     //         \   /            |           |
6445     //          \ /             |           |
6446     //           +              +-----+-----+
6447     //           n4           n6      n5     n4
6448
6449     // create new elements
6450     SMESHDS_Mesh *aMesh = GetMeshDS();
6451     int aShapeId = FindShape( theFace );
6452
6453     int n1,n2,n3;
6454     if(nbFaceNodes==6) { // quadratic triangle
6455       SMDS_MeshElement* newElem =
6456         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
6457       myLastCreatedElems.Append(newElem);
6458       if ( aShapeId && newElem )
6459         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6460       if(theFace->IsMediumNode(nodes[il1])) {
6461         // create quadrangle
6462         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[5]);
6463         myLastCreatedElems.Append(newElem);
6464         if ( aShapeId && newElem )
6465           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6466         n1 = 1;
6467         n2 = 2;
6468         n3 = 3;
6469       }
6470       else {
6471         // create quadrangle
6472         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[5]);
6473         myLastCreatedElems.Append(newElem);
6474         if ( aShapeId && newElem )
6475           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6476         n1 = 0;
6477         n2 = 1;
6478         n3 = 5;
6479       }
6480     }
6481     else { // nbFaceNodes==8 - quadratic quadrangle
6482       SMDS_MeshElement* newElem =
6483         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
6484       myLastCreatedElems.Append(newElem);
6485       if ( aShapeId && newElem )
6486         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6487       newElem = aMesh->AddFace(nodes[5],nodes[6],nodes[7]);
6488       myLastCreatedElems.Append(newElem);
6489       if ( aShapeId && newElem )
6490         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6491       newElem = aMesh->AddFace(nodes[5],nodes[7],nodes[3]);
6492       myLastCreatedElems.Append(newElem);
6493       if ( aShapeId && newElem )
6494         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6495       if(theFace->IsMediumNode(nodes[il1])) {
6496         // create quadrangle
6497         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[7]);
6498         myLastCreatedElems.Append(newElem);
6499         if ( aShapeId && newElem )
6500           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6501         n1 = 1;
6502         n2 = 2;
6503         n3 = 3;
6504       }
6505       else {
6506         // create quadrangle
6507         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[7]);
6508         myLastCreatedElems.Append(newElem);
6509         if ( aShapeId && newElem )
6510           aMesh->SetMeshElementOnShape( newElem, aShapeId );
6511         n1 = 0;
6512         n2 = 1;
6513         n3 = 7;
6514       }
6515     }
6516     // create needed triangles using n1,n2,n3 and inserted nodes
6517     int nbn = 2 + aNodesToInsert.size();
6518     //const SMDS_MeshNode* aNodes[nbn];
6519     vector<const SMDS_MeshNode*> aNodes(nbn);
6520     aNodes[0] = nodes[n1];
6521     aNodes[nbn-1] = nodes[n2];
6522     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
6523     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
6524       aNodes[iNode++] = *nIt;
6525     }
6526     for(i=1; i<nbn; i++) {
6527       SMDS_MeshElement* newElem =
6528         aMesh->AddFace(aNodes[i-1],aNodes[i],nodes[n3]);
6529       myLastCreatedElems.Append(newElem);
6530       if ( aShapeId && newElem )
6531         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6532     }
6533     // remove old quadratic face
6534     aMesh->RemoveElement(theFace);
6535   }
6536 }
6537
6538 //=======================================================================
6539 //function : UpdateVolumes
6540 //purpose  :
6541 //=======================================================================
6542 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode*        theBetweenNode1,
6543                                       const SMDS_MeshNode*        theBetweenNode2,
6544                                       list<const SMDS_MeshNode*>& theNodesToInsert)
6545 {
6546   myLastCreatedElems.Clear();
6547   myLastCreatedNodes.Clear();
6548
6549   SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator(SMDSAbs_Volume);
6550   while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
6551     const SMDS_MeshElement* elem = invElemIt->next();
6552
6553     // check, if current volume has link theBetweenNode1 - theBetweenNode2
6554     SMDS_VolumeTool aVolume (elem);
6555     if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
6556       continue;
6557
6558     // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
6559     int iface, nbFaces = aVolume.NbFaces();
6560     vector<const SMDS_MeshNode *> poly_nodes;
6561     vector<int> quantities (nbFaces);
6562
6563     for (iface = 0; iface < nbFaces; iface++) {
6564       int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
6565       // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
6566       const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
6567
6568       for (int inode = 0; inode < nbFaceNodes; inode++) {
6569         poly_nodes.push_back(faceNodes[inode]);
6570
6571         if (nbInserted == 0) {
6572           if (faceNodes[inode] == theBetweenNode1) {
6573             if (faceNodes[inode + 1] == theBetweenNode2) {
6574               nbInserted = theNodesToInsert.size();
6575
6576               // add nodes to insert
6577               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
6578               for (; nIt != theNodesToInsert.end(); nIt++) {
6579                 poly_nodes.push_back(*nIt);
6580               }
6581             }
6582           }
6583           else if (faceNodes[inode] == theBetweenNode2) {
6584             if (faceNodes[inode + 1] == theBetweenNode1) {
6585               nbInserted = theNodesToInsert.size();
6586
6587               // add nodes to insert in reversed order
6588               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
6589               nIt--;
6590               for (; nIt != theNodesToInsert.begin(); nIt--) {
6591                 poly_nodes.push_back(*nIt);
6592               }
6593               poly_nodes.push_back(*nIt);
6594             }
6595           }
6596           else {
6597           }
6598         }
6599       }
6600       quantities[iface] = nbFaceNodes + nbInserted;
6601     }
6602
6603     // Replace or update the volume
6604     SMESHDS_Mesh *aMesh = GetMeshDS();
6605
6606     if (elem->IsPoly()) {
6607       aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
6608
6609     }
6610     else {
6611       int aShapeId = FindShape( elem );
6612
6613       SMDS_MeshElement* newElem =
6614         aMesh->AddPolyhedralVolume(poly_nodes, quantities);
6615       myLastCreatedElems.Append(newElem);
6616       if (aShapeId && newElem)
6617         aMesh->SetMeshElementOnShape(newElem, aShapeId);
6618
6619       aMesh->RemoveElement(elem);
6620     }
6621   }
6622 }
6623
6624 //=======================================================================
6625 /*!
6626  * \brief Convert elements contained in a submesh to quadratic
6627  * \retval int - nb of checked elements
6628  */
6629 //=======================================================================
6630
6631 int SMESH_MeshEditor::convertElemToQuadratic(SMESHDS_SubMesh *   theSm,
6632                                              SMESH_MesherHelper& theHelper,
6633                                              const bool          theForce3d)
6634 {
6635   int nbElem = 0;
6636   if( !theSm ) return nbElem;
6637
6638   const bool notFromGroups = false;
6639   SMDS_ElemIteratorPtr ElemItr = theSm->GetElements();
6640   while(ElemItr->more())
6641   {
6642     nbElem++;
6643     const SMDS_MeshElement* elem = ElemItr->next();
6644     if( !elem || elem->IsQuadratic() ) continue;
6645
6646     int id = elem->GetID();
6647     int nbNodes = elem->NbNodes();
6648     vector<const SMDS_MeshNode *> aNds (nbNodes);
6649
6650     for(int i = 0; i < nbNodes; i++)
6651     {
6652       aNds[i] = elem->GetNode(i);
6653     }
6654     SMDSAbs_ElementType aType = elem->GetType();
6655
6656     GetMeshDS()->RemoveFreeElement(elem, theSm, notFromGroups);
6657
6658     const SMDS_MeshElement* NewElem = 0;
6659
6660     switch( aType )
6661     {
6662     case SMDSAbs_Edge :
6663     {
6664       NewElem = theHelper.AddEdge(aNds[0], aNds[1], id, theForce3d);
6665       break;
6666     }
6667     case SMDSAbs_Face :
6668     {
6669       switch(nbNodes)
6670       {
6671       case 3:
6672         NewElem = theHelper.AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6673         break;
6674       case 4:
6675         NewElem = theHelper.AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6676         break;
6677       default:
6678         continue;
6679       }
6680       break;
6681     }
6682     case SMDSAbs_Volume :
6683     {
6684       switch(nbNodes)
6685       {
6686       case 4:
6687         NewElem = theHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6688         break;
6689       case 6:
6690         NewElem = theHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], aNds[4], aNds[5], id, theForce3d);
6691         break;
6692       case 8:
6693         NewElem = theHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6694                                       aNds[4], aNds[5], aNds[6], aNds[7], id, theForce3d);
6695         break;
6696       default:
6697         continue;
6698       }
6699       break;
6700     }
6701     default :
6702       continue;
6703     }
6704     ReplaceElemInGroups( elem, NewElem, GetMeshDS());
6705     if( NewElem )
6706       theSm->AddElement( NewElem );
6707   }
6708   return nbElem;
6709 }
6710
6711 //=======================================================================
6712 //function : ConvertToQuadratic
6713 //purpose  :
6714 //=======================================================================
6715 void SMESH_MeshEditor::ConvertToQuadratic(const bool theForce3d)
6716 {
6717   SMESHDS_Mesh* meshDS = GetMeshDS();
6718
6719   SMESH_MesherHelper aHelper(*myMesh);
6720   aHelper.SetIsQuadratic( true );
6721   const bool notFromGroups = false;
6722
6723   int nbCheckedElems = 0;
6724   if ( myMesh->HasShapeToMesh() )
6725   {
6726     if ( SMESH_subMesh *aSubMesh = myMesh->GetSubMeshContaining(myMesh->GetShapeToMesh()))
6727     {
6728       SMESH_subMeshIteratorPtr smIt = aSubMesh->getDependsOnIterator(true,false);
6729       while ( smIt->more() ) {
6730         SMESH_subMesh* sm = smIt->next();
6731         if ( SMESHDS_SubMesh *smDS = sm->GetSubMeshDS() ) {
6732           aHelper.SetSubShape( sm->GetSubShape() );
6733           nbCheckedElems += convertElemToQuadratic(smDS, aHelper, theForce3d);
6734         }
6735       }
6736     }
6737   }
6738   int totalNbElems = meshDS->NbEdges() + meshDS->NbFaces() + meshDS->NbVolumes();
6739   if ( nbCheckedElems < totalNbElems ) // not all elements are in submeshes
6740   {
6741     SMESHDS_SubMesh *smDS = 0;
6742     SMDS_EdgeIteratorPtr aEdgeItr = meshDS->edgesIterator();
6743     while(aEdgeItr->more())
6744     {
6745       const SMDS_MeshEdge* edge = aEdgeItr->next();
6746       if(edge && !edge->IsQuadratic())
6747       {
6748         int id = edge->GetID();
6749         const SMDS_MeshNode* n1 = edge->GetNode(0);
6750         const SMDS_MeshNode* n2 = edge->GetNode(1);
6751
6752         meshDS->RemoveFreeElement(edge, smDS, notFromGroups);
6753
6754         const SMDS_MeshEdge* NewEdge = aHelper.AddEdge(n1, n2, id, theForce3d);
6755         ReplaceElemInGroups( edge, NewEdge, GetMeshDS());
6756       }
6757     }
6758     SMDS_FaceIteratorPtr aFaceItr = meshDS->facesIterator();
6759     while(aFaceItr->more())
6760     {
6761       const SMDS_MeshFace* face = aFaceItr->next();
6762       if(!face || face->IsQuadratic() ) continue;
6763
6764       int id = face->GetID();
6765       int nbNodes = face->NbNodes();
6766       vector<const SMDS_MeshNode *> aNds (nbNodes);
6767
6768       for(int i = 0; i < nbNodes; i++)
6769       {
6770         aNds[i] = face->GetNode(i);
6771       }
6772
6773       meshDS->RemoveFreeElement(face, smDS, notFromGroups);
6774
6775       SMDS_MeshFace * NewFace = 0;
6776       switch(nbNodes)
6777       {
6778       case 3:
6779         NewFace = aHelper.AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6780         break;
6781       case 4:
6782         NewFace = aHelper.AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6783         break;
6784       default:
6785         continue;
6786       }
6787       ReplaceElemInGroups( face, NewFace, GetMeshDS());
6788     }
6789     SMDS_VolumeIteratorPtr aVolumeItr = meshDS->volumesIterator();
6790     while(aVolumeItr->more())
6791     {
6792       const SMDS_MeshVolume* volume = aVolumeItr->next();
6793       if(!volume || volume->IsQuadratic() ) continue;
6794
6795       int id = volume->GetID();
6796       int nbNodes = volume->NbNodes();
6797       vector<const SMDS_MeshNode *> aNds (nbNodes);
6798
6799       for(int i = 0; i < nbNodes; i++)
6800       {
6801         aNds[i] = volume->GetNode(i);
6802       }
6803
6804       meshDS->RemoveFreeElement(volume, smDS, notFromGroups);
6805
6806       SMDS_MeshVolume * NewVolume = 0;
6807       switch(nbNodes)
6808       {
6809       case 4:
6810         NewVolume = aHelper.AddVolume(aNds[0], aNds[1], aNds[2],
6811                                       aNds[3], id, theForce3d );
6812         break;
6813       case 6:
6814         NewVolume = aHelper.AddVolume(aNds[0], aNds[1], aNds[2],
6815                                       aNds[3], aNds[4], aNds[5], id, theForce3d);
6816         break;
6817       case 8:
6818         NewVolume = aHelper.AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6819                                       aNds[4], aNds[5], aNds[6], aNds[7], id, theForce3d);
6820         break;
6821       default:
6822         continue;
6823       }
6824       ReplaceElemInGroups(volume, NewVolume, meshDS);
6825     }
6826   }
6827 }
6828
6829 //=======================================================================
6830 /*!
6831  * \brief Convert quadratic elements to linear ones and remove quadratic nodes
6832  * \retval int - nb of checked elements
6833  */
6834 //=======================================================================
6835
6836 int SMESH_MeshEditor::removeQuadElem(SMESHDS_SubMesh *    theSm,
6837                                      SMDS_ElemIteratorPtr theItr,
6838                                      const int            theShapeID)
6839 {
6840   int nbElem = 0;
6841   SMESHDS_Mesh* meshDS = GetMeshDS();
6842   const bool notFromGroups = false;
6843
6844   while( theItr->more() )
6845   {
6846     const SMDS_MeshElement* elem = theItr->next();
6847     nbElem++;
6848     if( elem && elem->IsQuadratic())
6849     {
6850       int id = elem->GetID();
6851       int nbNodes = elem->NbNodes();
6852       vector<const SMDS_MeshNode *> aNds, mediumNodes;
6853       aNds.reserve( nbNodes );
6854       mediumNodes.reserve( nbNodes );
6855
6856       for(int i = 0; i < nbNodes; i++)
6857       {
6858         const SMDS_MeshNode* n = elem->GetNode(i);
6859
6860         if( elem->IsMediumNode( n ) )
6861           mediumNodes.push_back( n );
6862         else
6863           aNds.push_back( n );
6864       }
6865       if( aNds.empty() ) continue;
6866       SMDSAbs_ElementType aType = elem->GetType();
6867
6868       //remove old quadratic element
6869       meshDS->RemoveFreeElement( elem, theSm, notFromGroups );
6870
6871       SMDS_MeshElement * NewElem = AddElement( aNds, aType, false, id );
6872       ReplaceElemInGroups(elem, NewElem, meshDS);
6873       if( theSm && NewElem )
6874         theSm->AddElement( NewElem );
6875
6876       // remove medium nodes
6877       vector<const SMDS_MeshNode*>::iterator nIt = mediumNodes.begin();
6878       for ( ; nIt != mediumNodes.end(); ++nIt ) {
6879         const SMDS_MeshNode* n = *nIt;
6880         if ( n->NbInverseElements() == 0 ) {
6881           if ( n->GetPosition()->GetShapeId() != theShapeID )
6882             meshDS->RemoveFreeNode( n, meshDS->MeshElements
6883                                     ( n->GetPosition()->GetShapeId() ));
6884           else
6885             meshDS->RemoveFreeNode( n, theSm );
6886         }
6887       }
6888     }
6889   }
6890   return nbElem;
6891 }
6892
6893 //=======================================================================
6894 //function : ConvertFromQuadratic
6895 //purpose  :
6896 //=======================================================================
6897 bool  SMESH_MeshEditor::ConvertFromQuadratic()
6898 {
6899   int nbCheckedElems = 0;
6900   if ( myMesh->HasShapeToMesh() )
6901   {
6902     if ( SMESH_subMesh *aSubMesh = myMesh->GetSubMeshContaining(myMesh->GetShapeToMesh()))
6903     {
6904       SMESH_subMeshIteratorPtr smIt = aSubMesh->getDependsOnIterator(true,false);
6905       while ( smIt->more() ) {
6906         SMESH_subMesh* sm = smIt->next();
6907         if ( SMESHDS_SubMesh *smDS = sm->GetSubMeshDS() )
6908           nbCheckedElems += removeQuadElem( smDS, smDS->GetElements(), sm->GetId() );
6909       }
6910     }
6911   }
6912   
6913   int totalNbElems =
6914     GetMeshDS()->NbEdges() + GetMeshDS()->NbFaces() + GetMeshDS()->NbVolumes();
6915   if ( nbCheckedElems < totalNbElems ) // not all elements are in submeshes
6916   {
6917     SMESHDS_SubMesh *aSM = 0;
6918     removeQuadElem( aSM, GetMeshDS()->elementsIterator(), 0 );
6919   }
6920
6921   return true;
6922 }
6923
6924 //=======================================================================
6925 //function : SewSideElements
6926 //purpose  :
6927 //=======================================================================
6928
6929 SMESH_MeshEditor::Sew_Error
6930   SMESH_MeshEditor::SewSideElements (TIDSortedElemSet&    theSide1,
6931                                      TIDSortedElemSet&    theSide2,
6932                                      const SMDS_MeshNode* theFirstNode1,
6933                                      const SMDS_MeshNode* theFirstNode2,
6934                                      const SMDS_MeshNode* theSecondNode1,
6935                                      const SMDS_MeshNode* theSecondNode2)
6936 {
6937   myLastCreatedElems.Clear();
6938   myLastCreatedNodes.Clear();
6939
6940   MESSAGE ("::::SewSideElements()");
6941   if ( theSide1.size() != theSide2.size() )
6942     return SEW_DIFF_NB_OF_ELEMENTS;
6943
6944   Sew_Error aResult = SEW_OK;
6945   // Algo:
6946   // 1. Build set of faces representing each side
6947   // 2. Find which nodes of the side 1 to merge with ones on the side 2
6948   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
6949
6950   // =======================================================================
6951   // 1. Build set of faces representing each side:
6952   // =======================================================================
6953   // a. build set of nodes belonging to faces
6954   // b. complete set of faces: find missing fices whose nodes are in set of nodes
6955   // c. create temporary faces representing side of volumes if correspondent
6956   //    face does not exist
6957
6958   SMESHDS_Mesh* aMesh = GetMeshDS();
6959   SMDS_Mesh aTmpFacesMesh;
6960   set<const SMDS_MeshElement*> faceSet1, faceSet2;
6961   set<const SMDS_MeshElement*> volSet1,  volSet2;
6962   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
6963   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
6964   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
6965   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
6966   TIDSortedElemSet * elemSetPtr[] = { &theSide1, &theSide2 };
6967   int iSide, iFace, iNode;
6968
6969   for ( iSide = 0; iSide < 2; iSide++ ) {
6970     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
6971     TIDSortedElemSet * elemSet = elemSetPtr[ iSide ];
6972     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
6973     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
6974     set<const SMDS_MeshElement*>::iterator vIt;
6975     TIDSortedElemSet::iterator eIt;
6976     set<const SMDS_MeshNode*>::iterator    nIt;
6977
6978     // check that given nodes belong to given elements
6979     const SMDS_MeshNode* n1 = ( iSide == 0 ) ? theFirstNode1 : theFirstNode2;
6980     const SMDS_MeshNode* n2 = ( iSide == 0 ) ? theSecondNode1 : theSecondNode2;
6981     int firstIndex = -1, secondIndex = -1;
6982     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
6983       const SMDS_MeshElement* elem = *eIt;
6984       if ( firstIndex  < 0 ) firstIndex  = elem->GetNodeIndex( n1 );
6985       if ( secondIndex < 0 ) secondIndex = elem->GetNodeIndex( n2 );
6986       if ( firstIndex > -1 && secondIndex > -1 ) break;
6987     }
6988     if ( firstIndex < 0 || secondIndex < 0 ) {
6989       // we can simply return until temporary faces created
6990       return (iSide == 0 ) ? SEW_BAD_SIDE1_NODES : SEW_BAD_SIDE2_NODES;
6991     }
6992
6993     // -----------------------------------------------------------
6994     // 1a. Collect nodes of existing faces
6995     //     and build set of face nodes in order to detect missing
6996     //     faces corresponing to sides of volumes
6997     // -----------------------------------------------------------
6998
6999     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
7000
7001     // loop on the given element of a side
7002     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
7003       //const SMDS_MeshElement* elem = *eIt;
7004       const SMDS_MeshElement* elem = *eIt;
7005       if ( elem->GetType() == SMDSAbs_Face ) {
7006         faceSet->insert( elem );
7007         set <const SMDS_MeshNode*> faceNodeSet;
7008         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
7009         while ( nodeIt->more() ) {
7010           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7011           nodeSet->insert( n );
7012           faceNodeSet.insert( n );
7013         }
7014         setOfFaceNodeSet.insert( faceNodeSet );
7015       }
7016       else if ( elem->GetType() == SMDSAbs_Volume )
7017         volSet->insert( elem );
7018     }
7019     // ------------------------------------------------------------------------------
7020     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
7021     // ------------------------------------------------------------------------------
7022
7023     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
7024       SMDS_ElemIteratorPtr fIt = (*nIt)->GetInverseElementIterator(SMDSAbs_Face);
7025       while ( fIt->more() ) { // loop on faces sharing a node
7026         const SMDS_MeshElement* f = fIt->next();
7027         if ( faceSet->find( f ) == faceSet->end() ) {
7028           // check if all nodes are in nodeSet and
7029           // complete setOfFaceNodeSet if they are
7030           set <const SMDS_MeshNode*> faceNodeSet;
7031           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
7032           bool allInSet = true;
7033           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
7034             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7035             if ( nodeSet->find( n ) == nodeSet->end() )
7036               allInSet = false;
7037             else
7038               faceNodeSet.insert( n );
7039           }
7040           if ( allInSet ) {
7041             faceSet->insert( f );
7042             setOfFaceNodeSet.insert( faceNodeSet );
7043           }
7044         }
7045       }
7046     }
7047
7048     // -------------------------------------------------------------------------
7049     // 1c. Create temporary faces representing sides of volumes if correspondent
7050     //     face does not exist
7051     // -------------------------------------------------------------------------
7052
7053     if ( !volSet->empty() ) {
7054       //int nodeSetSize = nodeSet->size();
7055
7056       // loop on given volumes
7057       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
7058         SMDS_VolumeTool vol (*vIt);
7059         // loop on volume faces: find free faces
7060         // --------------------------------------
7061         list<const SMDS_MeshElement* > freeFaceList;
7062         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
7063           if ( !vol.IsFreeFace( iFace ))
7064             continue;
7065           // check if there is already a face with same nodes in a face set
7066           const SMDS_MeshElement* aFreeFace = 0;
7067           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
7068           int nbNodes = vol.NbFaceNodes( iFace );
7069           set <const SMDS_MeshNode*> faceNodeSet;
7070           vol.GetFaceNodes( iFace, faceNodeSet );
7071           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
7072           if ( isNewFace ) {
7073             // no such a face is given but it still can exist, check it
7074             if ( nbNodes == 3 ) {
7075               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
7076             }
7077             else if ( nbNodes == 4 ) {
7078               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
7079             }
7080             else {
7081               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
7082               aFreeFace = aMesh->FindFace(poly_nodes);
7083             }
7084           }
7085           if ( !aFreeFace ) {
7086             // create a temporary face
7087             if ( nbNodes == 3 ) {
7088               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
7089             }
7090             else if ( nbNodes == 4 ) {
7091               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
7092             }
7093             else {
7094               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
7095               aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
7096             }
7097           }
7098           if ( aFreeFace )
7099             freeFaceList.push_back( aFreeFace );
7100
7101         } // loop on faces of a volume
7102
7103         // choose one of several free faces
7104         // --------------------------------------
7105         if ( freeFaceList.size() > 1 ) {
7106           // choose a face having max nb of nodes shared by other elems of a side
7107           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
7108           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
7109           while ( fIt != freeFaceList.end() ) { // loop on free faces
7110             int nbSharedNodes = 0;
7111             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
7112             while ( nodeIt->more() ) { // loop on free face nodes
7113               const SMDS_MeshNode* n =
7114                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7115               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
7116               while ( invElemIt->more() ) {
7117                 const SMDS_MeshElement* e = invElemIt->next();
7118                 if ( faceSet->find( e ) != faceSet->end() )
7119                   nbSharedNodes++;
7120                 if ( elemSet->find( e ) != elemSet->end() )
7121                   nbSharedNodes++;
7122               }
7123             }
7124             if ( nbSharedNodes >= maxNbNodes ) {
7125               maxNbNodes = nbSharedNodes;
7126               fIt++;
7127             }
7128             else
7129               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
7130           }
7131           if ( freeFaceList.size() > 1 )
7132           {
7133             // could not choose one face, use another way
7134             // choose a face most close to the bary center of the opposite side
7135             gp_XYZ aBC( 0., 0., 0. );
7136             set <const SMDS_MeshNode*> addedNodes;
7137             TIDSortedElemSet * elemSet2 = elemSetPtr[ 1 - iSide ];
7138             eIt = elemSet2->begin();
7139             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
7140               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
7141               while ( nodeIt->more() ) { // loop on free face nodes
7142                 const SMDS_MeshNode* n =
7143                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7144                 if ( addedNodes.insert( n ).second )
7145                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
7146               }
7147             }
7148             aBC /= addedNodes.size();
7149             double minDist = DBL_MAX;
7150             fIt = freeFaceList.begin();
7151             while ( fIt != freeFaceList.end() ) { // loop on free faces
7152               double dist = 0;
7153               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
7154               while ( nodeIt->more() ) { // loop on free face nodes
7155                 const SMDS_MeshNode* n =
7156                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7157                 gp_XYZ p( n->X(),n->Y(),n->Z() );
7158                 dist += ( aBC - p ).SquareModulus();
7159               }
7160               if ( dist < minDist ) {
7161                 minDist = dist;
7162                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
7163               }
7164               else
7165                 fIt = freeFaceList.erase( fIt++ );
7166             }
7167           }
7168         } // choose one of several free faces of a volume
7169
7170         if ( freeFaceList.size() == 1 ) {
7171           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
7172           faceSet->insert( aFreeFace );
7173           // complete a node set with nodes of a found free face
7174 //           for ( iNode = 0; iNode < ; iNode++ )
7175 //             nodeSet->insert( fNodes[ iNode ] );
7176         }
7177
7178       } // loop on volumes of a side
7179
7180 //       // complete a set of faces if new nodes in a nodeSet appeared
7181 //       // ----------------------------------------------------------
7182 //       if ( nodeSetSize != nodeSet->size() ) {
7183 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
7184 //           SMDS_ElemIteratorPtr fIt = (*nIt)->GetInverseElementIterator(SMDSAbs_Face);
7185 //           while ( fIt->more() ) { // loop on faces sharing a node
7186 //             const SMDS_MeshElement* f = fIt->next();
7187 //             if ( faceSet->find( f ) == faceSet->end() ) {
7188 //               // check if all nodes are in nodeSet and
7189 //               // complete setOfFaceNodeSet if they are
7190 //               set <const SMDS_MeshNode*> faceNodeSet;
7191 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
7192 //               bool allInSet = true;
7193 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
7194 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
7195 //                 if ( nodeSet->find( n ) == nodeSet->end() )
7196 //                   allInSet = false;
7197 //                 else
7198 //                   faceNodeSet.insert( n );
7199 //               }
7200 //               if ( allInSet ) {
7201 //                 faceSet->insert( f );
7202 //                 setOfFaceNodeSet.insert( faceNodeSet );
7203 //               }
7204 //             }
7205 //           }
7206 //         }
7207 //       }
7208     } // Create temporary faces, if there are volumes given
7209   } // loop on sides
7210
7211   if ( faceSet1.size() != faceSet2.size() ) {
7212     // delete temporary faces: they are in reverseElements of actual nodes
7213     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
7214     while ( tmpFaceIt->more() )
7215       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
7216     MESSAGE("Diff nb of faces");
7217     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7218   }
7219
7220   // ============================================================
7221   // 2. Find nodes to merge:
7222   //              bind a node to remove to a node to put instead
7223   // ============================================================
7224
7225   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
7226   if ( theFirstNode1 != theFirstNode2 )
7227     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
7228   if ( theSecondNode1 != theSecondNode2 )
7229     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
7230
7231   LinkID_Gen aLinkID_Gen( GetMeshDS() );
7232   set< long > linkIdSet; // links to process
7233   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
7234
7235   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > NLink;
7236   list< NLink > linkList[2];
7237   linkList[0].push_back( NLink( theFirstNode1, theSecondNode1 ));
7238   linkList[1].push_back( NLink( theFirstNode2, theSecondNode2 ));
7239   // loop on links in linkList; find faces by links and append links
7240   // of the found faces to linkList
7241   list< NLink >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
7242   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ ) {
7243     NLink link[] = { *linkIt[0], *linkIt[1] };
7244     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
7245     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
7246       continue;
7247
7248     // by links, find faces in the face sets,
7249     // and find indices of link nodes in the found faces;
7250     // in a face set, there is only one or no face sharing a link
7251     // ---------------------------------------------------------------
7252
7253     const SMDS_MeshElement* face[] = { 0, 0 };
7254     //const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
7255     vector<const SMDS_MeshNode*> fnodes1(9);
7256     vector<const SMDS_MeshNode*> fnodes2(9);
7257     //const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
7258     vector<const SMDS_MeshNode*> notLinkNodes1(6);
7259     vector<const SMDS_MeshNode*> notLinkNodes2(6);
7260     int iLinkNode[2][2];
7261     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
7262       const SMDS_MeshNode* n1 = link[iSide].first;
7263       const SMDS_MeshNode* n2 = link[iSide].second;
7264       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
7265       set< const SMDS_MeshElement* > fMap;
7266       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
7267         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
7268         SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
7269         while ( fIt->more() ) { // loop on faces sharing a node
7270           const SMDS_MeshElement* f = fIt->next();
7271           if (faceSet->find( f ) != faceSet->end() && // f is in face set
7272               ! fMap.insert( f ).second ) // f encounters twice
7273           {
7274             if ( face[ iSide ] ) {
7275               MESSAGE( "2 faces per link " );
7276               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
7277               break;
7278             }
7279             face[ iSide ] = f;
7280             faceSet->erase( f );
7281             // get face nodes and find ones of a link
7282             iNode = 0;
7283             int nbl = -1;
7284             if(f->IsPoly()) {
7285               if(iSide==0) {
7286                 fnodes1.resize(f->NbNodes()+1);
7287                 notLinkNodes1.resize(f->NbNodes()-2);
7288               }
7289               else {
7290                 fnodes2.resize(f->NbNodes()+1);
7291                 notLinkNodes2.resize(f->NbNodes()-2);
7292               }
7293             }
7294             if(!f->IsQuadratic()) {
7295               SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7296               while ( nIt->more() ) {
7297                 const SMDS_MeshNode* n =
7298                   static_cast<const SMDS_MeshNode*>( nIt->next() );
7299                 if ( n == n1 ) {
7300                   iLinkNode[ iSide ][ 0 ] = iNode;
7301                 }
7302                 else if ( n == n2 ) {
7303                   iLinkNode[ iSide ][ 1 ] = iNode;
7304                 }
7305                 //else if ( notLinkNodes[ iSide ][ 0 ] )
7306                 //  notLinkNodes[ iSide ][ 1 ] = n;
7307                 //else
7308                 //  notLinkNodes[ iSide ][ 0 ] = n;
7309                 else {
7310                   nbl++;
7311                   if(iSide==0)
7312                     notLinkNodes1[nbl] = n;
7313                     //notLinkNodes1.push_back(n);
7314                   else
7315                     notLinkNodes2[nbl] = n;
7316                     //notLinkNodes2.push_back(n);
7317                 }
7318                 //faceNodes[ iSide ][ iNode++ ] = n;
7319                 if(iSide==0) {
7320                   fnodes1[iNode++] = n;
7321                 }
7322                 else {
7323                   fnodes2[iNode++] = n;
7324                 }
7325               }
7326             }
7327             else { // f->IsQuadratic()
7328               const SMDS_QuadraticFaceOfNodes* F =
7329                 static_cast<const SMDS_QuadraticFaceOfNodes*>(f);
7330               // use special nodes iterator
7331               SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
7332               while ( anIter->more() ) {
7333                 const SMDS_MeshNode* n =
7334                   static_cast<const SMDS_MeshNode*>( anIter->next() );
7335                 if ( n == n1 ) {
7336                   iLinkNode[ iSide ][ 0 ] = iNode;
7337                 }
7338                 else if ( n == n2 ) {
7339                   iLinkNode[ iSide ][ 1 ] = iNode;
7340                 }
7341                 else {
7342                   nbl++;
7343                   if(iSide==0) {
7344                     notLinkNodes1[nbl] = n;
7345                   }
7346                   else {
7347                     notLinkNodes2[nbl] = n;
7348                   }
7349                 }
7350                 if(iSide==0) {
7351                   fnodes1[iNode++] = n;
7352                 }
7353                 else {
7354                   fnodes2[iNode++] = n;
7355                 }
7356               }
7357             }
7358             //faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
7359             if(iSide==0) {
7360               fnodes1[iNode] = fnodes1[0];
7361             }
7362             else {
7363               fnodes2[iNode] = fnodes1[0];
7364             }
7365           }
7366         }
7367       }
7368     }
7369
7370     // check similarity of elements of the sides
7371     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
7372       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
7373       if ( nReplaceMap.size() == 2 ) { // faces on input nodes not found
7374         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7375       }
7376       else {
7377         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7378       }
7379       break; // do not return because it s necessary to remove tmp faces
7380     }
7381
7382     // set nodes to merge
7383     // -------------------
7384
7385     if ( face[0] && face[1] )  {
7386       int nbNodes = face[0]->NbNodes();
7387       if ( nbNodes != face[1]->NbNodes() ) {
7388         MESSAGE("Diff nb of face nodes");
7389         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7390         break; // do not return because it s necessary to remove tmp faces
7391       }
7392       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
7393       if ( nbNodes == 3 ) {
7394         //nReplaceMap.insert( TNodeNodeMap::value_type
7395         //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
7396         nReplaceMap.insert( TNodeNodeMap::value_type
7397                            ( notLinkNodes1[0], notLinkNodes2[0] ));
7398       }
7399       else {
7400         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
7401           // analyse link orientation in faces
7402           int i1 = iLinkNode[ iSide ][ 0 ];
7403           int i2 = iLinkNode[ iSide ][ 1 ];
7404           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
7405           // if notLinkNodes are the first and the last ones, then
7406           // their order does not correspond to the link orientation
7407           if (( i1 == 1 && i2 == 2 ) ||
7408               ( i1 == 2 && i2 == 1 ))
7409             reverse[ iSide ] = !reverse[ iSide ];
7410         }
7411         if ( reverse[0] == reverse[1] ) {
7412           //nReplaceMap.insert( TNodeNodeMap::value_type
7413           //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
7414           //nReplaceMap.insert( TNodeNodeMap::value_type
7415           //                   ( notLinkNodes[0][1], notLinkNodes[1][1] ));
7416           for(int nn=0; nn<nbNodes-2; nn++) {
7417             nReplaceMap.insert( TNodeNodeMap::value_type
7418                              ( notLinkNodes1[nn], notLinkNodes2[nn] ));
7419           }
7420         }
7421         else {
7422           //nReplaceMap.insert( TNodeNodeMap::value_type
7423           //                   ( notLinkNodes[0][0], notLinkNodes[1][1] ));
7424           //nReplaceMap.insert( TNodeNodeMap::value_type
7425           //                   ( notLinkNodes[0][1], notLinkNodes[1][0] ));
7426           for(int nn=0; nn<nbNodes-2; nn++) {
7427             nReplaceMap.insert( TNodeNodeMap::value_type
7428                              ( notLinkNodes1[nn], notLinkNodes2[nbNodes-3-nn] ));
7429           }
7430         }
7431       }
7432
7433       // add other links of the faces to linkList
7434       // -----------------------------------------
7435
7436       //const SMDS_MeshNode** nodes = faceNodes[ 0 ];
7437       for ( iNode = 0; iNode < nbNodes; iNode++ )  {
7438         //linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
7439         linkID = aLinkID_Gen.GetLinkID( fnodes1[iNode], fnodes1[iNode+1] );
7440         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
7441         if ( !iter_isnew.second ) { // already in a set: no need to process
7442           linkIdSet.erase( iter_isnew.first );
7443         }
7444         else // new in set == encountered for the first time: add
7445         {
7446           //const SMDS_MeshNode* n1 = nodes[ iNode ];
7447           //const SMDS_MeshNode* n2 = nodes[ iNode + 1];
7448           const SMDS_MeshNode* n1 = fnodes1[ iNode ];
7449           const SMDS_MeshNode* n2 = fnodes1[ iNode + 1];
7450           linkList[0].push_back ( NLink( n1, n2 ));
7451           linkList[1].push_back ( NLink( nReplaceMap[n1], nReplaceMap[n2] ));
7452         }
7453       }
7454     } // 2 faces found
7455   } // loop on link lists
7456
7457   if ( aResult == SEW_OK &&
7458       ( linkIt[0] != linkList[0].end() ||
7459        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
7460     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
7461             " " << (faceSetPtr[1]->empty()));
7462     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7463   }
7464
7465   // ====================================================================
7466   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
7467   // ====================================================================
7468
7469   // delete temporary faces: they are in reverseElements of actual nodes
7470   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
7471   while ( tmpFaceIt->more() )
7472     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
7473
7474   if ( aResult != SEW_OK)
7475     return aResult;
7476
7477   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
7478   // loop on nodes replacement map
7479   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
7480   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
7481     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second ) {
7482       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
7483       nodeIDsToRemove.push_back( nToRemove->GetID() );
7484       // loop on elements sharing nToRemove
7485       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
7486       while ( invElemIt->more() ) {
7487         const SMDS_MeshElement* e = invElemIt->next();
7488         // get a new suite of nodes: make replacement
7489         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
7490         vector< const SMDS_MeshNode*> nodes( nbNodes );
7491         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7492         while ( nIt->more() ) {
7493           const SMDS_MeshNode* n =
7494             static_cast<const SMDS_MeshNode*>( nIt->next() );
7495           nnIt = nReplaceMap.find( n );
7496           if ( nnIt != nReplaceMap.end() ) {
7497             nbReplaced++;
7498             n = (*nnIt).second;
7499           }
7500           nodes[ i++ ] = n;
7501         }
7502         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
7503         //         elemIDsToRemove.push_back( e->GetID() );
7504         //       else
7505         if ( nbReplaced )
7506           aMesh->ChangeElementNodes( e, & nodes[0], nbNodes );
7507       }
7508     }
7509
7510   Remove( nodeIDsToRemove, true );
7511
7512   return aResult;
7513 }
7514
7515 //================================================================================
7516   /*!
7517    * \brief Find corresponding nodes in two sets of faces
7518     * \param theSide1 - first face set
7519     * \param theSide2 - second first face
7520     * \param theFirstNode1 - a boundary node of set 1
7521     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
7522     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
7523     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
7524     * \param nReplaceMap - output map of corresponding nodes
7525     * \retval bool  - is a success or not
7526    */
7527 //================================================================================
7528
7529 #ifdef _DEBUG_
7530 //#define DEBUG_MATCHING_NODES
7531 #endif
7532
7533 SMESH_MeshEditor::Sew_Error
7534 SMESH_MeshEditor::FindMatchingNodes(set<const SMDS_MeshElement*>& theSide1,
7535                                     set<const SMDS_MeshElement*>& theSide2,
7536                                     const SMDS_MeshNode*          theFirstNode1,
7537                                     const SMDS_MeshNode*          theFirstNode2,
7538                                     const SMDS_MeshNode*          theSecondNode1,
7539                                     const SMDS_MeshNode*          theSecondNode2,
7540                                     TNodeNodeMap &                nReplaceMap)
7541 {
7542   set<const SMDS_MeshElement*> * faceSetPtr[] = { &theSide1, &theSide2 };
7543
7544   nReplaceMap.clear();
7545   if ( theFirstNode1 != theFirstNode2 )
7546     nReplaceMap.insert( make_pair( theFirstNode1, theFirstNode2 ));
7547   if ( theSecondNode1 != theSecondNode2 )
7548     nReplaceMap.insert( make_pair( theSecondNode1, theSecondNode2 ));
7549
7550   set< TLink > linkSet; // set of nodes where order of nodes is ignored
7551   linkSet.insert( TLink( theFirstNode1, theSecondNode1 ));
7552
7553   list< NLink > linkList[2];
7554   linkList[0].push_back( NLink( theFirstNode1, theSecondNode1 ));
7555   linkList[1].push_back( NLink( theFirstNode2, theSecondNode2 ));
7556
7557   // loop on links in linkList; find faces by links and append links
7558   // of the found faces to linkList
7559   list< NLink >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
7560   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ ) {
7561     NLink link[] = { *linkIt[0], *linkIt[1] };
7562     if ( linkSet.find( link[0] ) == linkSet.end() )
7563       continue;
7564
7565     // by links, find faces in the face sets,
7566     // and find indices of link nodes in the found faces;
7567     // in a face set, there is only one or no face sharing a link
7568     // ---------------------------------------------------------------
7569
7570     const SMDS_MeshElement* face[] = { 0, 0 };
7571     list<const SMDS_MeshNode*> notLinkNodes[2];
7572     //bool reverse[] = { false, false }; // order of notLinkNodes
7573     int nbNodes[2];
7574     for ( int iSide = 0; iSide < 2; iSide++ ) // loop on 2 sides
7575     {
7576       const SMDS_MeshNode* n1 = link[iSide].first;
7577       const SMDS_MeshNode* n2 = link[iSide].second;
7578       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
7579       set< const SMDS_MeshElement* > facesOfNode1;
7580       for ( int iNode = 0; iNode < 2; iNode++ ) // loop on 2 nodes of a link
7581       {
7582         // during a loop of the first node, we find all faces around n1,
7583         // during a loop of the second node, we find one face sharing both n1 and n2
7584         const SMDS_MeshNode* n = iNode ? n1 : n2; // a node of a link
7585         SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
7586         while ( fIt->more() ) { // loop on faces sharing a node
7587           const SMDS_MeshElement* f = fIt->next();
7588           if (faceSet->find( f ) != faceSet->end() && // f is in face set
7589               ! facesOfNode1.insert( f ).second ) // f encounters twice
7590           {
7591             if ( face[ iSide ] ) {
7592               MESSAGE( "2 faces per link " );
7593               return ( iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7594             }
7595             face[ iSide ] = f;
7596             faceSet->erase( f );
7597
7598             // get not link nodes
7599             int nbN = f->NbNodes();
7600             if ( f->IsQuadratic() )
7601               nbN /= 2;
7602             nbNodes[ iSide ] = nbN;
7603             list< const SMDS_MeshNode* > & nodes = notLinkNodes[ iSide ];
7604             int i1 = f->GetNodeIndex( n1 );
7605             int i2 = f->GetNodeIndex( n2 );
7606             int iEnd = nbN, iBeg = -1, iDelta = 1;
7607             bool reverse = ( Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1 );
7608             if ( reverse ) {
7609               std::swap( iEnd, iBeg ); iDelta = -1;
7610             }
7611             int i = i2;
7612             while ( true ) {
7613               i += iDelta;
7614               if ( i == iEnd ) i = iBeg + iDelta;
7615               if ( i == i1 ) break;
7616               nodes.push_back ( f->GetNode( i ) );
7617             }
7618           }
7619         }
7620       }
7621     }
7622     // check similarity of elements of the sides
7623     if (( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
7624       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
7625       if ( nReplaceMap.size() == 2 ) { // faces on input nodes not found
7626         return ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7627       }
7628       else {
7629         return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7630       }
7631     }
7632
7633     // set nodes to merge
7634     // -------------------
7635
7636     if ( face[0] && face[1] )  {
7637       if ( nbNodes[0] != nbNodes[1] ) {
7638         MESSAGE("Diff nb of face nodes");
7639         return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7640       }
7641 #ifdef DEBUG_MATCHING_NODES
7642       MESSAGE ( " Link 1: " << link[0].first->GetID() <<" "<< link[0].second->GetID()
7643              << " F 1: " << face[0] << "| Link 2: " << link[1].first->GetID() <<" "
7644              << link[1].second->GetID() << " F 2: " << face[1] << " | Bind: " ) ;
7645 #endif
7646       int nbN = nbNodes[0];
7647       {
7648         list<const SMDS_MeshNode*>::iterator n1 = notLinkNodes[0].begin();
7649         list<const SMDS_MeshNode*>::iterator n2 = notLinkNodes[1].begin();
7650         for ( int i = 0 ; i < nbN - 2; ++i ) {
7651 #ifdef DEBUG_MATCHING_NODES
7652           MESSAGE ( (*n1)->GetID() << " to " << (*n2)->GetID() );
7653 #endif
7654           nReplaceMap.insert( make_pair( *(n1++), *(n2++) ));
7655         }
7656       }
7657
7658       // add other links of the face 1 to linkList
7659       // -----------------------------------------
7660
7661       const SMDS_MeshElement* f0 = face[0];
7662       const SMDS_MeshNode* n1 = f0->GetNode( nbN - 1 );
7663       for ( int i = 0; i < nbN; i++ )
7664       {
7665         const SMDS_MeshNode* n2 = f0->GetNode( i );
7666         pair< set< TLink >::iterator, bool > iter_isnew =
7667           linkSet.insert( TLink( n1, n2 ));
7668         if ( !iter_isnew.second ) { // already in a set: no need to process
7669           linkSet.erase( iter_isnew.first );
7670         }
7671         else // new in set == encountered for the first time: add
7672         {
7673 #ifdef DEBUG_MATCHING_NODES
7674           MESSAGE ( "Add link 1: " << n1->GetID() << " " << n2->GetID() << " "
7675           << " | link 2: " << nReplaceMap[n1]->GetID() << " " << nReplaceMap[n2]->GetID() << " " );
7676 #endif
7677           linkList[0].push_back ( NLink( n1, n2 ));
7678           linkList[1].push_back ( NLink( nReplaceMap[n1], nReplaceMap[n2] ));
7679         }
7680         n1 = n2;
7681       }
7682     } // 2 faces found
7683   } // loop on link lists
7684
7685   return SEW_OK;
7686 }