Salome HOME
Join modifications from branch BR_DEBUG_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.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 // File      : SMESH_MeshEditor.cxx
25 // Created   : Mon Apr 12 16:10:22 2004
26 // Author    : Edward AGAPOV (eap)
27
28
29 #include "SMESH_MeshEditor.hxx"
30
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
37 #include "SMDS_QuadraticFaceOfNodes.hxx"
38
39 #include "SMESHDS_Group.hxx"
40 #include "SMESHDS_Mesh.hxx"
41
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_ControlsDef.hxx"
44 #include "SMESH_MesherHelper.hxx"
45
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 = 0;
2942     SMDSAbs_ElementType highType = SMDSAbs_Edge; // count most complex elements only
2943     while ( eIt->more() && nbInitElems < 2 ) {
2944       el = eIt->next();
2945       SMDSAbs_ElementType type = el->GetType();
2946       if ( type == SMDSAbs_Volume || type < highType ) continue;
2947       if ( type > highType ) {
2948         nbInitElems = 0;
2949         highType = type;
2950       }
2951       if ( elemSet.find(el->GetID()) != elemSet.end() )
2952         nbInitElems++;
2953     }
2954     if ( nbInitElems < 2 ) {
2955       bool NotCreateEdge = el && el->IsQuadratic() && el->IsMediumNode(node);
2956       if(!NotCreateEdge) {
2957         vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2958         list<const SMDS_MeshElement*> newEdges;
2959         sweepElement( aMesh, node, newNodesItVec, newEdges, nbSteps, myLastCreatedElems );
2960       }
2961     }
2962   }
2963
2964   // Make a ceiling for each element ie an equal element of last new nodes.
2965   // Find free links of faces - make edges and sweep them into faces.
2966
2967   TElemOfElemListMap::iterator   itElem      = newElemsMap.begin();
2968   TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2969   for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ ) {
2970     const SMDS_MeshElement* elem = itElem->first;
2971     vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2972
2973     if ( elem->GetType() == SMDSAbs_Edge ) {
2974       // create a ceiling edge
2975       if (!elem->IsQuadratic()) {
2976         if ( !aMesh->FindEdge( vecNewNodes[ 0 ]->second.back(),
2977                                vecNewNodes[ 1 ]->second.back()))
2978           myLastCreatedElems.Append(aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2979                                                    vecNewNodes[ 1 ]->second.back()));
2980       }
2981       else {
2982         if ( !aMesh->FindEdge( vecNewNodes[ 0 ]->second.back(),
2983                                vecNewNodes[ 1 ]->second.back(),
2984                                vecNewNodes[ 2 ]->second.back()))
2985           myLastCreatedElems.Append(aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2986                                                    vecNewNodes[ 1 ]->second.back(),
2987                                                    vecNewNodes[ 2 ]->second.back()));
2988       }
2989     }
2990     if ( elem->GetType() != SMDSAbs_Face )
2991       continue;
2992
2993     if(itElem->second.size()==0) continue;
2994
2995     bool hasFreeLinks = false;
2996
2997     map<int,const SMDS_MeshElement*> avoidSet;
2998     avoidSet.insert( make_pair(elem->GetID(),elem) );
2999
3000     set<const SMDS_MeshNode*> aFaceLastNodes;
3001     int iNode, nbNodes = vecNewNodes.size();
3002     if(!elem->IsQuadratic()) {
3003       // loop on the face nodes
3004       for ( iNode = 0; iNode < nbNodes; iNode++ ) {
3005         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3006         // look for free links of the face
3007         int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
3008         const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
3009         const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
3010         // check if a link is free
3011         if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet )) {
3012           hasFreeLinks = true;
3013           // make an edge and a ceiling for a new edge
3014           if ( !aMesh->FindEdge( n1, n2 )) {
3015             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2 ));
3016           }
3017           n1 = vecNewNodes[ iNode ]->second.back();
3018           n2 = vecNewNodes[ iNext ]->second.back();
3019           if ( !aMesh->FindEdge( n1, n2 )) {
3020             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2 ));
3021           }
3022         }
3023       }
3024     }
3025     else { // elem is quadratic face
3026       int nbn = nbNodes/2;
3027       for ( iNode = 0; iNode < nbn; iNode++ ) {
3028         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3029         int iNext = ( iNode + 1 == nbn ) ? 0 : iNode + 1;
3030         const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
3031         const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
3032         // check if a link is free
3033         if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet )) {
3034           hasFreeLinks = true;
3035           // make an edge and a ceiling for a new edge
3036           // find medium node
3037           const SMDS_MeshNode* n3 = vecNewNodes[ iNode+nbn ]->first;
3038           if ( !aMesh->FindEdge( n1, n2, n3 )) {
3039             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2, n3 ));
3040           }
3041           n1 = vecNewNodes[ iNode ]->second.back();
3042           n2 = vecNewNodes[ iNext ]->second.back();
3043           n3 = vecNewNodes[ iNode+nbn ]->second.back();
3044           if ( !aMesh->FindEdge( n1, n2, n3 )) {
3045             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2, n3 ));
3046           }
3047         }
3048       }
3049       for ( iNode = nbn; iNode < 2*nbn; iNode++ ) {
3050         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3051       }
3052     }
3053
3054     // sweep free links into faces
3055
3056     if ( hasFreeLinks )  {
3057       list<const SMDS_MeshElement*> & newVolumes = itElem->second;
3058       int iStep; //, nbSteps = vecNewNodes[0]->second.size();
3059       int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
3060
3061       set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
3062       for ( iNode = 0; iNode < nbNodes; iNode++ )
3063         initNodeSet.insert( vecNewNodes[ iNode ]->first );
3064
3065       for ( volNb = 0; volNb < nbVolumesByStep; volNb++ ) {
3066         list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
3067         iVol = 0;
3068         while ( iVol++ < volNb ) v++;
3069         // find indices of free faces of a volume
3070         list< int > fInd;
3071         SMDS_VolumeTool vTool( *v );
3072         int iF, nbF = vTool.NbFaces();
3073         for ( iF = 0; iF < nbF; iF ++ ) {
3074           if (vTool.IsFreeFace( iF ) &&
3075               vTool.GetFaceNodes( iF, faceNodeSet ) &&
3076               initNodeSet != faceNodeSet) // except an initial face
3077             fInd.push_back( iF );
3078         }
3079         if ( fInd.empty() )
3080           continue;
3081
3082         // create faces for all steps
3083         // if such a face has been already created by sweep of edge, assure that its orientation is OK
3084         for ( iStep = 0; iStep < nbSteps; iStep++ )  {
3085           vTool.Set( *v );
3086           vTool.SetExternalNormal();
3087           list< int >::iterator ind = fInd.begin();
3088           for ( ; ind != fInd.end(); ind++ ) {
3089             const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
3090             int nbn = vTool.NbFaceNodes( *ind );
3091             switch ( nbn ) {
3092             case 3: { ///// triangle
3093               const SMDS_MeshFace * f = aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]);
3094               if ( !f )
3095                 myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
3096               else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3097                 aMesh->ChangeElementNodes( f, nodes, nbn );
3098               break;
3099             }
3100             case 4: { ///// quadrangle
3101               const SMDS_MeshFace * f = aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]);
3102               if ( !f )
3103                 myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ));
3104               else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3105                 aMesh->ChangeElementNodes( f, nodes, nbn );
3106               break;
3107             }
3108             default:
3109               if( (*v)->IsQuadratic() ) {
3110                 if(nbn==6) { /////// quadratic triangle
3111                   const SMDS_MeshFace * f = aMesh->FindFace( nodes[0], nodes[2], nodes[4],
3112                                                              nodes[1], nodes[3], nodes[5] );
3113                   if ( !f )
3114                     myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4],
3115                                                              nodes[1], nodes[3], nodes[5]));
3116                   else if ( nodes[ 2 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3117                     aMesh->ChangeElementNodes( f, nodes, nbn );
3118                 }
3119                 else {       /////// quadratic quadrangle
3120                   const SMDS_MeshFace * f = aMesh->FindFace( nodes[0], nodes[2], nodes[4], nodes[6],
3121                                                              nodes[1], nodes[3], nodes[5], nodes[7] );
3122                   if ( !f )
3123                     myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4], nodes[6],
3124                                                              nodes[1], nodes[3], nodes[5], nodes[7]));
3125                   else if ( nodes[ 2 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3126                     aMesh->ChangeElementNodes( f, nodes, nbn );
3127                 }
3128               }
3129               else { //////// polygon
3130                 vector<const SMDS_MeshNode*> polygon_nodes ( nodes, &nodes[nbn] );
3131                 const SMDS_MeshFace * f = aMesh->FindFace( polygon_nodes );
3132                 if ( !f )
3133                   myLastCreatedElems.Append(aMesh->AddPolygonalFace(polygon_nodes));
3134                 else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3135                   aMesh->ChangeElementNodes( f, nodes, nbn );
3136               }
3137             }
3138           }
3139           // go to the next volume
3140           iVol = 0;
3141           while ( iVol++ < nbVolumesByStep ) v++;
3142         }
3143       }
3144     } // sweep free links into faces
3145
3146     // make a ceiling face with a normal external to a volume
3147
3148     SMDS_VolumeTool lastVol( itElem->second.back() );
3149
3150     int iF = lastVol.GetFaceIndex( aFaceLastNodes );
3151     if ( iF >= 0 ) {
3152       lastVol.SetExternalNormal();
3153       const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
3154       int nbn = lastVol.NbFaceNodes( iF );
3155       switch ( nbn ) {
3156       case 3:
3157         if (!hasFreeLinks ||
3158             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
3159           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
3160         break;
3161       case 4:
3162         if (!hasFreeLinks ||
3163             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
3164           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ));
3165         break;
3166       default:
3167         if(itElem->second.back()->IsQuadratic()) {
3168           if(nbn==6) {
3169             if (!hasFreeLinks ||
3170                 !aMesh->FindFace(nodes[0], nodes[2], nodes[4],
3171                                  nodes[1], nodes[3], nodes[5]) ) {
3172               myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4],
3173                                                        nodes[1], nodes[3], nodes[5]));
3174             }
3175           }
3176           else { // nbn==8
3177             if (!hasFreeLinks ||
3178                 !aMesh->FindFace(nodes[0], nodes[2], nodes[4], nodes[6],
3179                                  nodes[1], nodes[3], nodes[5], nodes[7]) )
3180               myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4], nodes[6],
3181                                                        nodes[1], nodes[3], nodes[5], nodes[7]));
3182           }
3183         }
3184         else {
3185           vector<const SMDS_MeshNode*> polygon_nodes ( nodes, &nodes[nbn] );
3186           if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
3187             myLastCreatedElems.Append(aMesh->AddPolygonalFace(polygon_nodes));
3188         }
3189       } // switch
3190     }
3191   } // loop on swept elements
3192 }
3193
3194 //=======================================================================
3195 //function : RotationSweep
3196 //purpose  :
3197 //=======================================================================
3198
3199 void SMESH_MeshEditor::RotationSweep(map<int,const SMDS_MeshElement*> & theElems,
3200                                      const gp_Ax1&                  theAxis,
3201                                      const double                   theAngle,
3202                                      const int                      theNbSteps,
3203                                      const double                   theTol)
3204 {
3205   myLastCreatedElems.Clear();
3206   myLastCreatedNodes.Clear();
3207
3208   MESSAGE( "RotationSweep()");
3209   gp_Trsf aTrsf;
3210   aTrsf.SetRotation( theAxis, theAngle );
3211   gp_Trsf aTrsf2;
3212   aTrsf2.SetRotation( theAxis, theAngle/2. );
3213
3214   gp_Lin aLine( theAxis );
3215   double aSqTol = theTol * theTol;
3216
3217   SMESHDS_Mesh* aMesh = GetMeshDS();
3218
3219   TNodeOfNodeListMap mapNewNodes;
3220   TElemOfVecOfNnlmiMap mapElemNewNodes;
3221   TElemOfElemListMap newElemsMap;
3222
3223   // loop on theElems
3224   map<int, const SMDS_MeshElement* >::iterator itElem;
3225   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3226     const SMDS_MeshElement* elem = (*itElem).second;
3227     if ( !elem )
3228       continue;
3229     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3230     newNodesItVec.reserve( elem->NbNodes() );
3231
3232     // loop on elem nodes
3233     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3234     while ( itN->more() ) {
3235
3236       // check if a node has been already sweeped
3237       const SMDS_MeshNode* node =
3238         static_cast<const SMDS_MeshNode*>( itN->next() );
3239       TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
3240       if ( nIt == mapNewNodes.end() ) {
3241         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3242         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3243
3244         // make new nodes
3245         gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
3246         double coord[3];
3247         aXYZ.Coord( coord[0], coord[1], coord[2] );
3248         bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
3249         const SMDS_MeshNode * newNode = node;
3250         for ( int i = 0; i < theNbSteps; i++ ) {
3251           if ( !isOnAxis ) {
3252             if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3253               // create two nodes
3254               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3255               //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3256               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3257               myLastCreatedNodes.Append(newNode);
3258               listNewNodes.push_back( newNode );
3259               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3260               //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3261             }
3262             else {
3263               aTrsf.Transforms( coord[0], coord[1], coord[2] );
3264             }
3265             newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3266             myLastCreatedNodes.Append(newNode);
3267           }
3268           listNewNodes.push_back( newNode );
3269         }
3270       }
3271       else {
3272         // if current elem is quadratic and current node is not medium
3273         // we have to check - may be it is needed to insert additional nodes
3274         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3275           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3276           if(listNewNodes.size()==theNbSteps) {
3277             listNewNodes.clear();
3278             // make new nodes
3279             gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
3280             double coord[3];
3281             aXYZ.Coord( coord[0], coord[1], coord[2] );
3282             const SMDS_MeshNode * newNode = node;
3283             for(int i = 0; i<theNbSteps; i++) {
3284               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3285               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3286               myLastCreatedNodes.Append(newNode);
3287               listNewNodes.push_back( newNode );
3288               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3289               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3290               myLastCreatedNodes.Append(newNode);
3291               listNewNodes.push_back( newNode );
3292             }
3293           }
3294         }
3295       }
3296       newNodesItVec.push_back( nIt );
3297     }
3298     // make new elements
3299     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem], theNbSteps, myLastCreatedElems );
3300   }
3301
3302   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems, theNbSteps, myLastCreatedElems );
3303
3304 }
3305
3306
3307 //=======================================================================
3308 //function : CreateNode
3309 //purpose  : 
3310 //=======================================================================
3311 const SMDS_MeshNode* SMESH_MeshEditor::CreateNode(const double x,
3312                                                   const double y,
3313                                                   const double z,
3314                                                   const double tolnode,
3315                                                   SMESH_SequenceOfNode& aNodes)
3316 {
3317   myLastCreatedElems.Clear();
3318   myLastCreatedNodes.Clear();
3319
3320   gp_Pnt P1(x,y,z);
3321   SMESHDS_Mesh * aMesh = myMesh->GetMeshDS();
3322
3323   // try to search in sequence of existing nodes
3324   // if aNodes.Length()>0 we 'nave to use given sequence
3325   // else - use all nodes of mesh
3326   if(aNodes.Length()>0) {
3327     int i;
3328     for(i=1; i<=aNodes.Length(); i++) {
3329       gp_Pnt P2(aNodes.Value(i)->X(),aNodes.Value(i)->Y(),aNodes.Value(i)->Z());
3330       if(P1.Distance(P2)<tolnode)
3331         return aNodes.Value(i);
3332     }
3333   }
3334   else {
3335     SMDS_NodeIteratorPtr itn = aMesh->nodesIterator();
3336     while(itn->more()) {
3337       const SMDS_MeshNode* aN = static_cast<const SMDS_MeshNode*> (itn->next());
3338       gp_Pnt P2(aN->X(),aN->Y(),aN->Z());
3339       if(P1.Distance(P2)<tolnode)
3340         return aN;
3341     }    
3342   }
3343
3344   // create new node and return it
3345   const SMDS_MeshNode* NewNode = aMesh->AddNode(x,y,z);
3346   myLastCreatedNodes.Append(NewNode);
3347   return NewNode;
3348 }
3349
3350
3351 //=======================================================================
3352 //function : ExtrusionSweep
3353 //purpose  :
3354 //=======================================================================
3355
3356 void SMESH_MeshEditor::ExtrusionSweep
3357                     (map<int,const SMDS_MeshElement*> & theElems,
3358                      const gp_Vec&                  theStep,
3359                      const int                      theNbSteps,
3360                      TElemOfElemListMap&            newElemsMap,
3361                      const int                      theFlags,
3362                      const double                   theTolerance)
3363 {
3364   ExtrusParam aParams;
3365   aParams.myDir = gp_Dir(theStep);
3366   aParams.myNodes.Clear();
3367   aParams.mySteps = new TColStd_HSequenceOfReal;
3368   int i;
3369   for(i=1; i<=theNbSteps; i++)
3370     aParams.mySteps->Append(theStep.Magnitude());
3371
3372   ExtrusionSweep(theElems,aParams,newElemsMap,theFlags,theTolerance);
3373
3374 }
3375
3376
3377 //=======================================================================
3378 //function : ExtrusionSweep
3379 //purpose  :
3380 //=======================================================================
3381
3382 void SMESH_MeshEditor::ExtrusionSweep
3383                     (map<int,const SMDS_MeshElement*> & theElems,
3384                      ExtrusParam&                   theParams,
3385                      TElemOfElemListMap&            newElemsMap,
3386                      const int                      theFlags,
3387                      const double                   theTolerance)
3388 {
3389   myLastCreatedElems.Clear();
3390   myLastCreatedNodes.Clear();
3391
3392   SMESHDS_Mesh* aMesh = GetMeshDS();
3393
3394   int nbsteps = theParams.mySteps->Length();
3395
3396   TNodeOfNodeListMap mapNewNodes;
3397   //TNodeOfNodeVecMap mapNewNodes;
3398   TElemOfVecOfNnlmiMap mapElemNewNodes;
3399   //TElemOfVecOfMapNodesMap mapElemNewNodes;
3400
3401   // loop on theElems
3402   map<int, const SMDS_MeshElement* >::iterator itElem;
3403   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3404     // check element type
3405     const SMDS_MeshElement* elem = (*itElem).second;
3406     if ( !elem )
3407       continue;
3408
3409     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3410     //vector<TNodeOfNodeVecMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3411     newNodesItVec.reserve( elem->NbNodes() );
3412
3413     // loop on elem nodes
3414     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3415     while ( itN->more() ) {
3416
3417       // check if a node has been already sweeped
3418       const SMDS_MeshNode* node =
3419         static_cast<const SMDS_MeshNode*>( itN->next() );
3420       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
3421       //TNodeOfNodeVecMap::iterator nIt = mapNewNodes.find( node );
3422       if ( nIt == mapNewNodes.end() ) {
3423         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3424         //nIt = mapNewNodes.insert( make_pair( node, vector<const SMDS_MeshNode*>() )).first;
3425         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3426         //vector<const SMDS_MeshNode*>& vecNewNodes = nIt->second;
3427         //vecNewNodes.reserve(nbsteps);
3428
3429         // make new nodes
3430         double coord[] = { node->X(), node->Y(), node->Z() };
3431         //int nbsteps = theParams.mySteps->Length();
3432         for ( int i = 0; i < nbsteps; i++ ) {
3433           if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3434             // create additional node
3435             double x = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1)/2.;
3436             double y = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1)/2.;
3437             double z = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1)/2.;
3438             if( theFlags & EXTRUSION_FLAG_SEW ) {
3439               const SMDS_MeshNode * newNode = CreateNode(x, y, z,
3440                                                          theTolerance, theParams.myNodes);
3441               listNewNodes.push_back( newNode );
3442             }
3443             else {
3444               const SMDS_MeshNode * newNode = aMesh->AddNode(x, y, z);
3445               myLastCreatedNodes.Append(newNode);
3446               listNewNodes.push_back( newNode );
3447             }
3448           }
3449           //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3450           coord[0] = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3451           coord[1] = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3452           coord[2] = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3453           if( theFlags & EXTRUSION_FLAG_SEW ) {
3454             const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1], coord[2],
3455                                                        theTolerance, theParams.myNodes);
3456             listNewNodes.push_back( newNode );
3457             //vecNewNodes[i]=newNode;
3458           }
3459           else {
3460             const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3461             myLastCreatedNodes.Append(newNode);
3462             listNewNodes.push_back( newNode );
3463             //vecNewNodes[i]=newNode;
3464           }
3465         }
3466       }
3467       else {
3468         // if current elem is quadratic and current node is not medium
3469         // we have to check - may be it is needed to insert additional nodes
3470         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3471           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3472           if(listNewNodes.size()==nbsteps) {
3473             listNewNodes.clear();
3474             double coord[] = { node->X(), node->Y(), node->Z() };
3475             for ( int i = 0; i < nbsteps; i++ ) {
3476               double x = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3477               double y = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3478               double z = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3479               if( theFlags & EXTRUSION_FLAG_SEW ) {
3480                 const SMDS_MeshNode * newNode = CreateNode(x, y, z,
3481                                                            theTolerance, theParams.myNodes);
3482                 listNewNodes.push_back( newNode );
3483               }
3484               else {
3485                 const SMDS_MeshNode * newNode = aMesh->AddNode(x, y, z);
3486                 myLastCreatedNodes.Append(newNode);
3487                 listNewNodes.push_back( newNode );
3488               }
3489               coord[0] = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3490               coord[1] = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3491               coord[2] = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3492               if( theFlags & EXTRUSION_FLAG_SEW ) {
3493                 const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1], coord[2],
3494                                                            theTolerance, theParams.myNodes);
3495                 listNewNodes.push_back( newNode );
3496               }
3497               else {
3498                 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3499                 myLastCreatedNodes.Append(newNode);
3500                 listNewNodes.push_back( newNode );
3501               }
3502             }
3503           }
3504         }
3505       }
3506       newNodesItVec.push_back( nIt );
3507     }
3508     // make new elements
3509     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem], nbsteps, myLastCreatedElems );
3510   }
3511
3512   if( theFlags & EXTRUSION_FLAG_BOUNDARY ) {
3513     makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems, nbsteps, myLastCreatedElems );
3514   }
3515 }
3516
3517
3518 //=======================================================================
3519 //class    : SMESH_MeshEditor_PathPoint
3520 //purpose  : auxiliary class
3521 //=======================================================================
3522 class SMESH_MeshEditor_PathPoint {
3523 public:
3524   SMESH_MeshEditor_PathPoint() {
3525     myPnt.SetCoord(99., 99., 99.);
3526     myTgt.SetCoord(1.,0.,0.);
3527     myAngle=0.;
3528     myPrm=0.;
3529   }
3530   void SetPnt(const gp_Pnt& aP3D){
3531     myPnt=aP3D;
3532   }
3533   void SetTangent(const gp_Dir& aTgt){
3534     myTgt=aTgt;
3535   }
3536   void SetAngle(const double& aBeta){
3537     myAngle=aBeta;
3538   }
3539   void SetParameter(const double& aPrm){
3540     myPrm=aPrm;
3541   }
3542   const gp_Pnt& Pnt()const{
3543     return myPnt;
3544   }
3545   const gp_Dir& Tangent()const{
3546     return myTgt;
3547   }
3548   double Angle()const{
3549     return myAngle;
3550   }
3551   double Parameter()const{
3552     return myPrm;
3553   }
3554
3555 protected:
3556   gp_Pnt myPnt;
3557   gp_Dir myTgt;
3558   double myAngle;
3559   double myPrm;
3560 };
3561
3562 //=======================================================================
3563 //function : ExtrusionAlongTrack
3564 //purpose  :
3565 //=======================================================================
3566 SMESH_MeshEditor::Extrusion_Error
3567   SMESH_MeshEditor::ExtrusionAlongTrack (std::map<int,const SMDS_MeshElement*> & theElements,
3568                                          SMESH_subMesh* theTrack,
3569                                          const SMDS_MeshNode* theN1,
3570                                          const bool theHasAngles,
3571                                          std::list<double>& theAngles,
3572                                          const bool theHasRefPoint,
3573                                          const gp_Pnt& theRefPoint)
3574 {
3575   myLastCreatedElems.Clear();
3576   myLastCreatedNodes.Clear();
3577
3578   MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
3579   int j, aNbTP, aNbE, aNb;
3580   double aT1, aT2, aT, aAngle, aX, aY, aZ;
3581   std::list<double> aPrms;
3582   std::list<double>::iterator aItD;
3583   std::map<int, const SMDS_MeshElement* >::iterator itElem;
3584
3585   Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
3586   gp_Pnt aP3D, aV0;
3587   gp_Vec aVec;
3588   gp_XYZ aGC;
3589   Handle(Geom_Curve) aC3D;
3590   TopoDS_Edge aTrackEdge;
3591   TopoDS_Vertex aV1, aV2;
3592
3593   SMDS_ElemIteratorPtr aItE;
3594   SMDS_NodeIteratorPtr aItN;
3595   SMDSAbs_ElementType aTypeE;
3596
3597   TNodeOfNodeListMap mapNewNodes;
3598   TElemOfVecOfNnlmiMap mapElemNewNodes;
3599   TElemOfElemListMap newElemsMap;
3600
3601   aTolVec=1.e-7;
3602   aTolVec2=aTolVec*aTolVec;
3603
3604   // 1. Check data
3605   aNbE = theElements.size();
3606   // nothing to do
3607   if ( !aNbE )
3608     return EXTR_NO_ELEMENTS;
3609
3610   // 1.1 Track Pattern
3611   ASSERT( theTrack );
3612
3613   SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
3614
3615   aItE = pSubMeshDS->GetElements();
3616   while ( aItE->more() ) {
3617     const SMDS_MeshElement* pE = aItE->next();
3618     aTypeE = pE->GetType();
3619     // Pattern must contain links only
3620     if ( aTypeE != SMDSAbs_Edge )
3621       return EXTR_PATH_NOT_EDGE;
3622   }
3623
3624   const TopoDS_Shape& aS = theTrack->GetSubShape();
3625   // Sub shape for the Pattern must be an Edge
3626   if ( aS.ShapeType() != TopAbs_EDGE )
3627     return EXTR_BAD_PATH_SHAPE;
3628
3629   aTrackEdge = TopoDS::Edge( aS );
3630   // the Edge must not be degenerated
3631   if ( BRep_Tool::Degenerated( aTrackEdge ) )
3632     return EXTR_BAD_PATH_SHAPE;
3633
3634   TopExp::Vertices( aTrackEdge, aV1, aV2 );
3635   aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
3636   aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
3637
3638   aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
3639   const SMDS_MeshNode* aN1 = aItN->next();
3640
3641   aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
3642   const SMDS_MeshNode* aN2 = aItN->next();
3643
3644   // starting node must be aN1 or aN2
3645   if ( !( aN1 == theN1 || aN2 == theN1 ) )
3646     return EXTR_BAD_STARTING_NODE;
3647
3648   aNbTP = pSubMeshDS->NbNodes() + 2;
3649
3650   // 1.2. Angles
3651   vector<double> aAngles( aNbTP );
3652
3653   for ( j=0; j < aNbTP; ++j ) {
3654     aAngles[j] = 0.;
3655   }
3656
3657   if ( theHasAngles ) {
3658     aItD = theAngles.begin();
3659     for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
3660       aAngle = *aItD;
3661       aAngles[j] = aAngle;
3662     }
3663   }
3664
3665   // 2. Collect parameters on the track edge
3666   aPrms.push_back( aT1 );
3667   aPrms.push_back( aT2 );
3668
3669   aItN = pSubMeshDS->GetNodes();
3670   while ( aItN->more() ) {
3671     const SMDS_MeshNode* pNode = aItN->next();
3672     const SMDS_EdgePosition* pEPos =
3673       static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
3674     aT = pEPos->GetUParameter();
3675     aPrms.push_back( aT );
3676   }
3677
3678   // sort parameters
3679   aPrms.sort();
3680   if ( aN1 == theN1 ) {
3681     if ( aT1 > aT2 ) {
3682       aPrms.reverse();
3683     }
3684   }
3685   else {
3686     if ( aT2 > aT1 ) {
3687       aPrms.reverse();
3688     }
3689   }
3690
3691   // 3. Path Points
3692   SMESH_MeshEditor_PathPoint aPP;
3693   vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
3694   //
3695   aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
3696   //
3697   aItD = aPrms.begin();
3698   for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
3699     aT = *aItD;
3700     aC3D->D1( aT, aP3D, aVec );
3701     aL2 = aVec.SquareMagnitude();
3702     if ( aL2 < aTolVec2 )
3703       return EXTR_CANT_GET_TANGENT;
3704
3705     gp_Dir aTgt( aVec );
3706     aAngle = aAngles[j];
3707
3708     aPP.SetPnt( aP3D );
3709     aPP.SetTangent( aTgt );
3710     aPP.SetAngle( aAngle );
3711     aPP.SetParameter( aT );
3712     aPPs[j]=aPP;
3713   }
3714
3715   // 3. Center of rotation aV0
3716   aV0 = theRefPoint;
3717   if ( !theHasRefPoint ) {
3718     aNb = 0;
3719     aGC.SetCoord( 0.,0.,0. );
3720
3721     itElem = theElements.begin();
3722     for ( ; itElem != theElements.end(); itElem++ ) {
3723       const SMDS_MeshElement* elem = (*itElem).second;
3724
3725       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3726       while ( itN->more() ) {
3727         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
3728         aX = node->X();
3729         aY = node->Y();
3730         aZ = node->Z();
3731
3732         if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
3733           list<const SMDS_MeshNode*> aLNx;
3734           mapNewNodes[node] = aLNx;
3735           //
3736           gp_XYZ aXYZ( aX, aY, aZ );
3737           aGC += aXYZ;
3738           ++aNb;
3739         }
3740       }
3741     }
3742     aGC /= aNb;
3743     aV0.SetXYZ( aGC );
3744   } // if (!theHasRefPoint) {
3745   mapNewNodes.clear();
3746
3747   // 4. Processing the elements
3748   SMESHDS_Mesh* aMesh = GetMeshDS();
3749
3750   for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
3751     // check element type
3752     const SMDS_MeshElement* elem = (*itElem).second;
3753     aTypeE = elem->GetType();
3754     if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
3755       continue;
3756
3757     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3758     newNodesItVec.reserve( elem->NbNodes() );
3759
3760     // loop on elem nodes
3761     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3762     while ( itN->more() ) {
3763
3764       // check if a node has been already processed
3765       const SMDS_MeshNode* node =
3766         static_cast<const SMDS_MeshNode*>( itN->next() );
3767       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
3768       if ( nIt == mapNewNodes.end() ) {
3769         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3770         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3771
3772         // make new nodes
3773         aX = node->X();  aY = node->Y(); aZ = node->Z();
3774
3775         Standard_Real aAngle1x, aAngleT1T0, aTolAng;
3776         gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
3777         gp_Ax1 anAx1, anAxT1T0;
3778         gp_Dir aDT1x, aDT0x, aDT1T0;
3779
3780         aTolAng=1.e-4;
3781
3782         aV0x = aV0;
3783         aPN0.SetCoord(aX, aY, aZ);
3784
3785         const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
3786         aP0x = aPP0.Pnt();
3787         aDT0x= aPP0.Tangent();
3788
3789         for ( j = 1; j < aNbTP; ++j ) {
3790           const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
3791           aP1x = aPP1.Pnt();
3792           aDT1x = aPP1.Tangent();
3793           aAngle1x = aPP1.Angle();
3794
3795           gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
3796           // Translation
3797           gp_Vec aV01x( aP0x, aP1x );
3798           aTrsf.SetTranslation( aV01x );
3799
3800           // traslated point
3801           aV1x = aV0x.Transformed( aTrsf );
3802           aPN1 = aPN0.Transformed( aTrsf );
3803
3804           // rotation 1 [ T1,T0 ]
3805           aAngleT1T0=-aDT1x.Angle( aDT0x );
3806           if (fabs(aAngleT1T0) > aTolAng) {
3807             aDT1T0=aDT1x^aDT0x;
3808             anAxT1T0.SetLocation( aV1x );
3809             anAxT1T0.SetDirection( aDT1T0 );
3810             aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
3811
3812             aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
3813           }
3814
3815           // rotation 2
3816           if ( theHasAngles ) {
3817             anAx1.SetLocation( aV1x );
3818             anAx1.SetDirection( aDT1x );
3819             aTrsfRot.SetRotation( anAx1, aAngle1x );
3820
3821             aPN1 = aPN1.Transformed( aTrsfRot );
3822           }
3823
3824           // make new node
3825           if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3826             // create additional node
3827             double x = ( aPN1.X() + aPN0.X() )/2.;
3828             double y = ( aPN1.Y() + aPN0.Y() )/2.;
3829             double z = ( aPN1.Z() + aPN0.Z() )/2.;
3830             const SMDS_MeshNode* newNode = aMesh->AddNode(x,y,z);
3831             myLastCreatedNodes.Append(newNode);
3832             listNewNodes.push_back( newNode );
3833           }
3834           aX = aPN1.X();
3835           aY = aPN1.Y();
3836           aZ = aPN1.Z();
3837           const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
3838           myLastCreatedNodes.Append(newNode);
3839           listNewNodes.push_back( newNode );
3840
3841           aPN0 = aPN1;
3842           aP0x = aP1x;
3843           aV0x = aV1x;
3844           aDT0x = aDT1x;
3845         }
3846       }
3847
3848       else {
3849         // if current elem is quadratic and current node is not medium
3850         // we have to check - may be it is needed to insert additional nodes
3851         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3852           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3853           if(listNewNodes.size()==aNbTP-1) {
3854             vector<const SMDS_MeshNode*> aNodes(2*(aNbTP-1));
3855             gp_XYZ P(node->X(), node->Y(), node->Z());
3856             list< const SMDS_MeshNode* >::iterator it = listNewNodes.begin();
3857             int i;
3858             for(i=0; i<aNbTP-1; i++) {
3859               const SMDS_MeshNode* N = *it;
3860               double x = ( N->X() + P.X() )/2.;
3861               double y = ( N->Y() + P.Y() )/2.;
3862               double z = ( N->Z() + P.Z() )/2.;
3863               const SMDS_MeshNode* newN = aMesh->AddNode(x,y,z);
3864               myLastCreatedNodes.Append(newN);
3865               aNodes[2*i] = newN;
3866               aNodes[2*i+1] = N;
3867               P = gp_XYZ(N->X(),N->Y(),N->Z());
3868             }
3869             listNewNodes.clear();
3870             for(i=0; i<2*(aNbTP-1); i++) {
3871               listNewNodes.push_back(aNodes[i]);
3872             }
3873           }
3874         }
3875       }
3876
3877       newNodesItVec.push_back( nIt );
3878     }
3879     // make new elements
3880     //sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem],
3881     //              newNodesItVec[0]->second.size(), myLastCreatedElems );
3882     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem],
3883                   aNbTP-1, myLastCreatedElems );
3884   }
3885
3886   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements,
3887              aNbTP-1, myLastCreatedElems );
3888
3889   return EXTR_OK;
3890 }
3891
3892 //=======================================================================
3893 //function : Transform
3894 //purpose  :
3895 //=======================================================================
3896
3897 void SMESH_MeshEditor::Transform (map<int,const SMDS_MeshElement*> & theElems,
3898                                   const gp_Trsf&                 theTrsf,
3899                                   const bool                     theCopy)
3900 {
3901   myLastCreatedElems.Clear();
3902   myLastCreatedNodes.Clear();
3903
3904   bool needReverse;
3905   switch ( theTrsf.Form() ) {
3906   case gp_PntMirror:
3907   case gp_Ax2Mirror:
3908     needReverse = true;
3909     break;
3910   default:
3911     needReverse = false;
3912   }
3913
3914   SMESHDS_Mesh* aMesh = GetMeshDS();
3915
3916   // map old node to new one
3917   TNodeNodeMap nodeMap;
3918
3919   // elements sharing moved nodes; those of them which have all
3920   // nodes mirrored but are not in theElems are to be reversed
3921   map<int,const SMDS_MeshElement*> inverseElemSet;
3922
3923   // loop on theElems
3924   map<int, const SMDS_MeshElement* >::iterator itElem;
3925   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3926     const SMDS_MeshElement* elem = (*itElem).second;
3927     if ( !elem )
3928       continue;
3929
3930     // loop on elem nodes
3931     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3932     while ( itN->more() ) {
3933
3934       // check if a node has been already transformed
3935       const SMDS_MeshNode* node =
3936         static_cast<const SMDS_MeshNode*>( itN->next() );
3937       if (nodeMap.find( node ) != nodeMap.end() )
3938         continue;
3939
3940       double coord[3];
3941       coord[0] = node->X();
3942       coord[1] = node->Y();
3943       coord[2] = node->Z();
3944       theTrsf.Transforms( coord[0], coord[1], coord[2] );
3945       const SMDS_MeshNode * newNode = node;
3946       if ( theCopy ) {
3947         newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3948         myLastCreatedNodes.Append(newNode);
3949       }
3950       else {
3951         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
3952         // node position on shape becomes invalid
3953         const_cast< SMDS_MeshNode* > ( node )->SetPosition
3954           ( SMDS_SpacePosition::originSpacePosition() );
3955       }
3956       nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
3957
3958       // keep inverse elements
3959       if ( !theCopy && needReverse ) {
3960         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
3961         while ( invElemIt->more() ) {
3962           const SMDS_MeshElement* iel = invElemIt->next(); 
3963           inverseElemSet.insert( make_pair(iel->GetID(),iel) );
3964         }
3965       }
3966     }
3967   }
3968
3969   // either new elements are to be created
3970   // or a mirrored element are to be reversed
3971   if ( !theCopy && !needReverse)
3972     return;
3973
3974   if ( !inverseElemSet.empty()) {
3975     map<int,const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
3976     for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
3977       theElems.insert( *invElemIt );
3978   }
3979
3980   // replicate or reverse elements
3981
3982   enum {
3983     REV_TETRA   = 0,  //  = nbNodes - 4
3984     REV_PYRAMID = 1,  //  = nbNodes - 4
3985     REV_PENTA   = 2,  //  = nbNodes - 4
3986     REV_FACE    = 3,
3987     REV_HEXA    = 4,  //  = nbNodes - 4
3988     FORWARD     = 5
3989     };
3990   int index[][8] = {
3991     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA
3992     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
3993     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA
3994     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE
3995     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA
3996     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD
3997   };
3998
3999   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
4000     const SMDS_MeshElement* elem = (*itElem).second;
4001     if ( !elem || elem->GetType() == SMDSAbs_Node )
4002       continue;
4003
4004     int nbNodes = elem->NbNodes();
4005     int elemType = elem->GetType();
4006
4007     if (elem->IsPoly()) {
4008       // Polygon or Polyhedral Volume
4009       switch ( elemType ) {
4010       case SMDSAbs_Face:
4011         {
4012           vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
4013           int iNode = 0;
4014           SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4015           while (itN->more()) {
4016             const SMDS_MeshNode* node =
4017               static_cast<const SMDS_MeshNode*>(itN->next());
4018             TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
4019             if (nodeMapIt == nodeMap.end())
4020               break; // not all nodes transformed
4021             if (needReverse) {
4022               // reverse mirrored faces and volumes
4023               poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
4024             } else {
4025               poly_nodes[iNode] = (*nodeMapIt).second;
4026             }
4027             iNode++;
4028           }
4029           if ( iNode != nbNodes )
4030             continue; // not all nodes transformed
4031
4032           if ( theCopy ) {
4033             myLastCreatedElems.Append(aMesh->AddPolygonalFace(poly_nodes));
4034           }
4035           else {
4036             aMesh->ChangePolygonNodes(elem, poly_nodes);
4037           }
4038         }
4039         break;
4040       case SMDSAbs_Volume:
4041         {
4042           // ATTENTION: Reversing is not yet done!!!
4043           const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4044             (const SMDS_PolyhedralVolumeOfNodes*) elem;
4045           if (!aPolyedre) {
4046             MESSAGE("Warning: bad volumic element");
4047             continue;
4048           }
4049
4050           vector<const SMDS_MeshNode*> poly_nodes;
4051           vector<int> quantities;
4052
4053           bool allTransformed = true;
4054           int nbFaces = aPolyedre->NbFaces();
4055           for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
4056             int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4057             for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
4058               const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
4059               TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
4060               if (nodeMapIt == nodeMap.end()) {
4061                 allTransformed = false; // not all nodes transformed
4062               } else {
4063                 poly_nodes.push_back((*nodeMapIt).second);
4064               }
4065             }
4066             quantities.push_back(nbFaceNodes);
4067           }
4068           if ( !allTransformed )
4069             continue; // not all nodes transformed
4070
4071           if ( theCopy ) {
4072             myLastCreatedElems.Append(aMesh->AddPolyhedralVolume(poly_nodes, quantities));
4073           }
4074           else {
4075             aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4076           }
4077         }
4078         break;
4079       default:;
4080       }
4081       continue;
4082     }
4083
4084     // Regular elements
4085     int* i = index[ FORWARD ];
4086     if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
4087       if ( elemType == SMDSAbs_Face )
4088         i = index[ REV_FACE ];
4089       else
4090         i = index[ nbNodes - 4 ];
4091
4092     if(elem->IsQuadratic()) {
4093       static int anIds[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
4094       i = anIds;
4095       if(needReverse) {
4096         if(nbNodes==3) { // quadratic edge
4097           static int anIds[] = {1,0,2};
4098           i = anIds;
4099         }
4100         else if(nbNodes==6) { // quadratic triangle
4101           static int anIds[] = {0,2,1,5,4,3};
4102           i = anIds;
4103         }
4104         else if(nbNodes==8) { // quadratic quadrangle
4105           static int anIds[] = {0,3,2,1,7,6,5,4};
4106           i = anIds;
4107         }
4108         else if(nbNodes==10) { // quadratic tetrahedron of 10 nodes
4109           static int anIds[] = {0,2,1,3,6,5,4,7,9,8};
4110           i = anIds;
4111         }
4112         else if(nbNodes==13) { // quadratic pyramid of 13 nodes
4113           static int anIds[] = {0,3,2,1,4,8,7,6,5,9,12,11,10};
4114           i = anIds;
4115         }
4116         else if(nbNodes==15) { // quadratic pentahedron with 15 nodes
4117           static int anIds[] = {0,2,1,3,5,4,8,7,6,11,10,9,12,14,13};
4118           i = anIds;
4119         }
4120         else { // nbNodes==20 - quadratic hexahedron with 20 nodes
4121           static int anIds[] = {0,3,2,1,4,7,6,5,11,10,9,8,15,14,13,12,16,19,18,17};
4122           i = anIds;
4123         }
4124       }
4125     }
4126
4127     // find transformed nodes
4128     const SMDS_MeshNode* nodes[8];
4129     int iNode = 0;
4130     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4131     while ( itN->more() ) {
4132       const SMDS_MeshNode* node =
4133         static_cast<const SMDS_MeshNode*>( itN->next() );
4134       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
4135       if ( nodeMapIt == nodeMap.end() )
4136         break; // not all nodes transformed
4137       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
4138     }
4139     if ( iNode != nbNodes )
4140       continue; // not all nodes transformed
4141
4142     if ( theCopy ) {
4143       // add a new element
4144       switch ( elemType ) {
4145       case SMDSAbs_Edge:
4146         if ( nbNodes == 2 )
4147           myLastCreatedElems.Append(aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] ));
4148         else
4149           myLastCreatedElems.Append(aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
4150         break;
4151       case SMDSAbs_Face:
4152         if ( nbNodes == 3 )
4153           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
4154         else if(nbNodes==4)
4155           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]));
4156         else if(nbNodes==6)
4157           myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[1], nodes[2], nodes[3],
4158                                              nodes[4], nodes[5]));
4159         else // nbNodes==8
4160           myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[1], nodes[2], nodes[3],
4161                                              nodes[4], nodes[5], nodes[6], nodes[7]));
4162         break;
4163       case SMDSAbs_Volume:
4164         if ( nbNodes == 4 )
4165           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] ));
4166         else if ( nbNodes == 8 )
4167           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
4168                                                nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]));
4169         else if ( nbNodes == 6 )
4170           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
4171                                                nodes[ 4 ], nodes[ 5 ]));
4172         else if ( nbNodes == 5 )
4173           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
4174                                                nodes[ 4 ]));
4175         else if(nbNodes==10)
4176           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4177                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9]));
4178         else if(nbNodes==13)
4179           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4180                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9],
4181                                                nodes[10], nodes[11], nodes[12]));
4182         else if(nbNodes==15)
4183           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4184                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9],
4185                                                nodes[10], nodes[11], nodes[12], nodes[13], nodes[14]));
4186         else // nbNodes==20
4187           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4188                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9],
4189                                                nodes[10], nodes[11], nodes[12], nodes[13], nodes[14],
4190                                                nodes[15], nodes[16], nodes[17], nodes[18], nodes[19]));
4191         break;
4192       default:;
4193       }
4194     }
4195     else
4196     {
4197       // reverse element as it was reversed by transformation
4198       if ( nbNodes > 2 )
4199         aMesh->ChangeElementNodes( elem, nodes, nbNodes );
4200     }
4201   }
4202 }
4203
4204 //=======================================================================
4205 //function : FindCoincidentNodes
4206 //purpose  : Return list of group of nodes close to each other within theTolerance
4207 //           Search among theNodes or in the whole mesh if theNodes is empty.
4208 //=======================================================================
4209
4210 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
4211                                             const double                theTolerance,
4212                                             TListOfListOfNodes &        theGroupsOfNodes)
4213 {
4214   myLastCreatedElems.Clear();
4215   myLastCreatedNodes.Clear();
4216
4217   double tol2 = theTolerance * theTolerance;
4218
4219   list<const SMDS_MeshNode*> nodes;
4220   if ( theNodes.empty() )
4221   { // get all nodes in the mesh
4222     SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
4223     while ( nIt->more() )
4224       nodes.push_back( nIt->next() );
4225   }
4226   else
4227   {
4228     nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
4229   }
4230
4231   list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
4232   for ( ; it1 != nodes.end(); it1++ )
4233   {
4234     const SMDS_MeshNode* n1 = *it1;
4235     gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
4236
4237     list<const SMDS_MeshNode*> * groupPtr = 0;
4238     it2 = it1;
4239     for ( it2++; it2 != nodes.end(); it2++ )
4240     {
4241       const SMDS_MeshNode* n2 = *it2;
4242       gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
4243       if ( p1.SquareDistance( p2 ) <= tol2 )
4244       {
4245         if ( !groupPtr ) {
4246           theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
4247           groupPtr = & theGroupsOfNodes.back();
4248           groupPtr->push_back( n1 );
4249         }
4250         if(groupPtr->front()>n2)
4251           groupPtr->push_front( n2 );
4252         else
4253           groupPtr->push_back( n2 );
4254         it2 = nodes.erase( it2 );
4255         it2--;
4256       }
4257     }
4258   }
4259 }
4260
4261 //=======================================================================
4262 //function : SimplifyFace
4263 //purpose  :
4264 //=======================================================================
4265 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
4266                                     vector<const SMDS_MeshNode *>&      poly_nodes,
4267                                     vector<int>&                        quantities) const
4268 {
4269   int nbNodes = faceNodes.size();
4270
4271   if (nbNodes < 3)
4272     return 0;
4273
4274   set<const SMDS_MeshNode*> nodeSet;
4275
4276   // get simple seq of nodes
4277   const SMDS_MeshNode* simpleNodes[ nbNodes ];
4278   int iSimple = 0, nbUnique = 0;
4279
4280   simpleNodes[iSimple++] = faceNodes[0];
4281   nbUnique++;
4282   for (int iCur = 1; iCur < nbNodes; iCur++) {
4283     if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
4284       simpleNodes[iSimple++] = faceNodes[iCur];
4285       if (nodeSet.insert( faceNodes[iCur] ).second)
4286         nbUnique++;
4287     }
4288   }
4289   int nbSimple = iSimple;
4290   if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
4291     nbSimple--;
4292     iSimple--;
4293   }
4294
4295   if (nbUnique < 3)
4296     return 0;
4297
4298   // separate loops
4299   int nbNew = 0;
4300   bool foundLoop = (nbSimple > nbUnique);
4301   while (foundLoop) {
4302     foundLoop = false;
4303     set<const SMDS_MeshNode*> loopSet;
4304     for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
4305       const SMDS_MeshNode* n = simpleNodes[iSimple];
4306       if (!loopSet.insert( n ).second) {
4307         foundLoop = true;
4308
4309         // separate loop
4310         int iC = 0, curLast = iSimple;
4311         for (; iC < curLast; iC++) {
4312           if (simpleNodes[iC] == n) break;
4313         }
4314         int loopLen = curLast - iC;
4315         if (loopLen > 2) {
4316           // create sub-element
4317           nbNew++;
4318           quantities.push_back(loopLen);
4319           for (; iC < curLast; iC++) {
4320             poly_nodes.push_back(simpleNodes[iC]);
4321           }
4322         }
4323         // shift the rest nodes (place from the first loop position)
4324         for (iC = curLast + 1; iC < nbSimple; iC++) {
4325           simpleNodes[iC - loopLen] = simpleNodes[iC];
4326         }
4327         nbSimple -= loopLen;
4328         iSimple -= loopLen;
4329       }
4330     } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
4331   } // while (foundLoop)
4332
4333   if (iSimple > 2) {
4334     nbNew++;
4335     quantities.push_back(iSimple);
4336     for (int i = 0; i < iSimple; i++)
4337       poly_nodes.push_back(simpleNodes[i]);
4338   }
4339
4340   return nbNew;
4341 }
4342
4343 //=======================================================================
4344 //function : MergeNodes
4345 //purpose  : In each group, the cdr of nodes are substituted by the first one
4346 //           in all elements.
4347 //=======================================================================
4348
4349 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
4350 {
4351   myLastCreatedElems.Clear();
4352   myLastCreatedNodes.Clear();
4353
4354   SMESHDS_Mesh* aMesh = GetMeshDS();
4355
4356   TNodeNodeMap nodeNodeMap; // node to replace - new node
4357   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
4358   list< int > rmElemIds, rmNodeIds;
4359
4360   // Fill nodeNodeMap and elems
4361
4362   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
4363   for ( ; grIt != theGroupsOfNodes.end(); grIt++ ) {
4364     list<const SMDS_MeshNode*>& nodes = *grIt;
4365     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
4366     const SMDS_MeshNode* nToKeep = *nIt;
4367     for ( ; nIt != nodes.end(); nIt++ ) {
4368       const SMDS_MeshNode* nToRemove = *nIt;
4369       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
4370       if ( nToRemove != nToKeep ) {
4371         rmNodeIds.push_back( nToRemove->GetID() );
4372         AddToSameGroups( nToKeep, nToRemove, aMesh );
4373       }
4374
4375       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
4376       while ( invElemIt->more() ) {
4377         const SMDS_MeshElement* elem = invElemIt->next();
4378           elems.insert(elem);
4379       }
4380     }
4381   }
4382   // Change element nodes or remove an element
4383
4384   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
4385   for ( ; eIt != elems.end(); eIt++ ) {
4386     const SMDS_MeshElement* elem = *eIt;
4387     int nbNodes = elem->NbNodes();
4388     int aShapeId = FindShape( elem );
4389
4390     set<const SMDS_MeshNode*> nodeSet;
4391     const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
4392     int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
4393
4394     // get new seq of nodes
4395     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4396     while ( itN->more() ) {
4397       const SMDS_MeshNode* n =
4398         static_cast<const SMDS_MeshNode*>( itN->next() );
4399
4400       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
4401       if ( nnIt != nodeNodeMap.end() ) { // n sticks
4402         n = (*nnIt).second;
4403         iRepl[ nbRepl++ ] = iCur;
4404       }
4405       curNodes[ iCur ] = n;
4406       bool isUnique = nodeSet.insert( n ).second;
4407       if ( isUnique )
4408         uniqueNodes[ iUnique++ ] = n;
4409       iCur++;
4410     }
4411
4412     // Analyse element topology after replacement
4413
4414     bool isOk = true;
4415     int nbUniqueNodes = nodeSet.size();
4416     if ( nbNodes != nbUniqueNodes ) { // some nodes stick
4417       // Polygons and Polyhedral volumes
4418       if (elem->IsPoly()) {
4419
4420         if (elem->GetType() == SMDSAbs_Face) {
4421           // Polygon
4422           vector<const SMDS_MeshNode *> face_nodes (nbNodes);
4423           int inode = 0;
4424           for (; inode < nbNodes; inode++) {
4425             face_nodes[inode] = curNodes[inode];
4426           }
4427
4428           vector<const SMDS_MeshNode *> polygons_nodes;
4429           vector<int> quantities;
4430           int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
4431
4432           if (nbNew > 0) {
4433             inode = 0;
4434             for (int iface = 0; iface < nbNew - 1; iface++) {
4435               int nbNodes = quantities[iface];
4436               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4437               for (int ii = 0; ii < nbNodes; ii++, inode++) {
4438                 poly_nodes[ii] = polygons_nodes[inode];
4439               }
4440               SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4441               myLastCreatedElems.Append(newElem);
4442               if (aShapeId)
4443                 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4444             }
4445             aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
4446           }
4447           else {
4448             rmElemIds.push_back(elem->GetID());
4449           }
4450
4451         }
4452         else if (elem->GetType() == SMDSAbs_Volume) {
4453           // Polyhedral volume
4454           if (nbUniqueNodes < 4) {
4455             rmElemIds.push_back(elem->GetID());
4456           }
4457           else {
4458             // each face has to be analized in order to check volume validity
4459             const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4460               static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
4461             if (aPolyedre) {
4462               int nbFaces = aPolyedre->NbFaces();
4463
4464               vector<const SMDS_MeshNode *> poly_nodes;
4465               vector<int> quantities;
4466
4467               for (int iface = 1; iface <= nbFaces; iface++) {
4468                 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4469                 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
4470
4471                 for (int inode = 1; inode <= nbFaceNodes; inode++) {
4472                   const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
4473                   TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
4474                   if (nnIt != nodeNodeMap.end()) { // faceNode sticks
4475                     faceNode = (*nnIt).second;
4476                   }
4477                   faceNodes[inode - 1] = faceNode;
4478                 }
4479
4480                 SimplifyFace(faceNodes, poly_nodes, quantities);
4481               }
4482
4483               if (quantities.size() > 3) {
4484                 // to be done: remove coincident faces
4485               }
4486
4487               if (quantities.size() > 3)
4488                 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4489               else
4490                 rmElemIds.push_back(elem->GetID());
4491
4492             }
4493             else {
4494               rmElemIds.push_back(elem->GetID());
4495             }
4496           }
4497         }
4498         else {
4499         }
4500
4501         continue;
4502       }
4503
4504       // Regular elements
4505       switch ( nbNodes ) {
4506       case 2: ///////////////////////////////////// EDGE
4507         isOk = false; break;
4508       case 3: ///////////////////////////////////// TRIANGLE
4509         isOk = false; break;
4510       case 4:
4511         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
4512           isOk = false;
4513         else { //////////////////////////////////// QUADRANGLE
4514           if ( nbUniqueNodes < 3 )
4515             isOk = false;
4516           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
4517             isOk = false; // opposite nodes stick
4518         }
4519         break;
4520       case 6: ///////////////////////////////////// PENTAHEDRON
4521         if ( nbUniqueNodes == 4 ) {
4522           // ---------------------------------> tetrahedron
4523           if (nbRepl == 3 &&
4524               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
4525             // all top nodes stick: reverse a bottom
4526             uniqueNodes[ 0 ] = curNodes [ 1 ];
4527             uniqueNodes[ 1 ] = curNodes [ 0 ];
4528           }
4529           else if (nbRepl == 3 &&
4530                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
4531             // all bottom nodes stick: set a top before
4532             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
4533             uniqueNodes[ 0 ] = curNodes [ 3 ];
4534             uniqueNodes[ 1 ] = curNodes [ 4 ];
4535             uniqueNodes[ 2 ] = curNodes [ 5 ];
4536           }
4537           else if (nbRepl == 4 &&
4538                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
4539             // a lateral face turns into a line: reverse a bottom
4540             uniqueNodes[ 0 ] = curNodes [ 1 ];
4541             uniqueNodes[ 1 ] = curNodes [ 0 ];
4542           }
4543           else
4544             isOk = false;
4545         }
4546         else if ( nbUniqueNodes == 5 ) {
4547           // PENTAHEDRON --------------------> 2 tetrahedrons
4548           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
4549             // a bottom node sticks with a linked top one
4550             // 1.
4551             SMDS_MeshElement* newElem =
4552               aMesh->AddVolume(curNodes[ 3 ],
4553                                curNodes[ 4 ],
4554                                curNodes[ 5 ],
4555                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
4556             myLastCreatedElems.Append(newElem);
4557             if ( aShapeId )
4558               aMesh->SetMeshElementOnShape( newElem, aShapeId );
4559             // 2. : reverse a bottom
4560             uniqueNodes[ 0 ] = curNodes [ 1 ];
4561             uniqueNodes[ 1 ] = curNodes [ 0 ];
4562             nbUniqueNodes = 4;
4563           }
4564           else
4565             isOk = false;
4566         }
4567         else
4568           isOk = false;
4569         break;
4570       case 8: { 
4571         if(elem->IsQuadratic()) { // Quadratic quadrangle
4572           //   1    5    2
4573           //    +---+---+
4574           //    |       |
4575           //    |       |
4576           //   4+       +6
4577           //    |       |
4578           //    |       |
4579           //    +---+---+
4580           //   0    7    3
4581           isOk = false;
4582           if(nbRepl==3) {
4583             nbUniqueNodes = 6;
4584             if( iRepl[0]==0 && iRepl[1]==1 && iRepl[2]==4 ) {
4585               uniqueNodes[0] = curNodes[0];
4586               uniqueNodes[1] = curNodes[2];
4587               uniqueNodes[2] = curNodes[3];
4588               uniqueNodes[3] = curNodes[5];
4589               uniqueNodes[4] = curNodes[6];
4590               uniqueNodes[5] = curNodes[7];
4591               isOk = true;
4592             }
4593             if( iRepl[0]==0 && iRepl[1]==3 && iRepl[2]==7 ) {
4594               uniqueNodes[0] = curNodes[0];
4595               uniqueNodes[1] = curNodes[1];
4596               uniqueNodes[2] = curNodes[2];
4597               uniqueNodes[3] = curNodes[4];
4598               uniqueNodes[4] = curNodes[5];
4599               uniqueNodes[5] = curNodes[6];
4600               isOk = true;
4601             }
4602             if( iRepl[0]==0 && iRepl[1]==4 && iRepl[2]==7 ) {
4603               uniqueNodes[0] = curNodes[1];
4604               uniqueNodes[1] = curNodes[2];
4605               uniqueNodes[2] = curNodes[3];
4606               uniqueNodes[3] = curNodes[5];
4607               uniqueNodes[4] = curNodes[6];
4608               uniqueNodes[5] = curNodes[0];
4609               isOk = true;
4610             }
4611             if( iRepl[0]==1 && iRepl[1]==2 && iRepl[2]==5 ) {
4612               uniqueNodes[0] = curNodes[0];
4613               uniqueNodes[1] = curNodes[1];
4614               uniqueNodes[2] = curNodes[3];
4615               uniqueNodes[3] = curNodes[4];
4616               uniqueNodes[4] = curNodes[6];
4617               uniqueNodes[5] = curNodes[7];
4618               isOk = true;
4619             }
4620             if( iRepl[0]==1 && iRepl[1]==4 && iRepl[2]==5 ) {
4621               uniqueNodes[0] = curNodes[0];
4622               uniqueNodes[1] = curNodes[2];
4623               uniqueNodes[2] = curNodes[3];
4624               uniqueNodes[3] = curNodes[1];
4625               uniqueNodes[4] = curNodes[6];
4626               uniqueNodes[5] = curNodes[7];
4627               isOk = true;
4628             }
4629             if( iRepl[0]==2 && iRepl[1]==3 && iRepl[2]==6 ) {
4630               uniqueNodes[0] = curNodes[0];
4631               uniqueNodes[1] = curNodes[1];
4632               uniqueNodes[2] = curNodes[2];
4633               uniqueNodes[3] = curNodes[4];
4634               uniqueNodes[4] = curNodes[5];
4635               uniqueNodes[5] = curNodes[7];
4636               isOk = true;
4637             }
4638             if( iRepl[0]==2 && iRepl[1]==5 && iRepl[2]==6 ) {
4639               uniqueNodes[0] = curNodes[0];
4640               uniqueNodes[1] = curNodes[1];
4641               uniqueNodes[2] = curNodes[3];
4642               uniqueNodes[3] = curNodes[4];
4643               uniqueNodes[4] = curNodes[2];
4644               uniqueNodes[5] = curNodes[7];
4645               isOk = true;
4646             }
4647             if( iRepl[0]==3 && iRepl[1]==6 && iRepl[2]==7 ) {
4648               uniqueNodes[0] = curNodes[0];
4649               uniqueNodes[1] = curNodes[1];
4650               uniqueNodes[2] = curNodes[2];
4651               uniqueNodes[3] = curNodes[4];
4652               uniqueNodes[4] = curNodes[5];
4653               uniqueNodes[5] = curNodes[3];
4654               isOk = true;
4655             }
4656           }
4657           break;
4658         }
4659         //////////////////////////////////// HEXAHEDRON
4660         isOk = false;
4661         SMDS_VolumeTool hexa (elem);
4662         hexa.SetExternalNormal();
4663         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
4664           //////////////////////// ---> tetrahedron
4665           for ( int iFace = 0; iFace < 6; iFace++ ) {
4666             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
4667             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
4668                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
4669                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
4670               // one face turns into a point ...
4671               int iOppFace = hexa.GetOppFaceIndex( iFace );
4672               ind = hexa.GetFaceNodesIndices( iOppFace );
4673               int nbStick = 0;
4674               iUnique = 2; // reverse a tetrahedron bottom
4675               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
4676                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
4677                   nbStick++;
4678                 else if ( iUnique >= 0 )
4679                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
4680               }
4681               if ( nbStick == 1 ) {
4682                 // ... and the opposite one - into a triangle.
4683                 // set a top node
4684                 ind = hexa.GetFaceNodesIndices( iFace );
4685                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
4686                 isOk = true;
4687               }
4688               break;
4689             }
4690           }
4691         }
4692         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
4693           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
4694           for ( int iFace = 0; iFace < 6; iFace++ ) {
4695             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
4696             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
4697                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
4698                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
4699               // one face turns into a point ...
4700               int iOppFace = hexa.GetOppFaceIndex( iFace );
4701               ind = hexa.GetFaceNodesIndices( iOppFace );
4702               int nbStick = 0;
4703               iUnique = 2;  // reverse a tetrahedron 1 bottom
4704               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
4705                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
4706                   nbStick++;
4707                 else if ( iUnique >= 0 )
4708                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
4709               }
4710               if ( nbStick == 0 ) {
4711                 // ... and the opposite one is a quadrangle
4712                 // set a top node
4713                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
4714                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
4715                 nbUniqueNodes = 4;
4716                 // tetrahedron 2
4717                 SMDS_MeshElement* newElem =
4718                   aMesh->AddVolume(curNodes[ind[ 0 ]],
4719                                    curNodes[ind[ 3 ]],
4720                                    curNodes[ind[ 2 ]],
4721                                    curNodes[indTop[ 0 ]]);
4722                 myLastCreatedElems.Append(newElem);
4723                 if ( aShapeId )
4724                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
4725                 isOk = true;
4726               }
4727               break;
4728             }
4729           }
4730         }
4731         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
4732           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
4733           // find indices of quad and tri faces
4734           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
4735           for ( iFace = 0; iFace < 6; iFace++ ) {
4736             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
4737             nodeSet.clear();
4738             for ( iCur = 0; iCur < 4; iCur++ )
4739               nodeSet.insert( curNodes[ind[ iCur ]] );
4740             nbUniqueNodes = nodeSet.size();
4741             if ( nbUniqueNodes == 3 )
4742               iTriFace[ nbTri++ ] = iFace;
4743             else if ( nbUniqueNodes == 4 )
4744               iQuadFace[ nbQuad++ ] = iFace;
4745           }
4746           if (nbQuad == 2 && nbTri == 4 &&
4747               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
4748             // 2 opposite quadrangles stuck with a diagonal;
4749             // sample groups of merged indices: (0-4)(2-6)
4750             // --------------------------------------------> 2 tetrahedrons
4751             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
4752             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
4753             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
4754             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
4755                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
4756               // stuck with 0-2 diagonal
4757               i0  = ind1[ 3 ];
4758               i1d = ind1[ 0 ];
4759               i2  = ind1[ 1 ];
4760               i3d = ind1[ 2 ];
4761               i0t = ind2[ 1 ];
4762               i2t = ind2[ 3 ];
4763             }
4764             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
4765                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
4766               // stuck with 1-3 diagonal
4767               i0  = ind1[ 0 ];
4768               i1d = ind1[ 1 ];
4769               i2  = ind1[ 2 ];
4770               i3d = ind1[ 3 ];
4771               i0t = ind2[ 0 ];
4772               i2t = ind2[ 1 ];
4773             }
4774             else {
4775               ASSERT(0);
4776             }
4777             // tetrahedron 1
4778             uniqueNodes[ 0 ] = curNodes [ i0 ];
4779             uniqueNodes[ 1 ] = curNodes [ i1d ];
4780             uniqueNodes[ 2 ] = curNodes [ i3d ];
4781             uniqueNodes[ 3 ] = curNodes [ i0t ];
4782             nbUniqueNodes = 4;
4783             // tetrahedron 2
4784             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
4785                                                          curNodes[ i2 ],
4786                                                          curNodes[ i3d ],
4787                                                          curNodes[ i2t ]);
4788             myLastCreatedElems.Append(newElem);
4789             if ( aShapeId )
4790               aMesh->SetMeshElementOnShape( newElem, aShapeId );
4791             isOk = true;
4792           }
4793           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
4794                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
4795             // --------------------------------------------> prism
4796             // find 2 opposite triangles
4797             nbUniqueNodes = 6;
4798             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
4799               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
4800                 // find indices of kept and replaced nodes
4801                 // and fill unique nodes of 2 opposite triangles
4802                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
4803                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
4804                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
4805                 // fill unique nodes
4806                 iUnique = 0;
4807                 isOk = true;
4808                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
4809                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
4810                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
4811                   if ( n == nInit ) {
4812                     // iCur of a linked node of the opposite face (make normals co-directed):
4813                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
4814                     // check that correspondent corners of triangles are linked
4815                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
4816                       isOk = false;
4817                     else {
4818                       uniqueNodes[ iUnique ] = n;
4819                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
4820                       iUnique++;
4821                     }
4822                   }
4823                 }
4824                 break;
4825               }
4826             }
4827           }
4828         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
4829         break;
4830       } // HEXAHEDRON
4831
4832       default:
4833         isOk = false;
4834       } // switch ( nbNodes )
4835
4836     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
4837
4838     if ( isOk ) {
4839       if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
4840         // Change nodes of polyedre
4841         const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4842           static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
4843         if (aPolyedre) {
4844           int nbFaces = aPolyedre->NbFaces();
4845
4846           vector<const SMDS_MeshNode *> poly_nodes;
4847           vector<int> quantities (nbFaces);
4848
4849           for (int iface = 1; iface <= nbFaces; iface++) {
4850             int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4851             quantities[iface - 1] = nbFaceNodes;
4852
4853             for (inode = 1; inode <= nbFaceNodes; inode++) {
4854               const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
4855
4856               TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
4857               if (nnIt != nodeNodeMap.end()) { // curNode sticks
4858                 curNode = (*nnIt).second;
4859               }
4860               poly_nodes.push_back(curNode);
4861             }
4862           }
4863           aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
4864         }
4865       }
4866       else {
4867         // Change regular element or polygon
4868         aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
4869       }
4870     }
4871     else {
4872       // Remove invalid regular element or invalid polygon
4873       rmElemIds.push_back( elem->GetID() );
4874     }
4875
4876   } // loop on elements
4877
4878   // Remove equal nodes and bad elements
4879
4880   Remove( rmNodeIds, true );
4881   Remove( rmElemIds, false );
4882
4883 }
4884
4885
4886 // =================================================
4887 // class   : SortableElement
4888 // purpose : auxilary
4889 // =================================================
4890 class SortableElement : public set <const SMDS_MeshElement*>
4891 {
4892  public:
4893
4894   SortableElement( const SMDS_MeshElement* theElem )
4895     {
4896       myID = theElem->GetID();
4897       SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
4898       while ( nodeIt->more() )
4899         this->insert( nodeIt->next() );
4900     }
4901
4902   const long GetID() const
4903     { return myID; }
4904
4905   void SetID(const long anID) const
4906     { myID = anID; }
4907
4908
4909  private:
4910   mutable long myID;
4911 };
4912
4913
4914 //=======================================================================
4915 //function : MergeEqualElements
4916 //purpose  : Remove all but one of elements built on the same nodes.
4917 //=======================================================================
4918
4919 void SMESH_MeshEditor::MergeEqualElements()
4920 {
4921   myLastCreatedElems.Clear();
4922   myLastCreatedNodes.Clear();
4923
4924   SMESHDS_Mesh* aMesh = GetMeshDS();
4925
4926   SMDS_EdgeIteratorPtr   eIt = aMesh->edgesIterator();
4927   SMDS_FaceIteratorPtr   fIt = aMesh->facesIterator();
4928   SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
4929
4930   list< int > rmElemIds; // IDs of elems to remove
4931
4932   for ( int iDim = 1; iDim <= 3; iDim++ ) {
4933
4934     set< SortableElement > setOfNodeSet;
4935     while ( 1 ) {
4936       // get next element
4937       const SMDS_MeshElement* elem = 0;
4938       if ( iDim == 1 ) {
4939         if ( eIt->more() ) elem = eIt->next();
4940       } else if ( iDim == 2 ) {
4941         if ( fIt->more() ) elem = fIt->next();
4942       } else {
4943         if ( vIt->more() ) elem = vIt->next();
4944       }
4945       if ( !elem ) break;
4946
4947       SortableElement SE(elem);
4948
4949       // check uniqueness
4950       pair< set<SortableElement>::iterator, bool> pp = setOfNodeSet.insert(SE);
4951       if( !(pp.second) ) {
4952         set<SortableElement>::iterator itSE = pp.first;
4953         SortableElement SEold = *itSE;
4954         if( SEold.GetID() > SE.GetID() ) {
4955           rmElemIds.push_back( SEold.GetID() );
4956           (*itSE).SetID(SE.GetID());
4957         }
4958         else {
4959           rmElemIds.push_back( SE.GetID() );
4960         }
4961       }
4962     }
4963   }
4964
4965   Remove( rmElemIds, false );
4966 }
4967
4968 //=======================================================================
4969 //function : FindFaceInSet
4970 //purpose  : Return a face having linked nodes n1 and n2 and which is
4971 //           - not in avoidSet,
4972 //           - in elemSet provided that !elemSet.empty()
4973 //=======================================================================
4974
4975 const SMDS_MeshElement*
4976   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*                n1,
4977                                   const SMDS_MeshNode*                n2,
4978                                   const map<int,const SMDS_MeshElement*>& elemSet,
4979                                   const map<int,const SMDS_MeshElement*>& avoidSet)
4980
4981 {
4982   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
4983   while ( invElemIt->more() ) { // loop on inverse elements of n1
4984     const SMDS_MeshElement* elem = invElemIt->next();
4985     if (elem->GetType() != SMDSAbs_Face ||
4986         avoidSet.find( elem->GetID() ) != avoidSet.end() )
4987       continue;
4988     if ( !elemSet.empty() && elemSet.find( elem->GetID() ) == elemSet.end())
4989       continue;
4990     // get face nodes and find index of n1
4991     int i1, nbN = elem->NbNodes(), iNode = 0;
4992     const SMDS_MeshNode* faceNodes[ nbN ], *n;
4993     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4994     while ( nIt->more() ) {
4995       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4996       if ( faceNodes[ iNode++ ] == n1 )
4997         i1 = iNode - 1;
4998     }
4999     // find a n2 linked to n1
5000     if(!elem->IsQuadratic()) {
5001       for ( iNode = 0; iNode < 2; iNode++ ) {
5002         if ( iNode ) // node before n1
5003           n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
5004         else         // node after n1
5005           n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
5006         if ( n == n2 )
5007           return elem;
5008       }
5009     }
5010     else { // analysis for quadratic elements
5011       bool IsFind = false;
5012       // check using only corner nodes
5013       for ( iNode = 0; iNode < 2; iNode++ ) {
5014         if ( iNode ) // node before n1
5015           n = faceNodes[ i1 == 0 ? nbN/2 - 1 : i1 - 1 ];
5016         else         // node after n1
5017           n = faceNodes[ i1 + 1 == nbN/2 ? 0 : i1 + 1 ];
5018         if ( n == n2 )
5019           IsFind = true;
5020       }
5021       if(IsFind) {
5022         return elem;
5023       }
5024       else {
5025         // check using all nodes
5026         const SMDS_QuadraticFaceOfNodes* F =
5027           static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5028         // use special nodes iterator
5029         iNode = 0;
5030         SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5031         while ( anIter->more() ) {
5032           faceNodes[iNode] = static_cast<const SMDS_MeshNode*>(anIter->next());
5033           if ( faceNodes[ iNode++ ] == n1 )
5034             i1 = iNode - 1;
5035         }
5036         for ( iNode = 0; iNode < 2; iNode++ ) {
5037           if ( iNode ) // node before n1
5038             n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
5039           else         // node after n1
5040             n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
5041           if ( n == n2 ) {
5042             return elem;
5043           }
5044         }
5045       }
5046     } // end analysis for quadratic elements
5047   }
5048   return 0;
5049 }
5050
5051 //=======================================================================
5052 //function : findAdjacentFace
5053 //purpose  :
5054 //=======================================================================
5055
5056 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
5057                                                 const SMDS_MeshNode* n2,
5058                                                 const SMDS_MeshElement* elem)
5059 {
5060   map<int,const SMDS_MeshElement*> elemSet, avoidSet;
5061   if ( elem )
5062     avoidSet.insert ( make_pair(elem->GetID(),elem) );
5063   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
5064 }
5065
5066 //=======================================================================
5067 //function : findFreeBorder
5068 //purpose  :
5069 //=======================================================================
5070
5071 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
5072
5073 static bool findFreeBorder (const SMDS_MeshNode*                theFirstNode,
5074                             const SMDS_MeshNode*                theSecondNode,
5075                             const SMDS_MeshNode*                theLastNode,
5076                             list< const SMDS_MeshNode* > &      theNodes,
5077                             list< const SMDS_MeshElement* > &   theFaces)
5078 {
5079   if ( !theFirstNode || !theSecondNode )
5080     return false;
5081   // find border face between theFirstNode and theSecondNode
5082   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
5083   if ( !curElem )
5084     return false;
5085
5086   theFaces.push_back( curElem );
5087   theNodes.push_back( theFirstNode );
5088   theNodes.push_back( theSecondNode );
5089
5090   //vector<const SMDS_MeshNode*> nodes;
5091   const SMDS_MeshNode *nIgnore = theFirstNode, *nStart = theSecondNode;
5092   set < const SMDS_MeshElement* > foundElems;
5093   bool needTheLast = ( theLastNode != 0 );
5094
5095   while ( nStart != theLastNode ) {
5096     if ( nStart == theFirstNode )
5097       return !needTheLast;
5098
5099     // find all free border faces sharing form nStart
5100
5101     list< const SMDS_MeshElement* > curElemList;
5102     list< const SMDS_MeshNode* > nStartList;
5103     SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
5104     while ( invElemIt->more() ) {
5105       const SMDS_MeshElement* e = invElemIt->next();
5106       if ( e == curElem || foundElems.insert( e ).second ) {
5107         // get nodes
5108         int iNode = 0, nbNodes = e->NbNodes();
5109         const SMDS_MeshNode* nodes[nbNodes+1];
5110         if(e->IsQuadratic()) {
5111           const SMDS_QuadraticFaceOfNodes* F =
5112             static_cast<const SMDS_QuadraticFaceOfNodes*>(e);
5113           // use special nodes iterator
5114           SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5115           while( anIter->more() ) {
5116             nodes[ iNode++ ] = anIter->next();
5117           }
5118         }
5119         else {
5120           SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5121           while ( nIt->more() )
5122             nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5123         }
5124         nodes[ iNode ] = nodes[ 0 ];
5125         // check 2 links
5126         for ( iNode = 0; iNode < nbNodes; iNode++ )
5127           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
5128                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
5129               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
5130           {
5131             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
5132             curElemList.push_back( e );
5133           }
5134       }
5135     }
5136     // analyse the found
5137
5138     int nbNewBorders = curElemList.size();
5139     if ( nbNewBorders == 0 ) {
5140       // no free border furthermore
5141       return !needTheLast;
5142     }
5143     else if ( nbNewBorders == 1 ) {
5144       // one more element found
5145       nIgnore = nStart;
5146       nStart = nStartList.front();
5147       curElem = curElemList.front();
5148       theFaces.push_back( curElem );
5149       theNodes.push_back( nStart );
5150     }
5151     else {
5152       // several continuations found
5153       list< const SMDS_MeshElement* >::iterator curElemIt;
5154       list< const SMDS_MeshNode* >::iterator nStartIt;
5155       // check if one of them reached the last node
5156       if ( needTheLast ) {
5157         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5158              curElemIt!= curElemList.end();
5159              curElemIt++, nStartIt++ )
5160           if ( *nStartIt == theLastNode ) {
5161             theFaces.push_back( *curElemIt );
5162             theNodes.push_back( *nStartIt );
5163             return true;
5164           }
5165       }
5166       // find the best free border by the continuations
5167       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
5168       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
5169       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5170            curElemIt!= curElemList.end();
5171            curElemIt++, nStartIt++ )
5172       {
5173         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
5174         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
5175         // find one more free border
5176         if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
5177           cNL->clear();
5178           cFL->clear();
5179         }
5180         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
5181           // choice: clear a worse one
5182           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
5183           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
5184           contNodes[ iWorse ].clear();
5185           contFaces[ iWorse ].clear();
5186         }
5187       }
5188       if ( contNodes[0].empty() && contNodes[1].empty() )
5189         return false;
5190
5191       // append the best free border
5192       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
5193       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
5194       theNodes.pop_back(); // remove nIgnore
5195       theNodes.pop_back(); // remove nStart
5196       theFaces.pop_back(); // remove curElem
5197       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
5198       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
5199       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
5200       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
5201       return true;
5202
5203     } // several continuations found
5204   } // while ( nStart != theLastNode )
5205
5206   return true;
5207 }
5208
5209 //=======================================================================
5210 //function : CheckFreeBorderNodes
5211 //purpose  : Return true if the tree nodes are on a free border
5212 //=======================================================================
5213
5214 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
5215                                             const SMDS_MeshNode* theNode2,
5216                                             const SMDS_MeshNode* theNode3)
5217 {
5218   list< const SMDS_MeshNode* > nodes;
5219   list< const SMDS_MeshElement* > faces;
5220   return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
5221 }
5222
5223 //=======================================================================
5224 //function : SewFreeBorder
5225 //purpose  :
5226 //=======================================================================
5227
5228 SMESH_MeshEditor::Sew_Error
5229   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
5230                                    const SMDS_MeshNode* theBordSecondNode,
5231                                    const SMDS_MeshNode* theBordLastNode,
5232                                    const SMDS_MeshNode* theSideFirstNode,
5233                                    const SMDS_MeshNode* theSideSecondNode,
5234                                    const SMDS_MeshNode* theSideThirdNode,
5235                                    const bool           theSideIsFreeBorder,
5236                                    const bool           toCreatePolygons,
5237                                    const bool           toCreatePolyedrs)
5238 {
5239   myLastCreatedElems.Clear();
5240   myLastCreatedNodes.Clear();
5241
5242   MESSAGE("::SewFreeBorder()");
5243   Sew_Error aResult = SEW_OK;
5244
5245   // ====================================
5246   //    find side nodes and elements
5247   // ====================================
5248
5249   list< const SMDS_MeshNode* > nSide[ 2 ];
5250   list< const SMDS_MeshElement* > eSide[ 2 ];
5251   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
5252   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
5253
5254   // Free border 1
5255   // --------------
5256   if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
5257                       nSide[0], eSide[0])) {
5258     MESSAGE(" Free Border 1 not found " );
5259     aResult = SEW_BORDER1_NOT_FOUND;
5260   }
5261   if (theSideIsFreeBorder) {
5262     // Free border 2
5263     // --------------
5264     if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
5265                         nSide[1], eSide[1])) {
5266       MESSAGE(" Free Border 2 not found " );
5267       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
5268     }
5269   }
5270   if ( aResult != SEW_OK )
5271     return aResult;
5272
5273   if (!theSideIsFreeBorder) {
5274     // Side 2
5275     // --------------
5276
5277     // -------------------------------------------------------------------------
5278     // Algo:
5279     // 1. If nodes to merge are not coincident, move nodes of the free border
5280     //    from the coord sys defined by the direction from the first to last
5281     //    nodes of the border to the correspondent sys of the side 2
5282     // 2. On the side 2, find the links most co-directed with the correspondent
5283     //    links of the free border
5284     // -------------------------------------------------------------------------
5285
5286     // 1. Since sewing may brake if there are volumes to split on the side 2,
5287     //    we wont move nodes but just compute new coordinates for them
5288     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
5289     TNodeXYZMap nBordXYZ;
5290     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
5291     list< const SMDS_MeshNode* >::iterator nBordIt;
5292
5293     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
5294     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
5295     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
5296     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
5297     double tol2 = 1.e-8;
5298     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
5299     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 ) {
5300       // Need node movement.
5301
5302       // find X and Z axes to create trsf
5303       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
5304       gp_Vec X = Zs ^ Zb;
5305       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
5306         // Zb || Zs
5307         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
5308
5309       // coord systems
5310       gp_Ax3 toBordAx( Pb1, Zb, X );
5311       gp_Ax3 fromSideAx( Ps1, Zs, X );
5312       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
5313       // set trsf
5314       gp_Trsf toBordSys, fromSide2Sys;
5315       toBordSys.SetTransformation( toBordAx );
5316       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
5317       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
5318
5319       // move
5320       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5321         const SMDS_MeshNode* n = *nBordIt;
5322         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
5323         toBordSys.Transforms( xyz );
5324         fromSide2Sys.Transforms( xyz );
5325         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
5326       }
5327     }
5328     else {
5329       // just insert nodes XYZ in the nBordXYZ map
5330       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5331         const SMDS_MeshNode* n = *nBordIt;
5332         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
5333       }
5334     }
5335
5336     // 2. On the side 2, find the links most co-directed with the correspondent
5337     //    links of the free border
5338
5339     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
5340     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
5341     sideNodes.push_back( theSideFirstNode );
5342
5343     bool hasVolumes = false;
5344     LinkID_Gen aLinkID_Gen( GetMeshDS() );
5345     set<long> foundSideLinkIDs, checkedLinkIDs;
5346     SMDS_VolumeTool volume;
5347     //const SMDS_MeshNode* faceNodes[ 4 ];
5348
5349     const SMDS_MeshNode*    sideNode;
5350     const SMDS_MeshElement* sideElem;
5351     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
5352     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
5353     nBordIt = bordNodes.begin();
5354     nBordIt++;
5355     // border node position and border link direction to compare with
5356     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
5357     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
5358     // choose next side node by link direction or by closeness to
5359     // the current border node:
5360     bool searchByDir = ( *nBordIt != theBordLastNode );
5361     do {
5362       // find the next node on the Side 2
5363       sideNode = 0;
5364       double maxDot = -DBL_MAX, minDist = DBL_MAX;
5365       long linkID;
5366       checkedLinkIDs.clear();
5367       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
5368
5369       SMDS_ElemIteratorPtr invElemIt
5370         = prevSideNode->GetInverseElementIterator();
5371       while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
5372         const SMDS_MeshElement* elem = invElemIt->next();
5373         // prepare data for a loop on links, of a face or a volume
5374         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
5375         const SMDS_MeshNode* faceNodes[ nbNodes ];
5376         bool isVolume = volume.Set( elem );
5377         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
5378         if ( isVolume ) // --volume
5379           hasVolumes = true;
5380         //else if ( nbNodes > 2 ) { // --face
5381         else if ( elem->GetType()==SMDSAbs_Face ) { // --face
5382           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
5383           if(elem->IsQuadratic()) {
5384             const SMDS_QuadraticFaceOfNodes* F =
5385               static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5386             // use special nodes iterator
5387             SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5388             while( anIter->more() ) {
5389               nodes[ iNode ] = anIter->next();
5390               if ( nodes[ iNode++ ] == prevSideNode )
5391                 iPrevNode = iNode - 1;
5392             }
5393           }
5394           else {
5395             SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
5396             while ( nIt->more() ) {
5397               nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5398               if ( nodes[ iNode++ ] == prevSideNode )
5399                 iPrevNode = iNode - 1;
5400             }
5401           }
5402           // there are 2 links to check
5403           nbNodes = 2;
5404         }
5405         else // --edge
5406           continue;
5407         // loop on links, to be precise, on the second node of links
5408         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
5409           const SMDS_MeshNode* n = nodes[ iNode ];
5410           if ( isVolume ) {
5411             if ( !volume.IsLinked( n, prevSideNode ))
5412               continue;
5413           }
5414           else {
5415             if ( iNode ) // a node before prevSideNode
5416               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
5417             else         // a node after prevSideNode
5418               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
5419           }
5420           // check if this link was already used
5421           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
5422           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
5423           if (!isJustChecked &&
5424               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
5425             // test a link geometrically
5426             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
5427             bool linkIsBetter = false;
5428             double dot, dist;
5429             if ( searchByDir ) { // choose most co-directed link
5430               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
5431               linkIsBetter = ( dot > maxDot );
5432             }
5433             else { // choose link with the node closest to bordPos
5434               dist = ( nextXYZ - bordPos ).SquareModulus();
5435               linkIsBetter = ( dist < minDist );
5436             }
5437             if ( linkIsBetter ) {
5438               maxDot = dot;
5439               minDist = dist;
5440               linkID = iLink;
5441               sideNode = n;
5442               sideElem = elem;
5443             }
5444           }
5445         }
5446       } // loop on inverse elements of prevSideNode
5447
5448       if ( !sideNode ) {
5449         MESSAGE(" Cant find path by links of the Side 2 ");
5450         return SEW_BAD_SIDE_NODES;
5451       }
5452       sideNodes.push_back( sideNode );
5453       sideElems.push_back( sideElem );
5454       foundSideLinkIDs.insert ( linkID );
5455       prevSideNode = sideNode;
5456
5457       if ( *nBordIt == theBordLastNode )
5458         searchByDir = false;
5459       else {
5460         // find the next border link to compare with
5461         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
5462         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5463         while ( *nBordIt != theBordLastNode && !searchByDir ) {
5464           prevBordNode = *nBordIt;
5465           nBordIt++;
5466           bordPos = nBordXYZ[ *nBordIt ];
5467           bordDir = bordPos - nBordXYZ[ prevBordNode ];
5468           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5469         }
5470       }
5471     }
5472     while ( sideNode != theSideSecondNode );
5473
5474     if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
5475       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
5476       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
5477     }
5478   } // end nodes search on the side 2
5479
5480   // ============================
5481   // sew the border to the side 2
5482   // ============================
5483
5484   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
5485   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
5486
5487   TListOfListOfNodes nodeGroupsToMerge;
5488   if ( nbNodes[0] == nbNodes[1] ||
5489       ( theSideIsFreeBorder && !theSideThirdNode)) {
5490
5491     // all nodes are to be merged
5492
5493     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
5494          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
5495          nIt[0]++, nIt[1]++ )
5496     {
5497       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
5498       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
5499       nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
5500     }
5501   }
5502   else {
5503
5504     // insert new nodes into the border and the side to get equal nb of segments
5505
5506     // get normalized parameters of nodes on the borders
5507     double param[ 2 ][ maxNbNodes ];
5508     int iNode, iBord;
5509     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
5510       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
5511       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
5512       const SMDS_MeshNode* nPrev = *nIt;
5513       double bordLength = 0;
5514       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
5515         const SMDS_MeshNode* nCur = *nIt;
5516         gp_XYZ segment (nCur->X() - nPrev->X(),
5517                         nCur->Y() - nPrev->Y(),
5518                         nCur->Z() - nPrev->Z());
5519         double segmentLen = segment.Modulus();
5520         bordLength += segmentLen;
5521         param[ iBord ][ iNode ] = bordLength;
5522         nPrev = nCur;
5523       }
5524       // normalize within [0,1]
5525       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
5526         param[ iBord ][ iNode ] /= bordLength;
5527       }
5528     }
5529
5530     // loop on border segments
5531     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
5532     int i[ 2 ] = { 0, 0 };
5533     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
5534     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
5535
5536     TElemOfNodeListMap insertMap;
5537     TElemOfNodeListMap::iterator insertMapIt;
5538     // insertMap is
5539     // key:   elem to insert nodes into
5540     // value: 2 nodes to insert between + nodes to be inserted
5541     do {
5542       bool next[ 2 ] = { false, false };
5543
5544       // find min adjacent segment length after sewing
5545       double nextParam = 10., prevParam = 0;
5546       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
5547         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
5548           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
5549         if ( i[ iBord ] > 0 )
5550           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
5551       }
5552       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
5553       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
5554       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
5555
5556       // choose to insert or to merge nodes
5557       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
5558       if ( Abs( du ) <= minSegLen * 0.2 ) {
5559         // merge
5560         // ------
5561         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
5562         const SMDS_MeshNode* n0 = *nIt[0];
5563         const SMDS_MeshNode* n1 = *nIt[1];
5564         nodeGroupsToMerge.back().push_back( n1 );
5565         nodeGroupsToMerge.back().push_back( n0 );
5566         // position of node of the border changes due to merge
5567         param[ 0 ][ i[0] ] += du;
5568         // move n1 for the sake of elem shape evaluation during insertion.
5569         // n1 will be removed by MergeNodes() anyway
5570         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
5571         next[0] = next[1] = true;
5572       }
5573       else {
5574         // insert
5575         // ------
5576         int intoBord = ( du < 0 ) ? 0 : 1;
5577         const SMDS_MeshElement* elem = *eIt[ intoBord ];
5578         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
5579         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
5580         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
5581         if ( intoBord == 1 ) {
5582           // move node of the border to be on a link of elem of the side
5583           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
5584           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
5585           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
5586           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
5587           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
5588         }
5589         insertMapIt = insertMap.find( elem );
5590         bool notFound = ( insertMapIt == insertMap.end() );
5591         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
5592         if ( otherLink ) {
5593           // insert into another link of the same element:
5594           // 1. perform insertion into the other link of the elem
5595           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
5596           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
5597           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
5598           InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
5599           // 2. perform insertion into the link of adjacent faces
5600           while (true) {
5601             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
5602             if ( adjElem )
5603               InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
5604             else
5605               break;
5606           }
5607           if (toCreatePolyedrs) {
5608             // perform insertion into the links of adjacent volumes
5609             UpdateVolumes(n12, n22, nodeList);
5610           }
5611           // 3. find an element appeared on n1 and n2 after the insertion
5612           insertMap.erase( elem );
5613           elem = findAdjacentFace( n1, n2, 0 );
5614         }
5615         if ( notFound || otherLink ) {
5616           // add element and nodes of the side into the insertMap
5617           insertMapIt = insertMap.insert
5618             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
5619           (*insertMapIt).second.push_back( n1 );
5620           (*insertMapIt).second.push_back( n2 );
5621         }
5622         // add node to be inserted into elem
5623         (*insertMapIt).second.push_back( nIns );
5624         next[ 1 - intoBord ] = true;
5625       }
5626
5627       // go to the next segment
5628       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
5629         if ( next[ iBord ] ) {
5630           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
5631             eIt[ iBord ]++;
5632           nPrev[ iBord ] = *nIt[ iBord ];
5633           nIt[ iBord ]++; i[ iBord ]++;
5634         }
5635       }
5636     }
5637     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
5638
5639     // perform insertion of nodes into elements
5640
5641     for (insertMapIt = insertMap.begin();
5642          insertMapIt != insertMap.end();
5643          insertMapIt++ )
5644     {
5645       const SMDS_MeshElement* elem = (*insertMapIt).first;
5646       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
5647       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
5648       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
5649
5650       InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
5651
5652       if ( !theSideIsFreeBorder ) {
5653         // look for and insert nodes into the faces adjacent to elem
5654         while (true) {
5655           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
5656           if ( adjElem )
5657             InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
5658           else
5659             break;
5660         }
5661       }
5662       if (toCreatePolyedrs) {
5663         // perform insertion into the links of adjacent volumes
5664         UpdateVolumes(n1, n2, nodeList);
5665       }
5666     }
5667
5668   } // end: insert new nodes
5669
5670   MergeNodes ( nodeGroupsToMerge );
5671
5672   return aResult;
5673 }
5674
5675 //=======================================================================
5676 //function : InsertNodesIntoLink
5677 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
5678 //           and theBetweenNode2 and split theElement
5679 //=======================================================================
5680
5681 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
5682                                            const SMDS_MeshNode*        theBetweenNode1,
5683                                            const SMDS_MeshNode*        theBetweenNode2,
5684                                            list<const SMDS_MeshNode*>& theNodesToInsert,
5685                                            const bool                  toCreatePoly)
5686 {
5687   if ( theFace->GetType() != SMDSAbs_Face ) return;
5688
5689   // find indices of 2 link nodes and of the rest nodes
5690   int iNode = 0, il1, il2, i3, i4;
5691   il1 = il2 = i3 = i4 = -1;
5692   const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
5693
5694   if(theFace->IsQuadratic()) {
5695     const SMDS_QuadraticFaceOfNodes* F =
5696       static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
5697     // use special nodes iterator
5698     SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5699     while( anIter->more() ) {
5700       const SMDS_MeshNode* n = anIter->next();
5701       if ( n == theBetweenNode1 )
5702         il1 = iNode;
5703       else if ( n == theBetweenNode2 )
5704         il2 = iNode;
5705       else if ( i3 < 0 )
5706         i3 = iNode;
5707       else
5708         i4 = iNode;
5709       nodes[ iNode++ ] = n;
5710     }
5711   }
5712   else {
5713     SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
5714     while ( nodeIt->more() ) {
5715       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
5716       if ( n == theBetweenNode1 )
5717         il1 = iNode;
5718       else if ( n == theBetweenNode2 )
5719         il2 = iNode;
5720       else if ( i3 < 0 )
5721         i3 = iNode;
5722       else
5723         i4 = iNode;
5724       nodes[ iNode++ ] = n;
5725     }
5726   }
5727   if ( il1 < 0 || il2 < 0 || i3 < 0 )
5728     return ;
5729
5730   // arrange link nodes to go one after another regarding the face orientation
5731   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
5732   list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
5733   if ( reverse ) {
5734     iNode = il1;
5735     il1 = il2;
5736     il2 = iNode;
5737     aNodesToInsert.reverse();
5738   }
5739   // check that not link nodes of a quadrangles are in good order
5740   int nbFaceNodes = theFace->NbNodes();
5741   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
5742     iNode = i3;
5743     i3 = i4;
5744     i4 = iNode;
5745   }
5746
5747   if (toCreatePoly || theFace->IsPoly()) {
5748
5749     iNode = 0;
5750     vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
5751
5752     // add nodes of face up to first node of link
5753     bool isFLN = false;
5754
5755     if(theFace->IsQuadratic()) {
5756       const SMDS_QuadraticFaceOfNodes* F =
5757         static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
5758       // use special nodes iterator
5759       SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5760       while( anIter->more()  && !isFLN ) {
5761         const SMDS_MeshNode* n = anIter->next();
5762         poly_nodes[iNode++] = n;
5763         if (n == nodes[il1]) {
5764           isFLN = true;
5765         }
5766       }
5767       // add nodes to insert
5768       list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5769       for (; nIt != aNodesToInsert.end(); nIt++) {
5770         poly_nodes[iNode++] = *nIt;
5771       }
5772       // add nodes of face starting from last node of link
5773       while ( anIter->more() ) {
5774         poly_nodes[iNode++] = anIter->next();
5775       }
5776     }
5777     else {
5778       SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
5779       while ( nodeIt->more() && !isFLN ) {
5780         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
5781         poly_nodes[iNode++] = n;
5782         if (n == nodes[il1]) {
5783           isFLN = true;
5784         }
5785       }
5786       // add nodes to insert
5787       list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5788       for (; nIt != aNodesToInsert.end(); nIt++) {
5789         poly_nodes[iNode++] = *nIt;
5790       }
5791       // add nodes of face starting from last node of link
5792       while ( nodeIt->more() ) {
5793         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
5794         poly_nodes[iNode++] = n;
5795       }
5796     }
5797
5798     // edit or replace the face
5799     SMESHDS_Mesh *aMesh = GetMeshDS();
5800
5801     if (theFace->IsPoly()) {
5802       aMesh->ChangePolygonNodes(theFace, poly_nodes);
5803     }
5804     else {
5805       int aShapeId = FindShape( theFace );
5806
5807       SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
5808       myLastCreatedElems.Append(newElem);
5809       if ( aShapeId && newElem )
5810         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5811
5812       aMesh->RemoveElement(theFace);
5813     }
5814     return;
5815   }
5816
5817   if( !theFace->IsQuadratic() ) {
5818
5819     // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
5820     int nbLinkNodes = 2 + aNodesToInsert.size();
5821     const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
5822     linkNodes[ 0 ] = nodes[ il1 ];
5823     linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
5824     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5825     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
5826       linkNodes[ iNode++ ] = *nIt;
5827     }
5828     // decide how to split a quadrangle: compare possible variants
5829     // and choose which of splits to be a quadrangle
5830     int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
5831     if ( nbFaceNodes == 3 ) {
5832       iBestQuad = nbSplits;
5833       i4 = i3;
5834     }
5835     else if ( nbFaceNodes == 4 ) {
5836       SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
5837       double aBestRate = DBL_MAX;
5838       for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
5839         i1 = 0; i2 = 1;
5840         double aBadRate = 0;
5841         // evaluate elements quality
5842         for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
5843           if ( iSplit == iQuad ) {
5844             SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
5845                                    linkNodes[ i2++ ],
5846                                    nodes[ i3 ],
5847                                    nodes[ i4 ]);
5848             aBadRate += getBadRate( &quad, aCrit );
5849           }
5850           else {
5851             SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
5852                                    linkNodes[ i2++ ],
5853                                    nodes[ iSplit < iQuad ? i4 : i3 ]);
5854             aBadRate += getBadRate( &tria, aCrit );
5855           }
5856         }
5857         // choice
5858         if ( aBadRate < aBestRate ) {
5859           iBestQuad = iQuad;
5860           aBestRate = aBadRate;
5861         }
5862       }
5863     }
5864     
5865     // create new elements
5866     SMESHDS_Mesh *aMesh = GetMeshDS();
5867     int aShapeId = FindShape( theFace );
5868     
5869     i1 = 0; i2 = 1;
5870     for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
5871       SMDS_MeshElement* newElem = 0;
5872       if ( iSplit == iBestQuad )
5873         newElem = aMesh->AddFace (linkNodes[ i1++ ],
5874                                   linkNodes[ i2++ ],
5875                                   nodes[ i3 ],
5876                                   nodes[ i4 ]);
5877       else
5878         newElem = aMesh->AddFace (linkNodes[ i1++ ],
5879                                   linkNodes[ i2++ ],
5880                                   nodes[ iSplit < iBestQuad ? i4 : i3 ]);
5881       myLastCreatedElems.Append(newElem);
5882       if ( aShapeId && newElem )
5883         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5884     }
5885     
5886     // change nodes of theFace
5887     const SMDS_MeshNode* newNodes[ 4 ];
5888     newNodes[ 0 ] = linkNodes[ i1 ];
5889     newNodes[ 1 ] = linkNodes[ i2 ];
5890     newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
5891     newNodes[ 3 ] = nodes[ i4 ];
5892     aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
5893   } // end if(!theFace->IsQuadratic())
5894   else { // theFace is quadratic
5895     // we have to split theFace on simple triangles and one simple quadrangle
5896     int tmp = il1/2;
5897     int nbshift = tmp*2;
5898     // shift nodes in nodes[] by nbshift
5899     int i,j;
5900     for(i=0; i<nbshift; i++) {
5901       const SMDS_MeshNode* n = nodes[0];
5902       for(j=0; j<nbFaceNodes-1; j++) {
5903         nodes[j] = nodes[j+1];
5904       }
5905       nodes[nbFaceNodes-1] = n;
5906     }
5907     il1 = il1 - nbshift;
5908     // now have to insert nodes between n0 and n1 or n1 and n2 (see below)
5909     //   n0      n1     n2    n0      n1     n2
5910     //     +-----+-----+        +-----+-----+ 
5911     //      \         /         |           |
5912     //       \       /          |           |
5913     //      n5+     +n3       n7+           +n3
5914     //         \   /            |           |
5915     //          \ /             |           |
5916     //           +              +-----+-----+
5917     //           n4           n6      n5     n4
5918
5919     // create new elements
5920     SMESHDS_Mesh *aMesh = GetMeshDS();
5921     int aShapeId = FindShape( theFace );
5922
5923     int n1,n2,n3;
5924     if(nbFaceNodes==6) { // quadratic triangle
5925       SMDS_MeshElement* newElem =
5926         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
5927       myLastCreatedElems.Append(newElem);
5928       if ( aShapeId && newElem )
5929         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5930       if(theFace->IsMediumNode(nodes[il1])) {
5931         // create quadrangle
5932         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[5]);
5933         myLastCreatedElems.Append(newElem);
5934         if ( aShapeId && newElem )
5935           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5936         n1 = 1;
5937         n2 = 2;
5938         n3 = 3;
5939       }
5940       else {
5941         // create quadrangle
5942         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[5]);
5943         myLastCreatedElems.Append(newElem);
5944         if ( aShapeId && newElem )
5945           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5946         n1 = 0;
5947         n2 = 1;
5948         n3 = 5;
5949       }
5950     }
5951     else { // nbFaceNodes==8 - quadratic quadrangle
5952       SMDS_MeshElement* newElem =
5953         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
5954       myLastCreatedElems.Append(newElem);
5955       if ( aShapeId && newElem )
5956         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5957       newElem = aMesh->AddFace(nodes[5],nodes[6],nodes[7]);
5958       myLastCreatedElems.Append(newElem);
5959       if ( aShapeId && newElem )
5960         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5961       newElem = aMesh->AddFace(nodes[5],nodes[7],nodes[3]);
5962       myLastCreatedElems.Append(newElem);
5963       if ( aShapeId && newElem )
5964         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5965       if(theFace->IsMediumNode(nodes[il1])) {
5966         // create quadrangle
5967         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[7]);
5968         myLastCreatedElems.Append(newElem);
5969         if ( aShapeId && newElem )
5970           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5971         n1 = 1;
5972         n2 = 2;
5973         n3 = 3;
5974       }
5975       else {
5976         // create quadrangle
5977         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[7]);
5978         myLastCreatedElems.Append(newElem);
5979         if ( aShapeId && newElem )
5980           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5981         n1 = 0;
5982         n2 = 1;
5983         n3 = 7;
5984       }
5985     }
5986     // create needed triangles using n1,n2,n3 and inserted nodes
5987     int nbn = 2 + aNodesToInsert.size();
5988     const SMDS_MeshNode* aNodes[nbn];
5989     aNodes[0] = nodes[n1];
5990     aNodes[nbn-1] = nodes[n2];
5991     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5992     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
5993       aNodes[iNode++] = *nIt;
5994     }
5995     for(i=1; i<nbn; i++) {
5996       SMDS_MeshElement* newElem =
5997         aMesh->AddFace(aNodes[i-1],aNodes[i],nodes[n3]);
5998       myLastCreatedElems.Append(newElem);
5999       if ( aShapeId && newElem )
6000         aMesh->SetMeshElementOnShape( newElem, aShapeId );
6001     }
6002     // remove old quadratic face
6003     aMesh->RemoveElement(theFace);
6004   }
6005 }
6006
6007 //=======================================================================
6008 //function : UpdateVolumes
6009 //purpose  :
6010 //=======================================================================
6011 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode*        theBetweenNode1,
6012                                       const SMDS_MeshNode*        theBetweenNode2,
6013                                       list<const SMDS_MeshNode*>& theNodesToInsert)
6014 {
6015   myLastCreatedElems.Clear();
6016   myLastCreatedNodes.Clear();
6017
6018   SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
6019   while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
6020     const SMDS_MeshElement* elem = invElemIt->next();
6021     if (elem->GetType() != SMDSAbs_Volume)
6022       continue;
6023
6024     // check, if current volume has link theBetweenNode1 - theBetweenNode2
6025     SMDS_VolumeTool aVolume (elem);
6026     if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
6027       continue;
6028
6029     // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
6030     int iface, nbFaces = aVolume.NbFaces();
6031     vector<const SMDS_MeshNode *> poly_nodes;
6032     vector<int> quantities (nbFaces);
6033
6034     for (iface = 0; iface < nbFaces; iface++) {
6035       int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
6036       // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
6037       const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
6038
6039       for (int inode = 0; inode < nbFaceNodes; inode++) {
6040         poly_nodes.push_back(faceNodes[inode]);
6041
6042         if (nbInserted == 0) {
6043           if (faceNodes[inode] == theBetweenNode1) {
6044             if (faceNodes[inode + 1] == theBetweenNode2) {
6045               nbInserted = theNodesToInsert.size();
6046
6047               // add nodes to insert
6048               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
6049               for (; nIt != theNodesToInsert.end(); nIt++) {
6050                 poly_nodes.push_back(*nIt);
6051               }
6052             }
6053           }
6054           else if (faceNodes[inode] == theBetweenNode2) {
6055             if (faceNodes[inode + 1] == theBetweenNode1) {
6056               nbInserted = theNodesToInsert.size();
6057
6058               // add nodes to insert in reversed order
6059               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
6060               nIt--;
6061               for (; nIt != theNodesToInsert.begin(); nIt--) {
6062                 poly_nodes.push_back(*nIt);
6063               }
6064               poly_nodes.push_back(*nIt);
6065             }
6066           }
6067           else {
6068           }
6069         }
6070       }
6071       quantities[iface] = nbFaceNodes + nbInserted;
6072     }
6073
6074     // Replace or update the volume
6075     SMESHDS_Mesh *aMesh = GetMeshDS();
6076
6077     if (elem->IsPoly()) {
6078       aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
6079
6080     }
6081     else {
6082       int aShapeId = FindShape( elem );
6083
6084       SMDS_MeshElement* newElem =
6085         aMesh->AddPolyhedralVolume(poly_nodes, quantities);
6086       myLastCreatedElems.Append(newElem);
6087       if (aShapeId && newElem)
6088         aMesh->SetMeshElementOnShape(newElem, aShapeId);
6089
6090       aMesh->RemoveElement(elem);
6091     }
6092   }
6093 }
6094
6095 //=======================================================================
6096 //function : ConvertElemToQuadratic
6097 //purpose  :
6098 //=======================================================================
6099 void SMESH_MeshEditor::ConvertElemToQuadratic(SMESHDS_SubMesh *theSm,
6100                                               SMESH_MesherHelper* theHelper,
6101                                               const bool theForce3d)
6102 {
6103   if( !theSm ) return;
6104   SMESHDS_Mesh* meshDS = GetMeshDS();
6105   SMDS_ElemIteratorPtr ElemItr = theSm->GetElements();
6106   while(ElemItr->more())
6107   {
6108     const SMDS_MeshElement* elem = ElemItr->next();
6109     if( !elem ) continue;
6110
6111     int id = elem->GetID();
6112     int nbNodes = elem->NbNodes();
6113     vector<const SMDS_MeshNode *> aNds (nbNodes);
6114     
6115     for(int i = 0; i < nbNodes; i++)
6116     {
6117       aNds[i] = elem->GetNode(i);
6118     }
6119
6120     SMDSAbs_ElementType aType = elem->GetType();
6121     const SMDS_MeshElement* NewElem = 0;
6122
6123     switch( aType )
6124     {
6125     case SMDSAbs_Edge :
6126     {
6127       meshDS->RemoveFreeElement(elem, theSm);   
6128       NewElem = theHelper->AddQuadraticEdge(aNds[0], aNds[1], id, theForce3d);
6129       break;
6130     }
6131     case SMDSAbs_Face :
6132     {
6133       if(elem->IsQuadratic()) continue;
6134
6135       meshDS->RemoveFreeElement(elem, theSm);
6136       switch(nbNodes)
6137       {
6138       case 3:
6139         NewElem = theHelper->AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6140         break;
6141       case 4:
6142         NewElem = theHelper->AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6143         break;
6144       default:
6145         continue;
6146       }
6147       break;  
6148     }
6149     case SMDSAbs_Volume :
6150     {
6151       if( elem->IsQuadratic() ) continue;
6152
6153       meshDS->RemoveFreeElement(elem, theSm);
6154       switch(nbNodes)
6155       {
6156       case 4:
6157         NewElem = theHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], id, true);
6158         break;
6159       case 6:
6160         NewElem = theHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], aNds[4], aNds[5], id, true);
6161         break;
6162       case 8:
6163         NewElem = theHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6164                                        aNds[4], aNds[5], aNds[6], aNds[7], id, true);
6165         break;
6166       default:
6167         continue;
6168       }
6169       break;  
6170     }
6171     default :
6172       continue;
6173     }
6174     if( NewElem )
6175     {
6176       AddToSameGroups( NewElem, elem, meshDS);
6177       theSm->AddElement( NewElem );
6178     }
6179   }
6180 }
6181
6182 //=======================================================================
6183 //function : ConvertToQuadratic
6184 //purpose  :
6185 //=======================================================================
6186 void SMESH_MeshEditor::ConvertToQuadratic(const bool theForce3d)
6187 {
6188   SMESHDS_Mesh* meshDS = GetMeshDS();
6189
6190   SMESH_MesherHelper* aHelper = new SMESH_MesherHelper(*myMesh);
6191   aHelper->SetKeyIsQuadratic( true );
6192   const TopoDS_Shape& aShape = meshDS->ShapeToMesh();
6193
6194   if ( !aShape.IsNull() && GetMesh()->GetSubMeshContaining(aShape) )
6195   {
6196     SMESH_subMesh *aSubMesh = GetMesh()->GetSubMeshContaining(aShape);
6197     
6198     const map < int, SMESH_subMesh * >& aMapSM = aSubMesh->DependsOn();
6199     map < int, SMESH_subMesh * >::const_iterator itsub;
6200     for (itsub = aMapSM.begin(); itsub != aMapSM.end(); itsub++)
6201     {
6202       SMESHDS_SubMesh *sm = ((*itsub).second)->GetSubMeshDS();
6203       aHelper->SetSubShape( (*itsub).second->GetSubShape() );
6204       ConvertElemToQuadratic(sm, aHelper, theForce3d);
6205     }
6206     aHelper->SetSubShape( aSubMesh->GetSubShape() );
6207     ConvertElemToQuadratic(aSubMesh->GetSubMeshDS(), aHelper, theForce3d);
6208   }
6209   else
6210   {
6211     SMDS_EdgeIteratorPtr aEdgeItr = meshDS->edgesIterator();
6212     while(aEdgeItr->more())
6213     {
6214       const SMDS_MeshEdge* edge = aEdgeItr->next();
6215       if(edge)
6216       {
6217         int id = edge->GetID();
6218         const SMDS_MeshNode* n1 = edge->GetNode(0);
6219         const SMDS_MeshNode* n2 = edge->GetNode(1);
6220
6221         RemoveElemFromGroups (edge, meshDS);
6222         meshDS->SMDS_Mesh::RemoveFreeElement(edge);
6223
6224         const SMDS_QuadraticEdge* NewEdge = aHelper->AddQuadraticEdge(n1, n2, id, theForce3d);
6225         AddToSameGroups(NewEdge, edge, meshDS);
6226       }
6227     }
6228     SMDS_FaceIteratorPtr aFaceItr = meshDS->facesIterator();
6229     while(aFaceItr->more())
6230     {
6231       const SMDS_MeshFace* face = aFaceItr->next();
6232       if(!face || face->IsQuadratic() ) continue;
6233       
6234       int id = face->GetID();
6235       int nbNodes = face->NbNodes();
6236       vector<const SMDS_MeshNode *> aNds (nbNodes);
6237
6238       for(int i = 0; i < nbNodes; i++)
6239       {
6240         aNds[i] = face->GetNode(i);
6241       }
6242
6243       RemoveElemFromGroups (face, meshDS); 
6244       meshDS->SMDS_Mesh::RemoveFreeElement(face);
6245
6246       SMDS_MeshFace * NewFace = 0;
6247       switch(nbNodes)
6248       {
6249       case 3:
6250         NewFace = aHelper->AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6251         break;
6252       case 4:
6253         NewFace = aHelper->AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6254         break;
6255       default:
6256         continue;
6257       }
6258       AddToSameGroups(NewFace, face, meshDS);
6259     }
6260     SMDS_VolumeIteratorPtr aVolumeItr = meshDS->volumesIterator();
6261     while(aVolumeItr->more())
6262     {
6263       const SMDS_MeshVolume* volume = aVolumeItr->next();
6264       if(!volume || volume->IsQuadratic() ) continue;
6265       
6266       int id = volume->GetID();
6267       int nbNodes = volume->NbNodes();
6268       vector<const SMDS_MeshNode *> aNds (nbNodes);
6269
6270       for(int i = 0; i < nbNodes; i++)
6271       {
6272         aNds[i] = volume->GetNode(i);
6273       }
6274
6275       RemoveElemFromGroups (volume, meshDS);
6276       meshDS->SMDS_Mesh::RemoveFreeElement(volume);
6277
6278       SMDS_MeshVolume * NewVolume = 0;
6279       switch(nbNodes)
6280       {
6281       case 4:
6282         NewVolume = aHelper->AddVolume(aNds[0], aNds[1], aNds[2],
6283                                        aNds[3], id, true );
6284         break;
6285       case 6:
6286         NewVolume = aHelper->AddVolume(aNds[0], aNds[1], aNds[2],
6287                                        aNds[3], aNds[4], aNds[5], id, true);
6288         break;
6289       case 8:
6290         NewVolume = aHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6291                                        aNds[4], aNds[5], aNds[6], aNds[7], id, true);
6292         break;
6293       default:
6294         continue;
6295       }
6296       AddToSameGroups(NewVolume, volume, meshDS);
6297     }
6298   }
6299   delete aHelper;
6300 }
6301
6302 //=======================================================================
6303 //function : RemoveQuadElem
6304 //purpose  :
6305 //=======================================================================
6306 void SMESH_MeshEditor::RemoveQuadElem(SMESHDS_SubMesh *theSm, 
6307                                       SMDS_ElemIteratorPtr theItr,
6308                                       RemoveQuadNodeMap& theRemoveNodeMap)
6309 {
6310   SMESHDS_Mesh* meshDS = GetMeshDS();
6311   while( theItr->more() )
6312   {
6313     const SMDS_MeshElement* elem = theItr->next();
6314     if( elem )
6315     {
6316       if( !elem->IsQuadratic() )
6317         continue;
6318       
6319       int id = elem->GetID();
6320
6321       int nbNodes = elem->NbNodes(), idx = 0;
6322       vector<const SMDS_MeshNode *> aNds; 
6323
6324       for(int i = 0; i < nbNodes; i++)
6325       {
6326         const SMDS_MeshNode* n = elem->GetNode(i);
6327
6328         if( elem->IsMediumNode( n ) )
6329         {
6330           ItRemoveQuadNodeMap itRNM = theRemoveNodeMap.find( n );
6331           if( itRNM == theRemoveNodeMap.end() )
6332           {
6333             theRemoveNodeMap.insert(RemoveQuadNodeMap::value_type( n,theSm ));
6334           }
6335         }
6336         else 
6337           aNds.push_back( n );
6338       }
6339
6340       idx = aNds.size();
6341       if( !idx ) continue;
6342       SMDSAbs_ElementType aType = elem->GetType();      
6343
6344       //remove old quadratic elements
6345       meshDS->RemoveFreeElement( elem, theSm );
6346
6347       SMDS_MeshElement * NewElem = 0;
6348       switch(aType)
6349       {
6350         case SMDSAbs_Edge:
6351           NewElem = meshDS->AddEdgeWithID( aNds[0], aNds[1] ,id );
6352           break;
6353         case SMDSAbs_Face:
6354           if( idx==3 ) NewElem = meshDS->AddFaceWithID( aNds[0],
6355                                    aNds[1], aNds[2], id );
6356           if( idx==4 ) NewElem = meshDS->AddFaceWithID( aNds[0],
6357                                    aNds[1], aNds[2], aNds[3],id );
6358           break;
6359         case SMDSAbs_Volume:
6360           if( idx==4 ) NewElem = meshDS->AddVolumeWithID( aNds[0],
6361                                    aNds[1], aNds[2], aNds[3], id );
6362           if( idx==6 ) NewElem = meshDS->AddVolumeWithID( aNds[0],
6363                                    aNds[1], aNds[2], aNds[3],
6364                                    aNds[4], aNds[5], id );
6365           if( idx==8 ) NewElem = meshDS->AddVolumeWithID(aNds[0],
6366                                    aNds[1], aNds[2], aNds[3],
6367                                    aNds[4], aNds[5], aNds[6],
6368                                    aNds[7] ,id );
6369           break;
6370         default:
6371           break;
6372       }
6373
6374       AddToSameGroups(NewElem, elem, meshDS);
6375       if( theSm )
6376         theSm->AddElement( NewElem );
6377     }
6378   }
6379 }
6380 //=======================================================================
6381 //function : ConvertFromQuadratic
6382 //purpose  :
6383 //=======================================================================
6384 bool  SMESH_MeshEditor::ConvertFromQuadratic()
6385 {
6386   SMESHDS_Mesh* meshDS = GetMeshDS();
6387   RemoveQuadNodeMap aRemoveNodeMap;
6388
6389   const TopoDS_Shape& aShape = meshDS->ShapeToMesh();
6390
6391   if ( !aShape.IsNull() && GetMesh()->GetSubMeshContaining(aShape) )
6392   {
6393     SMESH_subMesh *aSubMesh = GetMesh()->GetSubMeshContaining(aShape);
6394     
6395     const map < int, SMESH_subMesh * >& aMapSM = aSubMesh->DependsOn();
6396     map < int, SMESH_subMesh * >::const_iterator itsub;
6397     for (itsub = aMapSM.begin(); itsub != aMapSM.end(); itsub++)
6398     {
6399       SMESHDS_SubMesh *sm = ((*itsub).second)->GetSubMeshDS();
6400       if( sm )
6401         RemoveQuadElem( sm, sm->GetElements(), aRemoveNodeMap );
6402     }
6403     SMESHDS_SubMesh *Sm = aSubMesh->GetSubMeshDS();
6404     if( Sm )
6405       RemoveQuadElem( Sm, Sm->GetElements(), aRemoveNodeMap );
6406   }
6407   else
6408   {
6409     SMESHDS_SubMesh *aSM = 0;
6410     RemoveQuadElem( aSM, meshDS->elementsIterator(), aRemoveNodeMap );
6411   }
6412
6413   //remove all quadratic nodes 
6414   ItRemoveQuadNodeMap itRNM = aRemoveNodeMap.begin();
6415   for ( ; itRNM != aRemoveNodeMap.end(); itRNM++ ) 
6416   {
6417     meshDS->RemoveFreeNode( (*itRNM).first, (*itRNM).second  ); 
6418   }
6419
6420   return true;
6421 }
6422
6423 //=======================================================================
6424 //function : SewSideElements
6425 //purpose  :
6426 //=======================================================================
6427
6428 SMESH_MeshEditor::Sew_Error
6429   SMESH_MeshEditor::SewSideElements (map<int,const SMDS_MeshElement*>& theSide1,
6430                                      map<int,const SMDS_MeshElement*>& theSide2,
6431                                      const SMDS_MeshNode*          theFirstNode1,
6432                                      const SMDS_MeshNode*          theFirstNode2,
6433                                      const SMDS_MeshNode*          theSecondNode1,
6434                                      const SMDS_MeshNode*          theSecondNode2)
6435 {
6436   myLastCreatedElems.Clear();
6437   myLastCreatedNodes.Clear();
6438
6439   MESSAGE ("::::SewSideElements()");
6440   if ( theSide1.size() != theSide2.size() )
6441     return SEW_DIFF_NB_OF_ELEMENTS;
6442
6443   Sew_Error aResult = SEW_OK;
6444   // Algo:
6445   // 1. Build set of faces representing each side
6446   // 2. Find which nodes of the side 1 to merge with ones on the side 2
6447   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
6448
6449   // =======================================================================
6450   // 1. Build set of faces representing each side:
6451   // =======================================================================
6452   // a. build set of nodes belonging to faces
6453   // b. complete set of faces: find missing fices whose nodes are in set of nodes
6454   // c. create temporary faces representing side of volumes if correspondent
6455   //    face does not exist
6456
6457   SMESHDS_Mesh* aMesh = GetMeshDS();
6458   SMDS_Mesh aTmpFacesMesh;
6459   set<const SMDS_MeshElement*> faceSet1, faceSet2;
6460   set<const SMDS_MeshElement*> volSet1,  volSet2;
6461   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
6462   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
6463   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
6464   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
6465   map<int,const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
6466   int iSide, iFace, iNode;
6467
6468   for ( iSide = 0; iSide < 2; iSide++ ) {
6469     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
6470     map<int,const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
6471     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
6472     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
6473     set<const SMDS_MeshElement*>::iterator vIt;
6474     map<int,const SMDS_MeshElement*>::iterator eIt;
6475     set<const SMDS_MeshNode*>::iterator    nIt;
6476
6477     // check that given nodes belong to given elements
6478     const SMDS_MeshNode* n1 = ( iSide == 0 ) ? theFirstNode1 : theFirstNode2;
6479     const SMDS_MeshNode* n2 = ( iSide == 0 ) ? theSecondNode1 : theSecondNode2;
6480     int firstIndex = -1, secondIndex = -1;
6481     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
6482       const SMDS_MeshElement* elem = (*eIt).second;
6483       if ( firstIndex  < 0 ) firstIndex  = elem->GetNodeIndex( n1 );
6484       if ( secondIndex < 0 ) secondIndex = elem->GetNodeIndex( n2 );
6485       if ( firstIndex > -1 && secondIndex > -1 ) break;
6486     }
6487     if ( firstIndex < 0 || secondIndex < 0 ) {
6488       // we can simply return until temporary faces created
6489       return (iSide == 0 ) ? SEW_BAD_SIDE1_NODES : SEW_BAD_SIDE2_NODES;
6490     }
6491
6492     // -----------------------------------------------------------
6493     // 1a. Collect nodes of existing faces
6494     //     and build set of face nodes in order to detect missing
6495     //     faces corresponing to sides of volumes
6496     // -----------------------------------------------------------
6497
6498     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
6499
6500     // loop on the given element of a side
6501     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
6502       //const SMDS_MeshElement* elem = *eIt;
6503       const SMDS_MeshElement* elem = (*eIt).second;
6504       if ( elem->GetType() == SMDSAbs_Face ) {
6505         faceSet->insert( elem );
6506         set <const SMDS_MeshNode*> faceNodeSet;
6507         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
6508         while ( nodeIt->more() ) {
6509           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6510           nodeSet->insert( n );
6511           faceNodeSet.insert( n );
6512         }
6513         setOfFaceNodeSet.insert( faceNodeSet );
6514       }
6515       else if ( elem->GetType() == SMDSAbs_Volume )
6516         volSet->insert( elem );
6517     }
6518     // ------------------------------------------------------------------------------
6519     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
6520     // ------------------------------------------------------------------------------
6521
6522     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
6523       SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
6524       while ( fIt->more() ) { // loop on faces sharing a node
6525         const SMDS_MeshElement* f = fIt->next();
6526         if ( faceSet->find( f ) == faceSet->end() ) {
6527           // check if all nodes are in nodeSet and
6528           // complete setOfFaceNodeSet if they are
6529           set <const SMDS_MeshNode*> faceNodeSet;
6530           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
6531           bool allInSet = true;
6532           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
6533             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6534             if ( nodeSet->find( n ) == nodeSet->end() )
6535               allInSet = false;
6536             else
6537               faceNodeSet.insert( n );
6538           }
6539           if ( allInSet ) {
6540             faceSet->insert( f );
6541             setOfFaceNodeSet.insert( faceNodeSet );
6542           }
6543         }
6544       }
6545     }
6546
6547     // -------------------------------------------------------------------------
6548     // 1c. Create temporary faces representing sides of volumes if correspondent
6549     //     face does not exist
6550     // -------------------------------------------------------------------------
6551
6552     if ( !volSet->empty() ) {
6553       //int nodeSetSize = nodeSet->size();
6554
6555       // loop on given volumes
6556       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
6557         SMDS_VolumeTool vol (*vIt);
6558         // loop on volume faces: find free faces
6559         // --------------------------------------
6560         list<const SMDS_MeshElement* > freeFaceList;
6561         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
6562           if ( !vol.IsFreeFace( iFace ))
6563             continue;
6564           // check if there is already a face with same nodes in a face set
6565           const SMDS_MeshElement* aFreeFace = 0;
6566           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
6567           int nbNodes = vol.NbFaceNodes( iFace );
6568           set <const SMDS_MeshNode*> faceNodeSet;
6569           vol.GetFaceNodes( iFace, faceNodeSet );
6570           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
6571           if ( isNewFace ) {
6572             // no such a face is given but it still can exist, check it
6573             if ( nbNodes == 3 ) {
6574               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
6575             }
6576             else if ( nbNodes == 4 ) {
6577               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
6578             }
6579             else {
6580               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
6581               aFreeFace = aMesh->FindFace(poly_nodes);
6582             }
6583           }
6584           if ( !aFreeFace ) {
6585             // create a temporary face
6586             if ( nbNodes == 3 ) {
6587               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
6588             }
6589             else if ( nbNodes == 4 ) {
6590               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
6591             }
6592             else {
6593               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
6594               aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
6595             }
6596           }
6597           if ( aFreeFace )
6598             freeFaceList.push_back( aFreeFace );
6599
6600         } // loop on faces of a volume
6601
6602         // choose one of several free faces
6603         // --------------------------------------
6604         if ( freeFaceList.size() > 1 ) {
6605           // choose a face having max nb of nodes shared by other elems of a side
6606           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
6607           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
6608           while ( fIt != freeFaceList.end() ) { // loop on free faces
6609             int nbSharedNodes = 0;
6610             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
6611             while ( nodeIt->more() ) { // loop on free face nodes
6612               const SMDS_MeshNode* n =
6613                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6614               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
6615               while ( invElemIt->more() ) {
6616                 const SMDS_MeshElement* e = invElemIt->next();
6617                 if ( faceSet->find( e ) != faceSet->end() )
6618                   nbSharedNodes++;
6619                 if ( elemSet->find( e->GetID() ) != elemSet->end() )
6620                   nbSharedNodes++;
6621               }
6622             }
6623             if ( nbSharedNodes >= maxNbNodes ) {
6624               maxNbNodes = nbSharedNodes;
6625               fIt++;
6626             }
6627             else
6628               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
6629           }
6630           if ( freeFaceList.size() > 1 )
6631           {
6632             // could not choose one face, use another way
6633             // choose a face most close to the bary center of the opposite side
6634             gp_XYZ aBC( 0., 0., 0. );
6635             set <const SMDS_MeshNode*> addedNodes;
6636             map<int,const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
6637             eIt = elemSet2->begin();
6638             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
6639               SMDS_ElemIteratorPtr nodeIt = (*eIt).second->nodesIterator();
6640               while ( nodeIt->more() ) { // loop on free face nodes
6641                 const SMDS_MeshNode* n =
6642                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6643                 if ( addedNodes.insert( n ).second )
6644                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
6645               }
6646             }
6647             aBC /= addedNodes.size();
6648             double minDist = DBL_MAX;
6649             fIt = freeFaceList.begin();
6650             while ( fIt != freeFaceList.end() ) { // loop on free faces
6651               double dist = 0;
6652               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
6653               while ( nodeIt->more() ) { // loop on free face nodes
6654                 const SMDS_MeshNode* n =
6655                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6656                 gp_XYZ p( n->X(),n->Y(),n->Z() );
6657                 dist += ( aBC - p ).SquareModulus();
6658               }
6659               if ( dist < minDist ) {
6660                 minDist = dist;
6661                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
6662               }
6663               else
6664                 fIt = freeFaceList.erase( fIt++ );
6665             }
6666           }
6667         } // choose one of several free faces of a volume
6668
6669         if ( freeFaceList.size() == 1 ) {
6670           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
6671           faceSet->insert( aFreeFace );
6672           // complete a node set with nodes of a found free face
6673 //           for ( iNode = 0; iNode < ; iNode++ )
6674 //             nodeSet->insert( fNodes[ iNode ] );
6675         }
6676
6677       } // loop on volumes of a side
6678
6679 //       // complete a set of faces if new nodes in a nodeSet appeared
6680 //       // ----------------------------------------------------------
6681 //       if ( nodeSetSize != nodeSet->size() ) {
6682 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
6683 //           SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
6684 //           while ( fIt->more() ) { // loop on faces sharing a node
6685 //             const SMDS_MeshElement* f = fIt->next();
6686 //             if ( faceSet->find( f ) == faceSet->end() ) {
6687 //               // check if all nodes are in nodeSet and
6688 //               // complete setOfFaceNodeSet if they are
6689 //               set <const SMDS_MeshNode*> faceNodeSet;
6690 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
6691 //               bool allInSet = true;
6692 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
6693 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6694 //                 if ( nodeSet->find( n ) == nodeSet->end() )
6695 //                   allInSet = false;
6696 //                 else
6697 //                   faceNodeSet.insert( n );
6698 //               }
6699 //               if ( allInSet ) {
6700 //                 faceSet->insert( f );
6701 //                 setOfFaceNodeSet.insert( faceNodeSet );
6702 //               }
6703 //             }
6704 //           }
6705 //         }
6706 //       }
6707     } // Create temporary faces, if there are volumes given
6708   } // loop on sides
6709
6710   if ( faceSet1.size() != faceSet2.size() ) {
6711     // delete temporary faces: they are in reverseElements of actual nodes
6712     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
6713     while ( tmpFaceIt->more() )
6714       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
6715     MESSAGE("Diff nb of faces");
6716     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6717   }
6718
6719   // ============================================================
6720   // 2. Find nodes to merge:
6721   //              bind a node to remove to a node to put instead
6722   // ============================================================
6723
6724   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
6725   if ( theFirstNode1 != theFirstNode2 )
6726     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
6727   if ( theSecondNode1 != theSecondNode2 )
6728     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
6729
6730   LinkID_Gen aLinkID_Gen( GetMeshDS() );
6731   set< long > linkIdSet; // links to process
6732   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
6733
6734   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
6735   list< TPairOfNodes > linkList[2];
6736   linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
6737   linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
6738   // loop on links in linkList; find faces by links and append links
6739   // of the found faces to linkList
6740   list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
6741   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ ) {
6742     TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
6743     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
6744     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
6745       continue;
6746
6747     // by links, find faces in the face sets,
6748     // and find indices of link nodes in the found faces;
6749     // in a face set, there is only one or no face sharing a link
6750     // ---------------------------------------------------------------
6751
6752     const SMDS_MeshElement* face[] = { 0, 0 };
6753     //const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
6754     vector<const SMDS_MeshNode*> fnodes1(9);
6755     vector<const SMDS_MeshNode*> fnodes2(9);
6756     //const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
6757     vector<const SMDS_MeshNode*> notLinkNodes1(6);
6758     vector<const SMDS_MeshNode*> notLinkNodes2(6);
6759     int iLinkNode[2][2];
6760     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
6761       const SMDS_MeshNode* n1 = link[iSide].first;
6762       const SMDS_MeshNode* n2 = link[iSide].second;
6763       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
6764       set< const SMDS_MeshElement* > fMap;
6765       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
6766         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
6767         SMDS_ElemIteratorPtr fIt = n->facesIterator();
6768         while ( fIt->more() ) { // loop on faces sharing a node
6769           const SMDS_MeshElement* f = fIt->next();
6770           if (faceSet->find( f ) != faceSet->end() && // f is in face set
6771               ! fMap.insert( f ).second ) // f encounters twice
6772           {
6773             if ( face[ iSide ] ) {
6774               MESSAGE( "2 faces per link " );
6775               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
6776               break;
6777             }
6778             face[ iSide ] = f;
6779             faceSet->erase( f );
6780             // get face nodes and find ones of a link
6781             iNode = 0;
6782             int nbl = -1;
6783             if(f->IsPoly()) {
6784               if(iSide==0) {
6785                 fnodes1.resize(f->NbNodes()+1);
6786                 notLinkNodes1.resize(f->NbNodes()-2);
6787               }
6788               else {
6789                 fnodes2.resize(f->NbNodes()+1);
6790                 notLinkNodes2.resize(f->NbNodes()-2);
6791               }
6792             }
6793             if(!f->IsQuadratic()) {
6794               SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6795               while ( nIt->more() ) {
6796                 const SMDS_MeshNode* n =
6797                   static_cast<const SMDS_MeshNode*>( nIt->next() );
6798                 if ( n == n1 ) {
6799                   iLinkNode[ iSide ][ 0 ] = iNode;
6800                 }
6801                 else if ( n == n2 ) {
6802                   iLinkNode[ iSide ][ 1 ] = iNode;
6803                 }
6804                 //else if ( notLinkNodes[ iSide ][ 0 ] )
6805                 //  notLinkNodes[ iSide ][ 1 ] = n;
6806                 //else
6807                 //  notLinkNodes[ iSide ][ 0 ] = n;
6808                 else {
6809                   nbl++;
6810                   if(iSide==0)
6811                     notLinkNodes1[nbl] = n;
6812                     //notLinkNodes1.push_back(n);
6813                   else
6814                     notLinkNodes2[nbl] = n;
6815                     //notLinkNodes2.push_back(n);
6816                 }
6817                 //faceNodes[ iSide ][ iNode++ ] = n;
6818                 if(iSide==0) {
6819                   fnodes1[iNode++] = n;
6820                 }
6821                 else {
6822                   fnodes2[iNode++] = n;
6823                 }
6824               }
6825             }
6826             else { // f->IsQuadratic()
6827               const SMDS_QuadraticFaceOfNodes* F =
6828                 static_cast<const SMDS_QuadraticFaceOfNodes*>(f);
6829               // use special nodes iterator
6830               SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
6831               while ( anIter->more() ) {
6832                 const SMDS_MeshNode* n =
6833                   static_cast<const SMDS_MeshNode*>( anIter->next() );
6834                 if ( n == n1 ) {
6835                   iLinkNode[ iSide ][ 0 ] = iNode;
6836                 }
6837                 else if ( n == n2 ) {
6838                   iLinkNode[ iSide ][ 1 ] = iNode;
6839                 }
6840                 else {
6841                   nbl++;
6842                   if(iSide==0) {
6843                     notLinkNodes1[nbl] = n;
6844                   }
6845                   else {
6846                     notLinkNodes2[nbl] = n;
6847                   }
6848                 }
6849                 if(iSide==0) {
6850                   fnodes1[iNode++] = n;
6851                 }
6852                 else {
6853                   fnodes2[iNode++] = n;
6854                 }
6855               }
6856             }
6857             //faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
6858             if(iSide==0) {
6859               fnodes1[iNode] = fnodes1[0];
6860             }
6861             else {
6862               fnodes2[iNode] = fnodes1[0];
6863             }
6864           }
6865         }
6866       }
6867     }
6868
6869     // check similarity of elements of the sides
6870     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
6871       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
6872       if ( nReplaceMap.size() == 2 ) { // faces on input nodes not found
6873         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
6874       }
6875       else {
6876         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6877       }
6878       break; // do not return because it s necessary to remove tmp faces
6879     }
6880
6881     // set nodes to merge
6882     // -------------------
6883
6884     if ( face[0] && face[1] )  {
6885       int nbNodes = face[0]->NbNodes();
6886       if ( nbNodes != face[1]->NbNodes() ) {
6887         MESSAGE("Diff nb of face nodes");
6888         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6889         break; // do not return because it s necessary to remove tmp faces
6890       }
6891       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
6892       if ( nbNodes == 3 ) {
6893         //nReplaceMap.insert( TNodeNodeMap::value_type
6894         //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
6895         nReplaceMap.insert( TNodeNodeMap::value_type
6896                            ( notLinkNodes1[0], notLinkNodes2[0] ));
6897       }
6898       else {
6899         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
6900           // analyse link orientation in faces
6901           int i1 = iLinkNode[ iSide ][ 0 ];
6902           int i2 = iLinkNode[ iSide ][ 1 ];
6903           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
6904           // if notLinkNodes are the first and the last ones, then
6905           // their order does not correspond to the link orientation
6906           if (( i1 == 1 && i2 == 2 ) ||
6907               ( i1 == 2 && i2 == 1 ))
6908             reverse[ iSide ] = !reverse[ iSide ];
6909         }
6910         if ( reverse[0] == reverse[1] ) {
6911           //nReplaceMap.insert( TNodeNodeMap::value_type
6912           //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
6913           //nReplaceMap.insert( TNodeNodeMap::value_type
6914           //                   ( notLinkNodes[0][1], notLinkNodes[1][1] ));
6915           for(int nn=0; nn<nbNodes-2; nn++) {
6916             nReplaceMap.insert( TNodeNodeMap::value_type
6917                              ( notLinkNodes1[nn], notLinkNodes2[nn] ));
6918           }
6919         }
6920         else {
6921           //nReplaceMap.insert( TNodeNodeMap::value_type
6922           //                   ( notLinkNodes[0][0], notLinkNodes[1][1] ));
6923           //nReplaceMap.insert( TNodeNodeMap::value_type
6924           //                   ( notLinkNodes[0][1], notLinkNodes[1][0] ));
6925           for(int nn=0; nn<nbNodes-2; nn++) {
6926             nReplaceMap.insert( TNodeNodeMap::value_type
6927                              ( notLinkNodes1[nn], notLinkNodes2[nbNodes-3-nn] ));
6928           }
6929         }
6930       }
6931
6932       // add other links of the faces to linkList
6933       // -----------------------------------------
6934
6935       //const SMDS_MeshNode** nodes = faceNodes[ 0 ];
6936       for ( iNode = 0; iNode < nbNodes; iNode++ )  {
6937         //linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
6938         linkID = aLinkID_Gen.GetLinkID( fnodes1[iNode], fnodes1[iNode+1] );
6939         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
6940         if ( !iter_isnew.second ) { // already in a set: no need to process
6941           linkIdSet.erase( iter_isnew.first );
6942         }
6943         else // new in set == encountered for the first time: add
6944         {
6945           //const SMDS_MeshNode* n1 = nodes[ iNode ];
6946           //const SMDS_MeshNode* n2 = nodes[ iNode + 1];
6947           const SMDS_MeshNode* n1 = fnodes1[ iNode ];
6948           const SMDS_MeshNode* n2 = fnodes1[ iNode + 1];
6949           linkList[0].push_back ( TPairOfNodes( n1, n2 ));
6950           linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
6951         }
6952       }
6953     } // 2 faces found
6954   } // loop on link lists
6955
6956   if ( aResult == SEW_OK &&
6957       ( linkIt[0] != linkList[0].end() ||
6958        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
6959     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
6960             " " << (faceSetPtr[1]->empty()));
6961     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6962   }
6963
6964   // ====================================================================
6965   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
6966   // ====================================================================
6967
6968   // delete temporary faces: they are in reverseElements of actual nodes
6969   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
6970   while ( tmpFaceIt->more() )
6971     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
6972
6973   if ( aResult != SEW_OK)
6974     return aResult;
6975
6976   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
6977   // loop on nodes replacement map
6978   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
6979   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
6980     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second ) {
6981       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
6982       nodeIDsToRemove.push_back( nToRemove->GetID() );
6983       // loop on elements sharing nToRemove
6984       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
6985       while ( invElemIt->more() ) {
6986         const SMDS_MeshElement* e = invElemIt->next();
6987         // get a new suite of nodes: make replacement
6988         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
6989         vector< const SMDS_MeshNode*> nodes( nbNodes );
6990         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
6991         while ( nIt->more() ) {
6992           const SMDS_MeshNode* n =
6993             static_cast<const SMDS_MeshNode*>( nIt->next() );
6994           nnIt = nReplaceMap.find( n );
6995           if ( nnIt != nReplaceMap.end() ) {
6996             nbReplaced++;
6997             n = (*nnIt).second;
6998           }
6999           nodes[ i++ ] = n;
7000         }
7001         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
7002         //         elemIDsToRemove.push_back( e->GetID() );
7003         //       else
7004         if ( nbReplaced )
7005           aMesh->ChangeElementNodes( e, & nodes[0], nbNodes );
7006       }
7007     }
7008
7009   Remove( nodeIDsToRemove, true );
7010
7011   return aResult;
7012 }