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