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