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