Salome HOME
Replaced NMTTools map with NCollection map for removing dependencies from GEOM module.
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.cxx
1 //  SMESH SMESH : idl implementation based on 'SMESH' unit's classes
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
21 //
22 //
23 //
24 // File      : SMESH_MeshEditor.cxx
25 // Created   : Mon Apr 12 16:10:22 2004
26 // Author    : Edward AGAPOV (eap)
27
28
29 #include "SMESH_MeshEditor.hxx"
30
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
37
38 #include "SMESHDS_Group.hxx"
39 #include "SMESHDS_Mesh.hxx"
40
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_ControlsDef.hxx"
43
44 #include "utilities.h"
45
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_ListOfShape.hxx>
48 #include <math.h>
49 #include <gp_Dir.hxx>
50 #include <gp_Vec.hxx>
51 #include <gp_Ax1.hxx>
52 #include <gp_Trsf.hxx>
53 #include <gp_Lin.hxx>
54 #include <gp_XYZ.hxx>
55 #include <gp_XY.hxx>
56 #include <gp.hxx>
57 #include <gp_Pln.hxx>
58 #include <BRep_Tool.hxx>
59 #include <Geom_Curve.hxx>
60 #include <Geom_Surface.hxx>
61 #include <Geom2d_Curve.hxx>
62 #include <Extrema_GenExtPS.hxx>
63 #include <Extrema_POnSurf.hxx>
64 #include <GeomAdaptor_Surface.hxx>
65 #include <ElCLib.hxx>
66
67 #include <map>
68
69 using namespace std;
70 using namespace SMESH::Controls;
71
72 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*>              TNodeNodeMap;
73 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> >    TElemOfNodeListMap;
74 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
75 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> >       TNodeOfNodeListMap;
76 typedef TNodeOfNodeListMap::iterator                                 TNodeOfNodeListMapItr;
77 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
78
79 //=======================================================================
80 //function : SMESH_MeshEditor
81 //purpose  :
82 //=======================================================================
83
84 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
85 myMesh( theMesh )
86 {
87 }
88
89 //=======================================================================
90 //function : Remove
91 //purpose  : Remove a node or an element.
92 //           Modify a compute state of sub-meshes which become empty
93 //=======================================================================
94
95 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
96                                const bool         isNodes )
97 {
98
99   SMESHDS_Mesh* aMesh = GetMeshDS();
100   set< SMESH_subMesh *> smmap;
101
102   list<int>::const_iterator it = theIDs.begin();
103   for ( ; it != theIDs.end(); it++ )
104   {
105     const SMDS_MeshElement * elem;
106     if ( isNodes )
107       elem = aMesh->FindNode( *it );
108     else
109       elem = aMesh->FindElement( *it );
110     if ( !elem )
111       continue;
112
113     // Find sub-meshes to notify about modification
114     SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
115     while ( nodeIt->more() )
116     {
117       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
118       const SMDS_PositionPtr& aPosition = node->GetPosition();
119       if ( aPosition.get() ) {
120         int aShapeID = aPosition->GetShapeId();
121         if ( aShapeID ) {
122           TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
123           SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
124           if ( sm )
125             smmap.insert( sm );
126         }
127       }
128     }
129
130     // Do remove
131     if ( isNodes )
132       aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
133     else
134       aMesh->RemoveElement( elem );
135   }
136
137   // Notify sub-meshes about modification
138   if ( !smmap.empty() ) {
139     set< SMESH_subMesh *>::iterator smIt;
140     for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
141       (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
142   }
143   return true;
144 }
145
146 //=======================================================================
147 //function : FindShape
148 //purpose  : Return an index of the shape theElem is on
149 //           or zero if a shape not found
150 //=======================================================================
151
152 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
153 {
154   SMESHDS_Mesh * aMesh = GetMeshDS();
155   if ( aMesh->ShapeToMesh().IsNull() )
156     return 0;
157
158   if ( theElem->GetType() == SMDSAbs_Node )
159   {
160     const SMDS_PositionPtr& aPosition =
161       static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
162     if ( aPosition.get() )
163       return aPosition->GetShapeId();
164     else
165       return 0;
166   }
167
168   TopoDS_Shape aShape; // the shape a node is on
169   SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
170   while ( nodeIt->more() )
171   {
172     const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
173     const SMDS_PositionPtr& aPosition = node->GetPosition();
174     if ( aPosition.get() ) {
175         int aShapeID = aPosition->GetShapeId();
176         SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
177         if ( sm )
178         {
179           if ( sm->Contains( theElem ))
180             return aShapeID;
181           if ( aShape.IsNull() )
182             aShape = aMesh->IndexToShape( aShapeID );
183         }
184         else
185         {
186           //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
187         }
188       }
189   }
190
191   // None of nodes is on a proper shape,
192   // find the shape among ancestors of aShape on which a node is
193   if ( aShape.IsNull() ) {
194     //MESSAGE ("::FindShape() - NONE node is on shape")
195     return 0;
196   }
197   TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
198   for ( ; ancIt.More(); ancIt.Next() )
199   {
200       SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
201       if ( sm && sm->Contains( theElem ))
202         return aMesh->ShapeToIndex( ancIt.Value() );
203   }
204
205   //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
206   return 0;
207 }
208
209 //=======================================================================
210 //function : InverseDiag
211 //purpose  : Replace two neighbour triangles with ones built on the same 4 nodes
212 //           but having other common link.
213 //           Return False if args are improper
214 //=======================================================================
215
216 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
217                                     const SMDS_MeshElement * theTria2 )
218 {
219   if (!theTria1 || !theTria2)
220     return false;
221   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
222   if (!F1) return false;
223   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
224   if (!F2) return false;
225
226   //  1 +--+ A  theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
227   //    | /|    theTria2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |
228   //    |/ |                                         | \|
229   //  B +--+ 2                                     B +--+ 2
230
231   // put nodes in array and find out indices of the same ones
232   const SMDS_MeshNode* aNodes [6];
233   int sameInd [] = { 0, 0, 0, 0, 0, 0 };
234   int i = 0;
235   SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
236   while ( it->more() )
237   {
238     aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
239
240     if ( i > 2 ) // theTria2
241       // find same node of theTria1
242       for ( int j = 0; j < 3; j++ )
243         if ( aNodes[ i ] == aNodes[ j ]) {
244           sameInd[ j ] = i;
245           sameInd[ i ] = j;
246           break;
247         }
248     // next
249     i++;
250     if ( i == 3 ) {
251       if ( it->more() )
252         return false; // theTria1 is not a triangle
253       it = theTria2->nodesIterator();
254     }
255     if ( i == 6 && it->more() )
256       return false; // theTria2 is not a triangle
257   }
258
259   // find indices of 1,2 and of A,B in theTria1
260   int iA = 0, iB = 0, i1 = 0, i2 = 0;
261   for ( i = 0; i < 6; i++ )
262   {
263     if ( sameInd [ i ] == 0 )
264       if ( i < 3 ) i1 = i;
265       else         i2 = i;
266     else if (i < 3)
267       if ( iA ) iB = i;
268       else      iA = i;
269   }
270   // nodes 1 and 2 should not be the same
271   if ( aNodes[ i1 ] == aNodes[ i2 ] )
272     return false;
273
274
275   // theTria1: A->2
276   aNodes[ iA ] = aNodes[ i2 ];
277   // theTria2: B->1
278   aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
279
280   //MESSAGE( theTria1 << theTria2 );
281
282   GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
283   GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
284
285   //MESSAGE( theTria1 << theTria2 );
286
287   return true;
288 }
289
290 //=======================================================================
291 //function : findTriangles
292 //purpose  : find triangles sharing theNode1-theNode2 link
293 //=======================================================================
294
295 static bool findTriangles(const SMDS_MeshNode *    theNode1,
296                           const SMDS_MeshNode *    theNode2,
297                           const SMDS_MeshElement*& theTria1,
298                           const SMDS_MeshElement*& theTria2)
299 {
300   if ( !theNode1 || !theNode2 ) return false;
301
302   theTria1 = theTria2 = 0;
303
304   set< const SMDS_MeshElement* > emap;
305   SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
306   while (it->more()) {
307     const SMDS_MeshElement* elem = it->next();
308     if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
309       emap.insert( elem );
310   }
311   it = theNode2->GetInverseElementIterator();
312   while (it->more()) {
313     const SMDS_MeshElement* elem = it->next();
314     if ( elem->GetType() == SMDSAbs_Face &&
315          emap.find( elem ) != emap.end() )
316       if ( theTria1 ) {
317         theTria2 = elem;
318         break;
319       } else {
320         theTria1 = elem;
321       }
322   }
323   return ( theTria1 && theTria2 );
324 }
325
326 //=======================================================================
327 //function : InverseDiag
328 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
329 //           with ones built on the same 4 nodes but having other common link.
330 //           Return false if proper faces not found
331 //=======================================================================
332
333 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
334                                     const SMDS_MeshNode * theNode2)
335 {
336   MESSAGE( "::InverseDiag()" );
337
338   const SMDS_MeshElement *tr1, *tr2;
339   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
340     return false;
341
342   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
343   if (!F1) return false;
344   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
345   if (!F2) return false;
346
347   //  1 +--+ A  tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
348   //    | /|    tr2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |
349   //    |/ |                                    | \|
350   //  B +--+ 2                                B +--+ 2
351
352   // put nodes in array
353   // and find indices of 1,2 and of A in tr1 and of B in tr2
354   int i, iA1 = 0, i1 = 0;
355   const SMDS_MeshNode* aNodes1 [3];
356   SMDS_ElemIteratorPtr it;
357   for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
358     aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
359     if ( aNodes1[ i ] == theNode1 )
360       iA1 = i; // node A in tr1
361     else if ( aNodes1[ i ] != theNode2 )
362       i1 = i;  // node 1
363   }
364   int iB2 = 0, i2 = 0;
365   const SMDS_MeshNode* aNodes2 [3];
366   for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
367     aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
368     if ( aNodes2[ i ] == theNode2 )
369       iB2 = i; // node B in tr2
370     else if ( aNodes2[ i ] != theNode1 )
371       i2 = i;  // node 2
372   }
373
374   // nodes 1 and 2 should not be the same
375   if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
376     return false;
377
378   // tr1: A->2
379   aNodes1[ iA1 ] = aNodes2[ i2 ];
380   // tr2: B->1
381   aNodes2[ iB2 ] = aNodes1[ i1 ];
382
383   //MESSAGE( tr1 << tr2 );
384
385   GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
386   GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
387
388   //MESSAGE( tr1 << tr2 );
389
390   return true;
391
392 }
393
394 //=======================================================================
395 //function : getQuadrangleNodes
396 //purpose  : fill theQuadNodes - nodes of a quadrangle resulting from
397 //           fusion of triangles tr1 and tr2 having shared link on
398 //           theNode1 and theNode2
399 //=======================================================================
400
401 bool getQuadrangleNodes(const SMDS_MeshNode *    theQuadNodes [],
402                         const SMDS_MeshNode *    theNode1,
403                         const SMDS_MeshNode *    theNode2,
404                         const SMDS_MeshElement * tr1,
405                         const SMDS_MeshElement * tr2 )
406 {
407   // find the 4-th node to insert into tr1
408   const SMDS_MeshNode* n4 = 0;
409   SMDS_ElemIteratorPtr it = tr2->nodesIterator();
410   while ( !n4 && it->more() )
411   {
412     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
413     bool isDiag = ( n == theNode1 || n == theNode2 );
414     if ( !isDiag )
415       n4 = n;
416   }
417   // Make an array of nodes to be in a quadrangle
418   int iNode = 0, iFirstDiag = -1;
419   it = tr1->nodesIterator();
420   while ( it->more() )
421   {
422     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
423     bool isDiag = ( n == theNode1 || n == theNode2 );
424     if ( isDiag )
425     {
426       if ( iFirstDiag < 0 )
427         iFirstDiag = iNode;
428       else if ( iNode - iFirstDiag == 1 )
429         theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
430     }
431     else if ( n == n4 )
432     {
433       return false; // tr1 and tr2 should not have all the same nodes
434     }
435     theQuadNodes[ iNode++ ] = n;
436   }
437   if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
438     theQuadNodes[ iNode ] = n4;
439
440   return true;
441 }
442
443 //=======================================================================
444 //function : DeleteDiag
445 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
446 //           with a quadrangle built on the same 4 nodes.
447 //           Return false if proper faces not found
448 //=======================================================================
449
450 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
451                                    const SMDS_MeshNode * theNode2)
452 {
453   MESSAGE( "::DeleteDiag()" );
454
455   const SMDS_MeshElement *tr1, *tr2;
456   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
457     return false;
458
459   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
460   if (!F1) return false;
461   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
462   if (!F2) return false;
463
464   const SMDS_MeshNode* aNodes [ 4 ];
465   if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
466     return false;
467
468   //MESSAGE( endl << tr1 << tr2 );
469
470   GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
471   GetMeshDS()->RemoveElement( tr2 );
472
473   //MESSAGE( endl << tr1 );
474
475   return true;
476 }
477
478 //=======================================================================
479 //function : Reorient
480 //purpose  : Reverse theElement orientation
481 //=======================================================================
482
483 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
484 {
485   if (!theElem)
486     return false;
487   SMDS_ElemIteratorPtr it = theElem->nodesIterator();
488   if ( !it || !it->more() )
489     return false;
490
491   switch ( theElem->GetType() ) {
492
493   case SMDSAbs_Edge:
494   case SMDSAbs_Face:
495   {
496     int i = theElem->NbNodes();
497     vector<const SMDS_MeshNode*> aNodes( i );
498     while ( it->more() )
499       aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
500     return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
501   }
502   case SMDSAbs_Volume:
503   {
504     if (theElem->IsPoly()) {
505       const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
506         static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
507       if (!aPolyedre) {
508         MESSAGE("Warning: bad volumic element");
509         return false;
510       }
511
512       int nbFaces = aPolyedre->NbFaces();
513       vector<const SMDS_MeshNode *> poly_nodes;
514       vector<int> quantities (nbFaces);
515
516       // reverse each face of the polyedre
517       for (int iface = 1; iface <= nbFaces; iface++) {
518         int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
519         quantities[iface - 1] = nbFaceNodes;
520
521         for (inode = nbFaceNodes; inode >= 1; inode--) {
522           const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
523           poly_nodes.push_back(curNode);
524         }
525       }
526
527       return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
528
529     } else {
530       SMDS_VolumeTool vTool;
531       if ( !vTool.Set( theElem ))
532         return false;
533       vTool.Inverse();
534       return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
535     }
536   }
537   default:;
538   }
539
540   return false;
541 }
542
543 //=======================================================================
544 //function : getBadRate
545 //purpose  :
546 //=======================================================================
547
548 static double getBadRate (const SMDS_MeshElement*               theElem,
549                           SMESH::Controls::NumericalFunctorPtr& theCrit)
550 {
551   SMESH::Controls::TSequenceOfXYZ P;
552   if ( !theElem || !theCrit->GetPoints( theElem, P ))
553     return 1e100;
554   return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
555   //return theCrit->GetBadRate( theCrit->GetValue( theElem->GetID() ), theElem->NbNodes() );
556 }
557
558 //=======================================================================
559 //function : QuadToTri
560 //purpose  : Cut quadrangles into triangles.
561 //           theCrit is used to select a diagonal to cut
562 //=======================================================================
563
564 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> &       theElems,
565                                   SMESH::Controls::NumericalFunctorPtr theCrit)
566 {
567   MESSAGE( "::QuadToTri()" );
568
569   if ( !theCrit.get() )
570     return false;
571
572   SMESHDS_Mesh * aMesh = GetMeshDS();
573
574   set< const SMDS_MeshElement * >::iterator itElem;
575   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
576   {
577     const SMDS_MeshElement* elem = (*itElem);
578     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
579       continue;
580
581     // retrieve element nodes
582     const SMDS_MeshNode* aNodes [4];
583     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
584     int i = 0;
585     while ( itN->more() )
586       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
587
588     // compare two sets of possible triangles
589     double aBadRate1, aBadRate2; // to what extent a set is bad
590     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
591     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
592     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
593
594     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
595     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
596     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
597
598     int aShapeId = FindShape( elem );
599     //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
600       //      << " ShapeID = " << aShapeId << endl << elem );
601
602     if ( aBadRate1 <= aBadRate2 ) {
603       // tr1 + tr2 is better
604       aMesh->ChangeElementNodes( elem, aNodes, 3 );
605       //MESSAGE( endl << elem );
606
607       elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
608     }
609     else {
610       // tr3 + tr4 is better
611       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
612       //MESSAGE( endl << elem );
613
614       elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
615     }
616     //MESSAGE( endl << elem );
617
618     // put a new triangle on the same shape
619     if ( aShapeId )
620       aMesh->SetMeshElementOnShape( elem, aShapeId );
621   }
622
623   return true;
624 }
625
626 //=======================================================================
627 //function : BestSplit
628 //purpose  : Find better diagonal for cutting.
629 //=======================================================================
630 int SMESH_MeshEditor::BestSplit (const SMDS_MeshElement*              theQuad,
631                                  SMESH::Controls::NumericalFunctorPtr theCrit)
632 {
633   if (!theCrit.get())
634     return -1;
635
636   if (!theQuad || theQuad->GetType() != SMDSAbs_Face || theQuad->NbNodes() != 4)
637     return -1;
638
639   // retrieve element nodes
640   const SMDS_MeshNode* aNodes [4];
641   SMDS_ElemIteratorPtr itN = theQuad->nodesIterator();
642   int i = 0;
643   while (itN->more())
644     aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
645
646   // compare two sets of possible triangles
647   double aBadRate1, aBadRate2; // to what extent a set is bad
648   SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
649   SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
650   aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
651
652   SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
653   SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
654   aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
655
656   if (aBadRate1 <= aBadRate2) // tr1 + tr2 is better
657     return 1; // diagonal 1-3
658
659   return 2; // diagonal 2-4
660 }
661
662 //=======================================================================
663 //function : AddToSameGroups
664 //purpose  : add elemToAdd to the groups the elemInGroups belongs to
665 //=======================================================================
666
667 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
668                                         const SMDS_MeshElement* elemInGroups,
669                                         SMESHDS_Mesh *          aMesh)
670 {
671   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
672   set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
673   for ( ; grIt != groups.end(); grIt++ ) {
674     SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
675     if ( group && group->SMDSGroup().Contains( elemInGroups ))
676       group->SMDSGroup().Add( elemToAdd );
677   }
678 }
679
680 //=======================================================================
681 //function : QuadToTri
682 //purpose  : Cut quadrangles into triangles.
683 //           theCrit is used to select a diagonal to cut
684 //=======================================================================
685
686 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
687                                   const bool                          the13Diag)
688 {
689   MESSAGE( "::QuadToTri()" );
690
691   SMESHDS_Mesh * aMesh = GetMeshDS();
692
693   set< const SMDS_MeshElement * >::iterator itElem;
694   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
695   {
696     const SMDS_MeshElement* elem = (*itElem);
697     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
698       continue;
699
700     // retrieve element nodes
701     const SMDS_MeshNode* aNodes [4];
702     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
703     int i = 0;
704     while ( itN->more() )
705       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
706
707     int aShapeId = FindShape( elem );
708     const SMDS_MeshElement* newElem = 0;
709     if ( the13Diag )
710     {
711       aMesh->ChangeElementNodes( elem, aNodes, 3 );
712       newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
713     }
714     else
715     {
716       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
717       newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
718     }
719
720     // put a new triangle on the same shape and add to the same groups
721
722     if ( aShapeId )
723       aMesh->SetMeshElementOnShape( newElem, aShapeId );
724
725     AddToSameGroups( newElem, elem, aMesh );
726   }
727
728   return true;
729 }
730
731 //=======================================================================
732 //function : getAngle
733 //purpose  :
734 //=======================================================================
735
736 double getAngle(const SMDS_MeshElement * tr1,
737                 const SMDS_MeshElement * tr2,
738                 const SMDS_MeshNode *    n1,
739                 const SMDS_MeshNode *    n2)
740 {
741   double angle = 2*PI; // bad angle
742
743   // get normals
744   SMESH::Controls::TSequenceOfXYZ P1, P2;
745   if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
746        !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
747     return angle;
748   gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
749   if ( N1.SquareMagnitude() <= gp::Resolution() )
750     return angle;
751   gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
752   if ( N2.SquareMagnitude() <= gp::Resolution() )
753     return angle;
754
755   // find the first diagonal node n1 in the triangles:
756   // take in account a diagonal link orientation
757   const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
758   for ( int t = 0; t < 2; t++ )
759   {
760     SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
761     int i = 0, iDiag = -1;
762     while ( it->more()) {
763       const SMDS_MeshElement *n = it->next();
764       if ( n == n1 || n == n2 )
765         if ( iDiag < 0)
766           iDiag = i;
767         else {
768           if ( i - iDiag == 1 )
769             nFirst[ t ] = ( n == n1 ? n2 : n1 );
770           else
771             nFirst[ t ] = n;
772           break;
773         }
774       i++;
775     }
776   }
777   if ( nFirst[ 0 ] == nFirst[ 1 ] )
778     N2.Reverse();
779
780   angle = N1.Angle( N2 );
781   //SCRUTE( angle );
782   return angle;
783 }
784
785 // =================================================
786 // class generating a unique ID for a pair of nodes
787 // and able to return nodes by that ID
788 // =================================================
789
790 class LinkID_Gen {
791  public:
792
793   LinkID_Gen( const SMESHDS_Mesh* theMesh )
794     :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
795   {}
796
797   long GetLinkID (const SMDS_MeshNode * n1,
798                   const SMDS_MeshNode * n2) const
799   {
800     return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
801   }
802
803   bool GetNodes (const long             theLinkID,
804                  const SMDS_MeshNode* & theNode1,
805                  const SMDS_MeshNode* & theNode2) const
806   {
807     theNode1 = myMesh->FindNode( theLinkID / myMaxID );
808     if ( !theNode1 ) return false;
809     theNode2 = myMesh->FindNode( theLinkID % myMaxID );
810     if ( !theNode2 ) return false;
811     return true;
812   }
813
814  private:
815   LinkID_Gen();
816   const SMESHDS_Mesh* myMesh;
817   long                myMaxID;
818 };
819
820 //=======================================================================
821 //function : TriToQuad
822 //purpose  : Fuse neighbour triangles into quadrangles.
823 //           theCrit is used to select a neighbour to fuse with.
824 //           theMaxAngle is a max angle between element normals at which
825 //           fusion is still performed.
826 //=======================================================================
827
828 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> &       theElems,
829                                   SMESH::Controls::NumericalFunctorPtr theCrit,
830                                   const double                         theMaxAngle)
831 {
832   MESSAGE( "::TriToQuad()" );
833
834   if ( !theCrit.get() )
835     return false;
836
837   SMESHDS_Mesh * aMesh = GetMeshDS();
838   LinkID_Gen aLinkID_Gen( aMesh );
839
840
841   // Prepare data for algo: build
842   // 1. map of elements with their linkIDs
843   // 2. map of linkIDs with their elements
844
845   map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
846   map< long, list< const SMDS_MeshElement* > >::iterator itLE;
847   map< const SMDS_MeshElement*, set< long > >  mapEl_setLi;
848   map< const SMDS_MeshElement*, set< long > >::iterator itEL;
849
850   set<const SMDS_MeshElement*>::iterator itElem;
851   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
852   {
853     const SMDS_MeshElement* elem = (*itElem);
854     if ( !elem || elem->NbNodes() != 3 )
855       continue;
856
857     // retrieve element nodes
858     const SMDS_MeshNode* aNodes [4];
859     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
860     int i = 0;
861     while ( itN->more() )
862       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
863     ASSERT( i == 3 );
864     aNodes[ 3 ] = aNodes[ 0 ];
865
866     // fill maps
867     for ( i = 0; i < 3; i++ )
868     {
869       long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
870       // check if elements sharing a link can be fused
871       itLE = mapLi_listEl.find( linkID );
872       if ( itLE != mapLi_listEl.end() )
873       {
874         if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
875           continue;
876         const SMDS_MeshElement* elem2 = (*itLE).second.front();
877 //         if ( FindShape( elem ) != FindShape( elem2 ))
878 //           continue; // do not fuse triangles laying on different shapes
879         if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
880           continue; // avoid making badly shaped quads
881         (*itLE).second.push_back( elem );
882       }
883       else
884         mapLi_listEl[ linkID ].push_back( elem );
885       mapEl_setLi [ elem ].insert( linkID );
886     }
887   }
888   // Clean the maps from the links shared by a sole element, ie
889   // links to which only one element is bound in mapLi_listEl
890
891   for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
892   {
893     int nbElems = (*itLE).second.size();
894     if ( nbElems < 2  ) {
895       const SMDS_MeshElement* elem = (*itLE).second.front();
896       long link = (*itLE).first;
897       mapEl_setLi[ elem ].erase( link );
898       if ( mapEl_setLi[ elem ].empty() )
899         mapEl_setLi.erase( elem );
900     }
901   }
902
903   // Algo: fuse triangles into quadrangles
904
905   while ( ! mapEl_setLi.empty() )
906   {
907     // Look for the start element:
908     // the element having the least nb of shared links
909
910     const SMDS_MeshElement* startElem = 0;
911     int minNbLinks = 4;
912     for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
913     {
914       int nbLinks = (*itEL).second.size();
915       if ( nbLinks < minNbLinks )
916       {
917         startElem = (*itEL).first;
918         minNbLinks = nbLinks;
919         if ( minNbLinks == 1 )
920           break;
921       }
922     }
923
924     // search elements to fuse starting from startElem or links of elements
925     // fused earlyer - startLinks
926     list< long > startLinks;
927     while ( startElem || !startLinks.empty() )
928     {
929       while ( !startElem && !startLinks.empty() )
930       {
931         // Get an element to start, by a link
932         long linkId = startLinks.front();
933         startLinks.pop_front();
934         itLE = mapLi_listEl.find( linkId );
935         if ( itLE != mapLi_listEl.end() )
936         {
937           list< const SMDS_MeshElement* > & listElem = (*itLE).second;
938           list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
939           for ( ; itE != listElem.end() ; itE++ )
940             if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
941               startElem = (*itE);
942           mapLi_listEl.erase( itLE );
943         }
944       }
945
946       if ( startElem )
947       {
948         // Get candidates to be fused
949
950         const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
951         long link12, link13;
952         startElem = 0;
953         ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
954         set< long >& setLi = mapEl_setLi[ tr1 ];
955         ASSERT( !setLi.empty() );
956         set< long >::iterator itLi;
957         for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
958         {
959           long linkID = (*itLi);
960           itLE = mapLi_listEl.find( linkID );
961           if ( itLE == mapLi_listEl.end() )
962             continue;
963           const SMDS_MeshElement* elem = (*itLE).second.front();
964           if ( elem == tr1 )
965             elem = (*itLE).second.back();
966           mapLi_listEl.erase( itLE );
967           if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
968             continue;
969           if ( tr2 )
970           {
971             tr3 = elem;
972             link13 = linkID;
973           }
974           else
975           {
976             tr2 = elem;
977             link12 = linkID;
978           }
979
980           // add other links of elem to list of links to re-start from
981           set< long >& links = mapEl_setLi[ elem ];
982           set< long >::iterator it;
983           for ( it = links.begin(); it != links.end(); it++ )
984           {
985             long linkID2 = (*it);
986             if ( linkID2 != linkID )
987               startLinks.push_back( linkID2 );
988           }
989         }
990
991         // Get nodes of possible quadrangles
992
993         const SMDS_MeshNode *n12 [4], *n13 [4];
994         bool Ok12 = false, Ok13 = false;
995         const SMDS_MeshNode *linkNode1, *linkNode2;
996         if ( tr2 &&
997              aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
998              getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
999           Ok12 = true;
1000         if ( tr3 &&
1001              aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
1002              getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1003           Ok13 = true;
1004
1005         // Choose a pair to fuse
1006
1007         if ( Ok12 && Ok13 )
1008         {
1009           SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
1010           SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
1011           double aBadRate12 = getBadRate( &quad12, theCrit );
1012           double aBadRate13 = getBadRate( &quad13, theCrit );
1013           if (  aBadRate13 < aBadRate12 )
1014             Ok12 = false;
1015           else
1016             Ok13 = false;
1017         }
1018
1019
1020         // Make quadrangles
1021         // and remove fused elems and removed links from the maps
1022
1023         mapEl_setLi.erase( tr1 );
1024         if ( Ok12 )
1025         {
1026           mapEl_setLi.erase( tr2 );
1027           mapLi_listEl.erase( link12 );
1028           aMesh->ChangeElementNodes( tr1, n12, 4 );
1029           aMesh->RemoveElement( tr2 );
1030         }
1031         else if ( Ok13 )
1032         {
1033           mapEl_setLi.erase( tr3 );
1034           mapLi_listEl.erase( link13 );
1035           aMesh->ChangeElementNodes( tr1, n13, 4 );
1036           aMesh->RemoveElement( tr3 );
1037         }
1038
1039         // Next element to fuse: the rejected one
1040         if ( tr3 )
1041           startElem = Ok12 ? tr3 : tr2;
1042
1043       } // if ( startElem )
1044     } // while ( startElem || !startLinks.empty() )
1045   } // while ( ! mapEl_setLi.empty() )
1046
1047   return true;
1048 }
1049
1050
1051 /*#define DUMPSO(txt) \
1052 //  cout << txt << endl;
1053 //=============================================================================
1054 //
1055 //
1056 //
1057 //=============================================================================
1058 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1059 {
1060   if ( i1 == i2 )
1061     return;
1062   int tmp = idNodes[ i1 ];
1063   idNodes[ i1 ] = idNodes[ i2 ];
1064   idNodes[ i2 ] = tmp;
1065   gp_Pnt Ptmp = P[ i1 ];
1066   P[ i1 ] = P[ i2 ];
1067   P[ i2 ] = Ptmp;
1068   DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1069 }
1070
1071 //=======================================================================
1072 //function : SortQuadNodes
1073 //purpose  : Set 4 nodes of a quadrangle face in a good order.
1074 //           Swap 1<->2 or 2<->3 nodes and correspondingly return
1075 //           1 or 2 else 0.
1076 //=======================================================================
1077
1078 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1079                                      int               idNodes[] )
1080 {
1081   gp_Pnt P[4];
1082   int i;
1083   for ( i = 0; i < 4; i++ ) {
1084     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1085     if ( !n ) return 0;
1086     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1087   }
1088
1089   gp_Vec V1(P[0], P[1]);
1090   gp_Vec V2(P[0], P[2]);
1091   gp_Vec V3(P[0], P[3]);
1092
1093   gp_Vec Cross1 = V1 ^ V2;
1094   gp_Vec Cross2 = V2 ^ V3;
1095
1096   i = 0;
1097   if (Cross1.Dot(Cross2) < 0)
1098   {
1099     Cross1 = V2 ^ V1;
1100     Cross2 = V1 ^ V3;
1101
1102     if (Cross1.Dot(Cross2) < 0)
1103       i = 2;
1104     else
1105       i = 1;
1106     swap ( i, i + 1, idNodes, P );
1107
1108 //     for ( int ii = 0; ii < 4; ii++ ) {
1109 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1110 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1111 //     }
1112   }
1113   return i;
1114 }
1115
1116 //=======================================================================
1117 //function : SortHexaNodes
1118 //purpose  : Set 8 nodes of a hexahedron in a good order.
1119 //           Return success status
1120 //=======================================================================
1121
1122 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1123                                       int               idNodes[] )
1124 {
1125   gp_Pnt P[8];
1126   int i;
1127   DUMPSO( "INPUT: ========================================");
1128   for ( i = 0; i < 8; i++ ) {
1129     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1130     if ( !n ) return false;
1131     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1132     DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1133   }
1134   DUMPSO( "========================================");
1135
1136
1137   set<int> faceNodes;  // ids of bottom face nodes, to be found
1138   set<int> checkedId1; // ids of tried 2-nd nodes
1139   Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1140   const Standard_Real tol = 1.e-6;   // tolerance to find nodes in plane
1141   int iMin, iLoop1 = 0;
1142
1143   // Loop to try the 2-nd nodes
1144
1145   while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1146   {
1147     // Find not checked 2-nd node
1148     for ( i = 1; i < 8; i++ )
1149       if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1150         int id1 = idNodes[i];
1151         swap ( 1, i, idNodes, P );
1152         checkedId1.insert ( id1 );
1153         break;
1154       }
1155
1156     // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1157     // ie that all but meybe one (id3 which is on the same face) nodes
1158     // lay on the same side from the triangle plane.
1159
1160     bool manyInPlane = false; // more than 4 nodes lay in plane
1161     int iLoop2 = 0;
1162     while ( ++iLoop2 < 6 ) {
1163
1164       // get 1-2-3 plane coeffs
1165       Standard_Real A, B, C, D;
1166       gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1167       if ( N.SquareMagnitude() > gp::Resolution() )
1168       {
1169         gp_Pln pln ( P[0], N );
1170         pln.Coefficients( A, B, C, D );
1171
1172         // find the node (iMin) closest to pln
1173         Standard_Real dist[ 8 ], minDist = DBL_MAX;
1174         set<int> idInPln;
1175         for ( i = 3; i < 8; i++ ) {
1176           dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1177           if ( fabs( dist[i] ) < minDist ) {
1178             minDist = fabs( dist[i] );
1179             iMin = i;
1180           }
1181           if ( fabs( dist[i] ) <= tol )
1182             idInPln.insert( idNodes[i] );
1183         }
1184
1185         // there should not be more than 4 nodes in bottom plane
1186         if ( idInPln.size() > 1 )
1187         {
1188           DUMPSO( "### idInPln.size() = " << idInPln.size());
1189           // idInPlane does not contain the first 3 nodes
1190           if ( manyInPlane || idInPln.size() == 5)
1191             return false; // all nodes in one plane
1192           manyInPlane = true;
1193
1194           // set the 1-st node to be not in plane
1195           for ( i = 3; i < 8; i++ ) {
1196             if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1197               DUMPSO( "### Reset 0-th node");
1198               swap( 0, i, idNodes, P );
1199               break;
1200             }
1201           }
1202
1203           // reset to re-check second nodes
1204           leastDist = DBL_MAX;
1205           faceNodes.clear();
1206           checkedId1.clear();
1207           iLoop1 = 0;
1208           break; // from iLoop2;
1209         }
1210
1211         // check that the other 4 nodes are on the same side
1212         bool sameSide = true;
1213         bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1214         for ( i = 3; sameSide && i < 8; i++ ) {
1215           if ( i != iMin )
1216             sameSide = ( isNeg == dist[i] <= 0.);
1217         }
1218
1219         // keep best solution
1220         if ( sameSide && minDist < leastDist ) {
1221           leastDist = minDist;
1222           faceNodes.clear();
1223           faceNodes.insert( idNodes[ 1 ] );
1224           faceNodes.insert( idNodes[ 2 ] );
1225           faceNodes.insert( idNodes[ iMin ] );
1226           DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1227             << " leastDist = " << leastDist);
1228           if ( leastDist <= DBL_MIN )
1229             break;
1230         }
1231       }
1232
1233       // set next 3-d node to check
1234       int iNext = 2 + iLoop2;
1235       if ( iNext < 8 ) {
1236         DUMPSO( "Try 2-nd");
1237         swap ( 2, iNext, idNodes, P );
1238       }
1239     } // while ( iLoop2 < 6 )
1240   } // iLoop1
1241
1242   if ( faceNodes.empty() ) return false;
1243
1244   // Put the faceNodes in proper places
1245   for ( i = 4; i < 8; i++ ) {
1246     if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1247       // find a place to put
1248       int iTo = 1;
1249       while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1250         iTo++;
1251       DUMPSO( "Set faceNodes");
1252       swap ( iTo, i, idNodes, P );
1253     }
1254   }
1255
1256
1257   // Set nodes of the found bottom face in good order
1258   DUMPSO( " Found bottom face: ");
1259   i = SortQuadNodes( theMesh, idNodes );
1260   if ( i ) {
1261     gp_Pnt Ptmp = P[ i ];
1262     P[ i ] = P[ i+1 ];
1263     P[ i+1 ] = Ptmp;
1264   }
1265 //   else
1266 //     for ( int ii = 0; ii < 4; ii++ ) {
1267 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1268 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1269 //    }
1270
1271   // Gravity center of the top and bottom faces
1272   gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1273   gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1274
1275   // Get direction from the bottom to the top face
1276   gp_Vec upDir ( aGCb, aGCt );
1277   Standard_Real upDirSize = upDir.Magnitude();
1278   if ( upDirSize <= gp::Resolution() ) return false;
1279   upDir / upDirSize;
1280
1281   // Assure that the bottom face normal points up
1282   gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1283   Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1284   if ( Nb.Dot( upDir ) < 0 ) {
1285     DUMPSO( "Reverse bottom face");
1286     swap( 1, 3, idNodes, P );
1287   }
1288
1289   // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1290   Standard_Real minDist = DBL_MAX;
1291   for ( i = 4; i < 8; i++ ) {
1292     // projection of P[i] to the plane defined by P[0] and upDir
1293     gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1294     Standard_Real sqDist = P[0].SquareDistance( Pp );
1295     if ( sqDist < minDist ) {
1296       minDist = sqDist;
1297       iMin = i;
1298     }
1299   }
1300   DUMPSO( "Set 4-th");
1301   swap ( 4, iMin, idNodes, P );
1302
1303   // Set nodes of the top face in good order
1304   DUMPSO( "Sort top face");
1305   i = SortQuadNodes( theMesh, &idNodes[4] );
1306   if ( i ) {
1307     i += 4;
1308     gp_Pnt Ptmp = P[ i ];
1309     P[ i ] = P[ i+1 ];
1310     P[ i+1 ] = Ptmp;
1311   }
1312
1313   // Assure that direction of the top face normal is from the bottom face
1314   gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1315   Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1316   if ( Nt.Dot( upDir ) < 0 ) {
1317     DUMPSO( "Reverse top face");
1318     swap( 5, 7, idNodes, P );
1319   }
1320
1321 //   DUMPSO( "OUTPUT: ========================================");
1322 //   for ( i = 0; i < 8; i++ ) {
1323 //     float *p = ugrid->GetPoint(idNodes[i]);
1324 //     DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1325 //   }
1326
1327   return true;
1328 }*/
1329
1330 //=======================================================================
1331 //function : laplacianSmooth
1332 //purpose  : pulls theNode toward the center of surrounding nodes directly
1333 //           connected to that node along an element edge
1334 //=======================================================================
1335
1336 void laplacianSmooth(const SMDS_MeshNode*                 theNode,
1337                      const Handle(Geom_Surface)&          theSurface,
1338                      map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1339 {
1340   // find surrounding nodes
1341
1342   set< const SMDS_MeshNode* > nodeSet;
1343   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1344   while ( elemIt->more() )
1345   {
1346     const SMDS_MeshElement* elem = elemIt->next();
1347     if ( elem->GetType() != SMDSAbs_Face )
1348       continue;
1349
1350     // put all nodes in array
1351     int nbNodes = 0, iNode = 0;
1352     vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1353     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1354     while ( itN->more() )
1355     {
1356       aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1357       if ( aNodes[ nbNodes ] == theNode )
1358         iNode = nbNodes; // index of theNode within aNodes
1359       nbNodes++;
1360     }
1361     // add linked nodes
1362     int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1363     nodeSet.insert( aNodes[ iAfter ]);
1364     int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1365     nodeSet.insert( aNodes[ iBefore ]);
1366   }
1367
1368   // compute new coodrs
1369
1370   double coord[] = { 0., 0., 0. };
1371   set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1372   for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1373     const SMDS_MeshNode* node = (*nodeSetIt);
1374     if ( theSurface.IsNull() ) { // smooth in 3D
1375       coord[0] += node->X();
1376       coord[1] += node->Y();
1377       coord[2] += node->Z();
1378     }
1379     else { // smooth in 2D
1380       ASSERT( theUVMap.find( node ) != theUVMap.end() );
1381       gp_XY* uv = theUVMap[ node ];
1382       coord[0] += uv->X();
1383       coord[1] += uv->Y();
1384     }
1385   }
1386   int nbNodes = nodeSet.size();
1387   if ( !nbNodes )
1388     return;
1389   coord[0] /= nbNodes;
1390   coord[1] /= nbNodes;
1391
1392   if ( !theSurface.IsNull() ) {
1393     ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1394     theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1395     gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1396     coord[0] = p3d.X();
1397     coord[1] = p3d.Y();
1398     coord[2] = p3d.Z();
1399   }
1400   else
1401     coord[2] /= nbNodes;
1402
1403   // move node
1404
1405   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1406 }
1407
1408 //=======================================================================
1409 //function : centroidalSmooth
1410 //purpose  : pulls theNode toward the element-area-weighted centroid of the
1411 //           surrounding elements
1412 //=======================================================================
1413
1414 void centroidalSmooth(const SMDS_MeshNode*                 theNode,
1415                       const Handle(Geom_Surface)&          theSurface,
1416                       map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1417 {
1418   gp_XYZ aNewXYZ(0.,0.,0.);
1419   SMESH::Controls::Area anAreaFunc;
1420   double totalArea = 0.;
1421   int nbElems = 0;
1422
1423   // compute new XYZ
1424
1425   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1426   while ( elemIt->more() )
1427   {
1428     const SMDS_MeshElement* elem = elemIt->next();
1429     if ( elem->GetType() != SMDSAbs_Face )
1430       continue;
1431     nbElems++;
1432
1433     gp_XYZ elemCenter(0.,0.,0.);
1434     SMESH::Controls::TSequenceOfXYZ aNodePoints;
1435     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1436     while ( itN->more() )
1437     {
1438       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1439       gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1440       aNodePoints.push_back( aP );
1441       if ( !theSurface.IsNull() ) { // smooth in 2D
1442         ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
1443         gp_XY* uv = theUVMap[ aNode ];
1444         aP.SetCoord( uv->X(), uv->Y(), 0. );
1445       }
1446       elemCenter += aP;
1447     }
1448     double elemArea = anAreaFunc.GetValue( aNodePoints );
1449     totalArea += elemArea;
1450     elemCenter /= elem->NbNodes();
1451     aNewXYZ += elemCenter * elemArea;
1452   }
1453   aNewXYZ /= totalArea;
1454   if ( !theSurface.IsNull() ) {
1455     ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1456     theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1457     aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1458   }
1459
1460   // move node
1461
1462   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1463 }
1464
1465 //=======================================================================
1466 //function : getClosestUV
1467 //purpose  : return UV of closest projection
1468 //=======================================================================
1469
1470 static bool getClosestUV (Extrema_GenExtPS& projector,
1471                           const gp_Pnt&     point,
1472                           gp_XY &           result)
1473 {
1474   projector.Perform( point );
1475   if ( projector.IsDone() ) {
1476     double u, v, minVal = DBL_MAX;
1477     for ( int i = projector.NbExt(); i > 0; i-- )
1478       if ( projector.Value( i ) < minVal ) {
1479         minVal = projector.Value( i );
1480         projector.Point( i ).Parameter( u, v );
1481       }
1482     result.SetCoord( u, v );
1483     return true;
1484   }
1485   return false;
1486 }
1487
1488 //=======================================================================
1489 //function : Smooth
1490 //purpose  : Smooth theElements during theNbIterations or until a worst
1491 //           element has aspect ratio <= theTgtAspectRatio.
1492 //           Aspect Ratio varies in range [1.0, inf].
1493 //           If theElements is empty, the whole mesh is smoothed.
1494 //           theFixedNodes contains additionally fixed nodes. Nodes built
1495 //           on edges and boundary nodes are always fixed.
1496 //=======================================================================
1497
1498 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1499                                set<const SMDS_MeshNode*> &    theFixedNodes,
1500                                const SmoothMethod             theSmoothMethod,
1501                                const int                      theNbIterations,
1502                                double                         theTgtAspectRatio,
1503                                const bool                     the2D)
1504 {
1505   MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1506
1507   if ( theTgtAspectRatio < 1.0 )
1508     theTgtAspectRatio = 1.0;
1509
1510   SMESH::Controls::AspectRatio aQualityFunc;
1511
1512   SMESHDS_Mesh* aMesh = GetMeshDS();
1513
1514   if ( theElems.empty() ) {
1515     // add all faces to theElems
1516     SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1517     while ( fIt->more() )
1518       theElems.insert( fIt->next() );
1519   }
1520   // get all face ids theElems are on
1521   set< int > faceIdSet;
1522   set< const SMDS_MeshElement* >::iterator itElem;
1523   if ( the2D )
1524     for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1525       int fId = FindShape( *itElem );
1526       // check that corresponding submesh exists and a shape is face
1527       if (fId &&
1528           faceIdSet.find( fId ) == faceIdSet.end() &&
1529           aMesh->MeshElements( fId )) {
1530         TopoDS_Shape F = aMesh->IndexToShape( fId );
1531         if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1532           faceIdSet.insert( fId );
1533       }
1534     }
1535   faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1536
1537   // ===============================================
1538   // smooth elements on each TopoDS_Face separately
1539   // ===============================================
1540
1541   set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1542   for ( ; fId != faceIdSet.rend(); ++fId )
1543   {
1544     // get face surface and submesh
1545     Handle(Geom_Surface) surface;
1546     SMESHDS_SubMesh* faceSubMesh = 0;
1547     TopoDS_Face face;
1548     double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
1549     double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1550     bool isUPeriodic = false, isVPeriodic = false;
1551     if ( *fId ) {
1552       face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1553       surface = BRep_Tool::Surface( face );
1554       faceSubMesh = aMesh->MeshElements( *fId );
1555       fToler2 = BRep_Tool::Tolerance( face );
1556       fToler2 *= fToler2 * 10.;
1557       isUPeriodic = surface->IsUPeriodic();
1558       if ( isUPeriodic )
1559         vPeriod = surface->UPeriod();
1560       isVPeriodic = surface->IsVPeriodic();
1561       if ( isVPeriodic )
1562         uPeriod = surface->VPeriod();
1563       surface->Bounds( u1, u2, v1, v2 );
1564     }
1565     // ---------------------------------------------------------
1566     // for elements on a face, find movable and fixed nodes and
1567     // compute UV for them
1568     // ---------------------------------------------------------
1569     bool checkBoundaryNodes = false;
1570     set<const SMDS_MeshNode*> setMovableNodes;
1571     map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1572     list< gp_XY > listUV; // uvs the 2 uvMaps refer to
1573     list< const SMDS_MeshElement* > elemsOnFace;
1574
1575     Extrema_GenExtPS projector;
1576     GeomAdaptor_Surface surfAdaptor;
1577     if ( !surface.IsNull() ) {
1578       surfAdaptor.Load( surface );
1579       projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1580     }
1581     int nbElemOnFace = 0;
1582     itElem = theElems.begin();
1583      // loop on not yet smoothed elements: look for elems on a face
1584     while ( itElem != theElems.end() )
1585     {
1586       if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
1587         break; // all elements found
1588
1589       const SMDS_MeshElement* elem = (*itElem);
1590       if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1591           ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1592         ++itElem;
1593         continue;
1594       }
1595       elemsOnFace.push_back( elem );
1596       theElems.erase( itElem++ );
1597       nbElemOnFace++;
1598
1599       // get movable nodes of elem
1600       const SMDS_MeshNode* node;
1601       SMDS_TypeOfPosition posType;
1602       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1603       while ( itN->more() ) {
1604         node = static_cast<const SMDS_MeshNode*>( itN->next() );
1605         const SMDS_PositionPtr& pos = node->GetPosition();
1606         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1607         if (posType != SMDS_TOP_EDGE &&
1608             posType != SMDS_TOP_VERTEX &&
1609             theFixedNodes.find( node ) == theFixedNodes.end())
1610         {
1611           // check if all faces around the node are on faceSubMesh
1612           // because a node on edge may be bound to face
1613           SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1614           bool all = true;
1615           if ( faceSubMesh ) {
1616             while ( eIt->more() && all ) {
1617               const SMDS_MeshElement* e = eIt->next();
1618               if ( e->GetType() == SMDSAbs_Face )
1619                 all = faceSubMesh->Contains( e );
1620             }
1621           }
1622           if ( all )
1623             setMovableNodes.insert( node );
1624           else
1625             checkBoundaryNodes = true;
1626         }
1627         if ( posType == SMDS_TOP_3DSPACE )
1628           checkBoundaryNodes = true;
1629       }
1630
1631       if ( surface.IsNull() )
1632         continue;
1633
1634       // get nodes to check UV
1635       list< const SMDS_MeshNode* > uvCheckNodes;
1636       itN = elem->nodesIterator();
1637       while ( itN->more() ) {
1638         node = static_cast<const SMDS_MeshNode*>( itN->next() );
1639         if ( uvMap.find( node ) == uvMap.end() )
1640           uvCheckNodes.push_back( node );
1641         // add nodes of elems sharing node
1642 //         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1643 //         while ( eIt->more() ) {
1644 //           const SMDS_MeshElement* e = eIt->next();
1645 //           if ( e != elem && e->GetType() == SMDSAbs_Face ) {
1646 //             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1647 //             while ( nIt->more() ) {
1648 //               const SMDS_MeshNode* n =
1649 //                 static_cast<const SMDS_MeshNode*>( nIt->next() );
1650 //               if ( uvMap.find( n ) == uvMap.end() )
1651 //                 uvCheckNodes.push_back( n );
1652 //             }
1653 //           }
1654 //         }
1655       }
1656       // check UV on face
1657       list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
1658       for ( ; n != uvCheckNodes.end(); ++n )
1659       {
1660         node = *n;
1661         gp_XY uv( 0, 0 );
1662         const SMDS_PositionPtr& pos = node->GetPosition();
1663         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1664         // get existing UV
1665         switch ( posType ) {
1666         case SMDS_TOP_FACE: {
1667           SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1668           uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1669           break;
1670         }
1671         case SMDS_TOP_EDGE: {
1672           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1673           Handle(Geom2d_Curve) pcurve;
1674           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
1675             pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
1676           if ( !pcurve.IsNull() ) {
1677             double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
1678             uv = pcurve->Value( u ).XY();
1679           }
1680           break;
1681         }
1682         case SMDS_TOP_VERTEX: {
1683           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1684           if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
1685             uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
1686           break;
1687         }
1688         default:;
1689         }
1690         // check existing UV
1691         bool project = true;
1692         gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1693         double dist1 = DBL_MAX, dist2 = 0;
1694         if ( posType != SMDS_TOP_3DSPACE ) {
1695           dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
1696           project = dist1 > fToler2;
1697         }
1698         if ( project ) { // compute new UV
1699           gp_XY newUV;
1700           if ( !getClosestUV( projector, pNode, newUV )) {
1701             MESSAGE("Node Projection Failed " << node);
1702           }
1703           else {
1704             if ( isUPeriodic )
1705               newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
1706             if ( isVPeriodic )
1707               newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
1708             // check new UV
1709             if ( posType != SMDS_TOP_3DSPACE )
1710               dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
1711             if ( dist2 < dist1 )
1712               uv = newUV;
1713           }
1714         }
1715         // store UV in the map
1716         listUV.push_back( uv );
1717         uvMap.insert( make_pair( node, &listUV.back() ));
1718       }
1719     } // loop on not yet smoothed elements
1720
1721     if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
1722       checkBoundaryNodes = true;
1723
1724     // fix nodes on mesh boundary
1725
1726     if ( checkBoundaryNodes )
1727     {
1728       typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1729       map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1730       map< TLink, int >::iterator link_nb;
1731       // put all elements links to linkNbMap
1732       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1733       for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1734       {
1735         // put elem nodes in array
1736         vector< const SMDS_MeshNode* > nodes;
1737         nodes.reserve( (*elemIt)->NbNodes() + 1 );
1738         SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1739         while ( itN->more() )
1740           nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1741         nodes.push_back( nodes.front() );
1742         // loop on elem links: insert them in linkNbMap
1743         for ( int iN = 1; iN < nodes.size(); ++iN ) {
1744           TLink link;
1745           if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1746             link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1747           else
1748             link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1749           link_nb = linkNbMap.find( link );
1750           if ( link_nb == linkNbMap.end() )
1751             linkNbMap.insert( make_pair ( link, 1 ));
1752           else
1753             link_nb->second++;
1754         }
1755       }
1756       // remove nodes that are in links encountered only once from setMovableNodes
1757       for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1758         if ( link_nb->second == 1 ) {
1759           setMovableNodes.erase( link_nb->first.first );
1760           setMovableNodes.erase( link_nb->first.second );
1761         }
1762       }
1763     }
1764
1765     // -----------------------------------------------------
1766     // for nodes on seam edge, compute one more UV ( uvMap2 );
1767     // find movable nodes linked to nodes on seam and which
1768     // are to be smoothed using the second UV ( uvMap2 )
1769     // -----------------------------------------------------
1770
1771     set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1772     if ( !surface.IsNull() )
1773     {
1774       TopExp_Explorer eExp( face, TopAbs_EDGE );
1775       for ( ; eExp.More(); eExp.Next() )
1776       {
1777         TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1778         if ( !BRep_Tool::IsClosed( edge, face ))
1779           continue;
1780         SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1781         if ( !sm ) continue;
1782         // find out which parameter varies for a node on seam
1783         double f,l;
1784         gp_Pnt2d uv1, uv2;
1785         Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1786         if ( pcurve.IsNull() ) continue;
1787         uv1 = pcurve->Value( f );
1788         edge.Reverse();
1789         pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1790         if ( pcurve.IsNull() ) continue;
1791         uv2 = pcurve->Value( f );
1792         int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1793         // assure uv1 < uv2
1794         if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1795           gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1796         }
1797         // get nodes on seam and its vertices
1798         list< const SMDS_MeshNode* > seamNodes;
1799         SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1800         while ( nSeamIt->more() )
1801           seamNodes.push_back( nSeamIt->next() );
1802         TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1803         for ( ; vExp.More(); vExp.Next() ) {
1804           sm = aMesh->MeshElements( vExp.Current() );
1805           if ( sm ) {
1806             nSeamIt = sm->GetNodes();
1807             while ( nSeamIt->more() )
1808               seamNodes.push_back( nSeamIt->next() );
1809           }
1810         }
1811         // loop on nodes on seam
1812         list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1813         for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1814         {
1815           const SMDS_MeshNode* nSeam = *noSeIt;
1816           map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1817           if ( n_uv == uvMap.end() )
1818             continue;
1819           // set the first UV
1820           n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1821           // set the second UV
1822           listUV.push_back( *n_uv->second );
1823           listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1824           if ( uvMap2.empty() )
1825             uvMap2 = uvMap; // copy the uvMap contents
1826           uvMap2[ nSeam ] = &listUV.back();
1827
1828           // collect movable nodes linked to ones on seam in nodesNearSeam
1829           SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1830           while ( eIt->more() )
1831           {
1832             const SMDS_MeshElement* e = eIt->next();
1833             if ( e->GetType() != SMDSAbs_Face )
1834               continue;
1835             int nbUseMap1 = 0, nbUseMap2 = 0;
1836             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1837             while ( nIt->more() )
1838             {
1839               const SMDS_MeshNode* n =
1840                 static_cast<const SMDS_MeshNode*>( nIt->next() );
1841               if (n == nSeam ||
1842                   setMovableNodes.find( n ) == setMovableNodes.end() )
1843                 continue;
1844               // add only nodes being closer to uv2 than to uv1
1845               gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1846                            0.5 * ( n->Y() + nSeam->Y() ),
1847                            0.5 * ( n->Z() + nSeam->Z() ));
1848               gp_XY uv;
1849               getClosestUV( projector, pMid, uv );
1850               if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1851                 nodesNearSeam.insert( n );
1852                 nbUseMap2++;
1853               }
1854               else
1855                 nbUseMap1++;
1856             }
1857             // for centroidalSmooth all element nodes must
1858             // be on one side of a seam
1859             if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1860             {
1861               SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1862               while ( nIt->more() ) {
1863                 const SMDS_MeshNode* n =
1864                   static_cast<const SMDS_MeshNode*>( nIt->next() );
1865                 setMovableNodes.erase( n );
1866               }
1867             }
1868           }
1869         } // loop on nodes on seam
1870       } // loop on edge of a face
1871     } // if ( !face.IsNull() )
1872
1873     if ( setMovableNodes.empty() ) {
1874       MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
1875       continue; // goto next face
1876     }
1877
1878     // -------------
1879     // SMOOTHING //
1880     // -------------
1881
1882     int it = -1;
1883     double maxRatio = -1., maxDisplacement = -1.;
1884     set<const SMDS_MeshNode*>::iterator nodeToMove;
1885     for ( it = 0; it < theNbIterations; it++ )
1886     {
1887       maxDisplacement = 0.;
1888       nodeToMove = setMovableNodes.begin();
1889       for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1890       {
1891         const SMDS_MeshNode* node = (*nodeToMove);
1892         gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1893
1894         // smooth
1895         bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1896         if ( theSmoothMethod == LAPLACIAN )
1897           laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1898         else
1899           centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1900
1901         // node displacement
1902         gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1903         Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1904         if ( aDispl > maxDisplacement )
1905           maxDisplacement = aDispl;
1906       }
1907       // no node movement => exit
1908       if ( maxDisplacement < 1.e-16 ) {
1909         MESSAGE("-- no node movement --");
1910         break;
1911       }
1912
1913       // check elements quality
1914       maxRatio  = 0;
1915       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1916       for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1917       {
1918         const SMDS_MeshElement* elem = (*elemIt);
1919         if ( !elem || elem->GetType() != SMDSAbs_Face )
1920           continue;
1921         SMESH::Controls::TSequenceOfXYZ aPoints;
1922         if ( aQualityFunc.GetPoints( elem, aPoints )) {
1923           double aValue = aQualityFunc.GetValue( aPoints );
1924           if ( aValue > maxRatio )
1925             maxRatio = aValue;
1926         }
1927       }
1928       if ( maxRatio <= theTgtAspectRatio ) {
1929         MESSAGE("-- quality achived --");
1930         break;
1931       }
1932       if (it+1 == theNbIterations) {
1933         MESSAGE("-- Iteration limit exceeded --");
1934       }
1935     } // smoothing iterations
1936
1937     MESSAGE(" Face id: " << *fId <<
1938             " Nb iterstions: " << it <<
1939             " Displacement: " << maxDisplacement <<
1940             " Aspect Ratio " << maxRatio);
1941
1942     // ---------------------------------------
1943     // new nodes positions are computed,
1944     // record movement in DS and set new UV
1945     // ---------------------------------------
1946
1947     nodeToMove = setMovableNodes.begin();
1948     for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1949     {
1950       SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1951       aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1952       map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1953       if ( node_uv != uvMap.end() ) {
1954         gp_XY* uv = node_uv->second;
1955         node->SetPosition
1956           ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1957       }
1958     }
1959
1960   } // loop on face ids
1961 }
1962
1963 //=======================================================================
1964 //function : isReverse
1965 //purpose  : Return true if normal of prevNodes is not co-directied with
1966 //           gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1967 //           iNotSame is where prevNodes and nextNodes are different
1968 //=======================================================================
1969
1970 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1971                       const SMDS_MeshNode* nextNodes[],
1972                       const int            nbNodes,
1973                       const int            iNotSame)
1974 {
1975   int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1976   int iAfterNotSame  = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1977
1978   const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1979   const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1980   const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1981   const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1982
1983   gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1984   gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1985   gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1986   gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1987
1988   gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1989
1990   return (vA ^ vB) * vN < 0.0;
1991 }
1992
1993 //=======================================================================
1994 //function : sweepElement
1995 //purpose  :
1996 //=======================================================================
1997
1998 static void sweepElement(SMESHDS_Mesh*                         aMesh,
1999                          const SMDS_MeshElement*               elem,
2000                          const vector<TNodeOfNodeListMapItr> & newNodesItVec,
2001                          list<const SMDS_MeshElement*>&        newElems)
2002 {
2003   // Loop on elem nodes:
2004   // find new nodes and detect same nodes indices
2005   int nbNodes = elem->NbNodes();
2006   list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
2007   const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
2008   int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
2009
2010   for ( iNode = 0; iNode < nbNodes; iNode++ )
2011   {
2012     TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
2013     const SMDS_MeshNode*                 node         = nnIt->first;
2014     const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
2015     if ( listNewNodes.empty() )
2016       return;
2017
2018     itNN[ iNode ] = listNewNodes.begin();
2019     prevNod[ iNode ] = node;
2020     nextNod[ iNode ] = listNewNodes.front();
2021     if ( prevNod[ iNode ] != nextNod [ iNode ])
2022       iNotSameNode = iNode;
2023     else {
2024       iSameNode = iNode;
2025       nbSame++;
2026     }
2027   }
2028   if ( nbSame == nbNodes || nbSame > 2) {
2029     MESSAGE( " Too many same nodes of element " << elem->GetID() );
2030     return;
2031   }
2032
2033   int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
2034   if ( nbSame > 0 ) {
2035     iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
2036     iAfterSame  = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2037     iOpposSame  = ( iSameNode - 2 < 0  ? iSameNode + 2 : iSameNode - 2 );
2038   }
2039
2040   // check element orientation
2041   int i0 = 0, i2 = 2;
2042   if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2043     //MESSAGE("Reversed elem " << elem );
2044     i0 = 2;
2045     i2 = 0;
2046     if ( nbSame > 0 ) {
2047       int iAB = iAfterSame + iBeforeSame;
2048       iBeforeSame = iAB - iBeforeSame;
2049       iAfterSame  = iAB - iAfterSame;
2050     }
2051   }
2052
2053   // make new elements
2054   int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
2055   for (iStep = 0; iStep < nbSteps; iStep++ )
2056   {
2057     // get next nodes
2058     for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2059       nextNod[ iNode ] = *itNN[ iNode ];
2060       itNN[ iNode ]++;
2061     }
2062     SMDS_MeshElement* aNewElem = 0;
2063     switch ( nbNodes )
2064     {
2065     case 0:
2066       return;
2067     case 1: { // NODE
2068       if ( nbSame == 0 )
2069         aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2070       break;
2071     }
2072     case 2: { // EDGE
2073
2074       if ( nbSame == 0 )
2075         aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2076                                   nextNod[ 1 ], nextNod[ 0 ] );
2077       else
2078         aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2079                                   nextNod[ iNotSameNode ] );
2080       break;
2081     }
2082     case 3: { // TRIANGLE
2083
2084       if ( nbSame == 0 )       // --- pentahedron
2085         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2086                                      nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2087
2088       else if ( nbSame == 1 )  // --- pyramid
2089         aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2090                                      nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2091                                      nextNod[ iSameNode ]);
2092
2093       else // 2 same nodes:      --- tetrahedron
2094         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2095                                      nextNod[ iNotSameNode ]);
2096       break;
2097     }
2098     case 4: { // QUADRANGLE
2099
2100       if ( nbSame == 0 )       // --- hexahedron
2101         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2102                                      nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2103
2104       else if ( nbSame == 1 )  // --- pyramid + pentahedron
2105       {
2106         aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2107                                      nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2108                                      nextNod[ iSameNode ]);
2109         newElems.push_back( aNewElem );
2110         aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2111                                      prevNod[ iBeforeSame ],  nextNod[ iAfterSame ],
2112                                      nextNod[ iOpposSame ],  nextNod[ iBeforeSame ] );
2113       }
2114       else if ( nbSame == 2 )  // pentahedron
2115       {
2116         if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2117           // iBeforeSame is same too
2118           aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2119                                        nextNod[ iOpposSame ], prevNod[ iSameNode ],
2120                                        prevNod[ iAfterSame ],  nextNod[ iAfterSame ]);
2121         else
2122           // iAfterSame is same too
2123           aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2124                                        nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2125                                        prevNod[ iOpposSame ],  nextNod[ iOpposSame ]);
2126       }
2127       break;
2128     }
2129     default: {
2130       // realized for extrusion only
2131       vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2132       vector<int> quantities (nbNodes + 2);
2133
2134       quantities[0] = nbNodes; // bottom of prism
2135       for (int inode = 0; inode < nbNodes; inode++) {
2136         polyedre_nodes[inode] = prevNod[inode];
2137       }
2138
2139       quantities[1] = nbNodes; // top of prism
2140       for (int inode = 0; inode < nbNodes; inode++) {
2141         polyedre_nodes[nbNodes + inode] = nextNod[inode];
2142       }
2143
2144       for (int iface = 0; iface < nbNodes; iface++) {
2145         quantities[iface + 2] = 4;
2146         int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2147         polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2148         polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2149         polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2150         polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2151       }
2152       aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2153     }
2154     }
2155     if ( aNewElem )
2156       newElems.push_back( aNewElem );
2157
2158     // set new prev nodes
2159     for ( iNode = 0; iNode < nbNodes; iNode++ )
2160       prevNod[ iNode ] = nextNod[ iNode ];
2161
2162   } // for steps
2163 }
2164
2165 //=======================================================================
2166 //function : makeWalls
2167 //purpose  : create 1D and 2D elements around swept elements
2168 //=======================================================================
2169
2170 static void makeWalls (SMESHDS_Mesh*                 aMesh,
2171                        TNodeOfNodeListMap &          mapNewNodes,
2172                        TElemOfElemListMap &          newElemsMap,
2173                        TElemOfVecOfNnlmiMap &        elemNewNodesMap,
2174                        set<const SMDS_MeshElement*>& elemSet)
2175 {
2176   ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2177
2178   // Find nodes belonging to only one initial element - sweep them to get edges.
2179
2180   TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2181   for ( ; nList != mapNewNodes.end(); nList++ )
2182   {
2183     const SMDS_MeshNode* node =
2184       static_cast<const SMDS_MeshNode*>( nList->first );
2185     SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2186     int nbInitElems = 0;
2187     while ( eIt->more() && nbInitElems < 2 )
2188       if ( elemSet.find( eIt->next() ) != elemSet.end() )
2189         nbInitElems++;
2190     if ( nbInitElems < 2 ) {
2191       vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2192       list<const SMDS_MeshElement*> newEdges;
2193       sweepElement( aMesh, node, newNodesItVec, newEdges );
2194     }
2195   }
2196
2197   // Make a ceiling for each element ie an equal element of last new nodes.
2198   // Find free links of faces - make edges and sweep them into faces.
2199
2200   TElemOfElemListMap::iterator   itElem      = newElemsMap.begin();
2201   TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2202   for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2203   {
2204     const SMDS_MeshElement* elem = itElem->first;
2205     vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2206
2207     if ( elem->GetType() == SMDSAbs_Edge )
2208     {
2209       // create a ceiling edge
2210       aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2211                      vecNewNodes[ 1 ]->second.back() );
2212     }
2213     if ( elem->GetType() != SMDSAbs_Face )
2214       continue;
2215
2216     bool hasFreeLinks = false;
2217
2218     set<const SMDS_MeshElement*> avoidSet;
2219     avoidSet.insert( elem );
2220
2221     // loop on a face nodes
2222     set<const SMDS_MeshNode*> aFaceLastNodes;
2223     int iNode, nbNodes = vecNewNodes.size();
2224     for ( iNode = 0; iNode < nbNodes; iNode++ )
2225     {
2226       aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2227       // look for free links of a face
2228       int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2229       const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2230       const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2231       // check if a link is free
2232       if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2233       {
2234         hasFreeLinks = true;
2235         // make an edge and a ceiling for a new edge
2236         if ( !aMesh->FindEdge( n1, n2 ))
2237           aMesh->AddEdge( n1, n2 );
2238         n1 = vecNewNodes[ iNode ]->second.back();
2239         n2 = vecNewNodes[ iNext ]->second.back();
2240         if ( !aMesh->FindEdge( n1, n2 ))
2241           aMesh->AddEdge( n1, n2 );
2242       }
2243     }
2244     // sweep free links into faces
2245
2246     if ( hasFreeLinks )
2247     {
2248       list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2249       int iStep, nbSteps = vecNewNodes[0]->second.size();
2250       int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2251
2252       set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2253       for ( iNode = 0; iNode < nbNodes; iNode++ )
2254         initNodeSet.insert( vecNewNodes[ iNode ]->first );
2255
2256       for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2257       {
2258         list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2259         iVol = 0;
2260         while ( iVol++ < volNb ) v++;
2261         // find indices of free faces of a volume
2262         list< int > fInd;
2263         SMDS_VolumeTool vTool( *v );
2264         int iF, nbF = vTool.NbFaces();
2265         for ( iF = 0; iF < nbF; iF ++ )
2266           if (vTool.IsFreeFace( iF ) &&
2267               vTool.GetFaceNodes( iF, faceNodeSet ) &&
2268               initNodeSet != faceNodeSet) // except an initial face
2269             fInd.push_back( iF );
2270         if ( fInd.empty() )
2271           continue;
2272
2273         // create faces for all steps
2274         for ( iStep = 0; iStep < nbSteps; iStep++ )
2275         {
2276           vTool.Set( *v );
2277           vTool.SetExternalNormal();
2278           list< int >::iterator ind = fInd.begin();
2279           for ( ; ind != fInd.end(); ind++ )
2280           {
2281             const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2282             switch ( vTool.NbFaceNodes( *ind ) ) {
2283             case 3:
2284               aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2285             case 4:
2286               aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2287             default:
2288               {
2289                 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2290                 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2291                 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2292                   polygon_nodes[inode] = nodes[inode];
2293                 }
2294                 aMesh->AddPolygonalFace(polygon_nodes);
2295                 break;
2296               }
2297             }
2298           }
2299           // go to the next volume
2300           iVol = 0;
2301           while ( iVol++ < nbVolumesByStep ) v++;
2302         }
2303       }
2304     } // sweep free links into faces
2305
2306     // make a ceiling face with a normal external to a volume
2307
2308     SMDS_VolumeTool lastVol( itElem->second.back() );
2309     int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2310     if ( iF >= 0 )
2311     {
2312       lastVol.SetExternalNormal();
2313       const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2314       switch ( lastVol.NbFaceNodes( iF ) ) {
2315       case 3:
2316         if (!hasFreeLinks ||
2317             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2318           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2319         break;
2320       case 4:
2321         if (!hasFreeLinks ||
2322             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2323           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2324         break;
2325       default:
2326         {
2327           int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2328           vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2329           for (int inode = 0; inode < nbPolygonNodes; inode++) {
2330             polygon_nodes[inode] = nodes[inode];
2331           }
2332           if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2333             aMesh->AddPolygonalFace(polygon_nodes);
2334         }
2335         break;
2336       }
2337     }
2338
2339   } // loop on swept elements
2340 }
2341
2342 //=======================================================================
2343 //function : RotationSweep
2344 //purpose  :
2345 //=======================================================================
2346
2347 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2348                                      const gp_Ax1&                  theAxis,
2349                                      const double                   theAngle,
2350                                      const int                      theNbSteps,
2351                                      const double                   theTol)
2352 {
2353   MESSAGE( "RotationSweep()");
2354   gp_Trsf aTrsf;
2355   aTrsf.SetRotation( theAxis, theAngle );
2356
2357   gp_Lin aLine( theAxis );
2358   double aSqTol = theTol * theTol;
2359
2360   SMESHDS_Mesh* aMesh = GetMeshDS();
2361
2362   TNodeOfNodeListMap mapNewNodes;
2363   TElemOfVecOfNnlmiMap mapElemNewNodes;
2364   TElemOfElemListMap newElemsMap;
2365
2366   // loop on theElems
2367   set< const SMDS_MeshElement* >::iterator itElem;
2368   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2369   {
2370     const SMDS_MeshElement* elem = (*itElem);
2371     if ( !elem )
2372       continue;
2373     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2374     newNodesItVec.reserve( elem->NbNodes() );
2375
2376     // loop on elem nodes
2377     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2378     while ( itN->more() ) {
2379
2380       // check if a node has been already sweeped
2381       const SMDS_MeshNode* node =
2382         static_cast<const SMDS_MeshNode*>( itN->next() );
2383       TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2384       if ( nIt == mapNewNodes.end() )
2385       {
2386         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2387         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2388
2389         // make new nodes
2390         gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2391         double coord[3];
2392         aXYZ.Coord( coord[0], coord[1], coord[2] );
2393         bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2394         const SMDS_MeshNode * newNode = node;
2395         for ( int i = 0; i < theNbSteps; i++ ) {
2396           if ( !isOnAxis ) {
2397             aTrsf.Transforms( coord[0], coord[1], coord[2] );
2398             newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2399           }
2400           listNewNodes.push_back( newNode );
2401         }
2402       }
2403       newNodesItVec.push_back( nIt );
2404     }
2405     // make new elements
2406     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2407   }
2408
2409   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2410
2411 }
2412 //=======================================================================
2413 //function : ExtrusionSweep
2414 //purpose  :
2415 //=======================================================================
2416
2417 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
2418                                       const gp_Vec&                  theStep,
2419                                       const int                      theNbSteps)
2420 {
2421   gp_Trsf aTrsf;
2422   aTrsf.SetTranslation( theStep );
2423
2424   SMESHDS_Mesh* aMesh = GetMeshDS();
2425
2426   TNodeOfNodeListMap mapNewNodes;
2427   TElemOfVecOfNnlmiMap mapElemNewNodes;
2428   TElemOfElemListMap newElemsMap;
2429
2430   // loop on theElems
2431   set< const SMDS_MeshElement* >::iterator itElem;
2432   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2433   {
2434     // check element type
2435     const SMDS_MeshElement* elem = (*itElem);
2436     if ( !elem )
2437       continue;
2438
2439     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2440     newNodesItVec.reserve( elem->NbNodes() );
2441
2442     // loop on elem nodes
2443     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2444     while ( itN->more() ) {
2445
2446       // check if a node has been already sweeped
2447       const SMDS_MeshNode* node =
2448         static_cast<const SMDS_MeshNode*>( itN->next() );
2449       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2450       if ( nIt == mapNewNodes.end() )
2451       {
2452         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2453         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2454
2455         // make new nodes
2456         double coord[] = { node->X(), node->Y(), node->Z() };
2457         for ( int i = 0; i < theNbSteps; i++ ) {
2458           aTrsf.Transforms( coord[0], coord[1], coord[2] );
2459           const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2460           listNewNodes.push_back( newNode );
2461         }
2462       }
2463       newNodesItVec.push_back( nIt );
2464     }
2465     // make new elements
2466     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2467   }
2468   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2469 }
2470
2471 //=======================================================================
2472 //class    : SMESH_MeshEditor_PathPoint
2473 //purpose  : auxiliary class
2474 //=======================================================================
2475 class SMESH_MeshEditor_PathPoint {
2476 public:
2477   SMESH_MeshEditor_PathPoint() {
2478     myPnt.SetCoord(99., 99., 99.);
2479     myTgt.SetCoord(1.,0.,0.);
2480     myAngle=0.;
2481     myPrm=0.;
2482   }
2483   void SetPnt(const gp_Pnt& aP3D){
2484     myPnt=aP3D;
2485   }
2486   void SetTangent(const gp_Dir& aTgt){
2487     myTgt=aTgt;
2488   }
2489   void SetAngle(const double& aBeta){
2490     myAngle=aBeta;
2491   }
2492   void SetParameter(const double& aPrm){
2493     myPrm=aPrm;
2494   }
2495   const gp_Pnt& Pnt()const{
2496     return myPnt;
2497   }
2498   const gp_Dir& Tangent()const{
2499     return myTgt;
2500   }
2501   double Angle()const{
2502     return myAngle;
2503   }
2504   double Parameter()const{
2505     return myPrm;
2506   }
2507
2508 protected:
2509   gp_Pnt myPnt;
2510   gp_Dir myTgt;
2511   double myAngle;
2512   double myPrm;
2513 };
2514
2515 //=======================================================================
2516 //function : ExtrusionAlongTrack
2517 //purpose  :
2518 //=======================================================================
2519 SMESH_MeshEditor::Extrusion_Error
2520   SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2521                                          SMESH_subMesh* theTrack,
2522                                          const SMDS_MeshNode* theN1,
2523                                          const bool theHasAngles,
2524                                          std::list<double>& theAngles,
2525                                          const bool theHasRefPoint,
2526                                          const gp_Pnt& theRefPoint)
2527 {
2528   MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2529   int j, aNbTP, aNbE, aNb;
2530   double aT1, aT2, aT, aAngle, aX, aY, aZ;
2531   std::list<double> aPrms;
2532   std::list<double>::iterator aItD;
2533   std::set< const SMDS_MeshElement* >::iterator itElem;
2534
2535   Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2536   gp_Pnt aP3D, aV0;
2537   gp_Vec aVec;
2538   gp_XYZ aGC;
2539   Handle(Geom_Curve) aC3D;
2540   TopoDS_Edge aTrackEdge;
2541   TopoDS_Vertex aV1, aV2;
2542
2543   SMDS_ElemIteratorPtr aItE;
2544   SMDS_NodeIteratorPtr aItN;
2545   SMDSAbs_ElementType aTypeE;
2546
2547   TNodeOfNodeListMap mapNewNodes;
2548   TElemOfVecOfNnlmiMap mapElemNewNodes;
2549   TElemOfElemListMap newElemsMap;
2550
2551   aTolVec=1.e-7;
2552   aTolVec2=aTolVec*aTolVec;
2553
2554   // 1. Check data
2555   aNbE = theElements.size();
2556   // nothing to do
2557   if ( !aNbE )
2558     return EXTR_NO_ELEMENTS;
2559
2560   // 1.1 Track Pattern
2561   ASSERT( theTrack );
2562
2563   SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2564
2565   aItE = pSubMeshDS->GetElements();
2566   while ( aItE->more() ) {
2567     const SMDS_MeshElement* pE = aItE->next();
2568     aTypeE = pE->GetType();
2569     // Pattern must contain links only
2570     if ( aTypeE != SMDSAbs_Edge )
2571       return EXTR_PATH_NOT_EDGE;
2572   }
2573
2574   const TopoDS_Shape& aS = theTrack->GetSubShape();
2575   // Sub shape for the Pattern must be an Edge
2576   if ( aS.ShapeType() != TopAbs_EDGE )
2577     return EXTR_BAD_PATH_SHAPE;
2578
2579   aTrackEdge = TopoDS::Edge( aS );
2580   // the Edge must not be degenerated
2581   if ( BRep_Tool::Degenerated( aTrackEdge ) )
2582     return EXTR_BAD_PATH_SHAPE;
2583
2584   TopExp::Vertices( aTrackEdge, aV1, aV2 );
2585   aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2586   aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2587
2588   aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2589   const SMDS_MeshNode* aN1 = aItN->next();
2590
2591   aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2592   const SMDS_MeshNode* aN2 = aItN->next();
2593
2594   // starting node must be aN1 or aN2
2595   if ( !( aN1 == theN1 || aN2 == theN1 ) )
2596     return EXTR_BAD_STARTING_NODE;
2597
2598   aNbTP = pSubMeshDS->NbNodes() + 2;
2599
2600   // 1.2. Angles
2601   vector<double> aAngles( aNbTP );
2602
2603   for ( j=0; j < aNbTP; ++j ) {
2604     aAngles[j] = 0.;
2605   }
2606
2607   if ( theHasAngles ) {
2608     aItD = theAngles.begin();
2609     for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2610       aAngle = *aItD;
2611       aAngles[j] = aAngle;
2612     }
2613   }
2614
2615   // 2. Collect parameters on the track edge
2616   aPrms.push_back( aT1 );
2617   aPrms.push_back( aT2 );
2618
2619   aItN = pSubMeshDS->GetNodes();
2620   while ( aItN->more() ) {
2621     const SMDS_MeshNode* pNode = aItN->next();
2622     const SMDS_EdgePosition* pEPos =
2623       static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2624     aT = pEPos->GetUParameter();
2625     aPrms.push_back( aT );
2626   }
2627
2628   // sort parameters
2629   aPrms.sort();
2630   if ( aN1 == theN1 ) {
2631     if ( aT1 > aT2 ) {
2632       aPrms.reverse();
2633     }
2634   }
2635   else {
2636     if ( aT2 > aT1 ) {
2637       aPrms.reverse();
2638     }
2639   }
2640
2641   // 3. Path Points
2642   SMESH_MeshEditor_PathPoint aPP;
2643   vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2644   //
2645   aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2646   //
2647   aItD = aPrms.begin();
2648   for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2649     aT = *aItD;
2650     aC3D->D1( aT, aP3D, aVec );
2651     aL2 = aVec.SquareMagnitude();
2652     if ( aL2 < aTolVec2 )
2653       return EXTR_CANT_GET_TANGENT;
2654
2655     gp_Dir aTgt( aVec );
2656     aAngle = aAngles[j];
2657
2658     aPP.SetPnt( aP3D );
2659     aPP.SetTangent( aTgt );
2660     aPP.SetAngle( aAngle );
2661     aPP.SetParameter( aT );
2662     aPPs[j]=aPP;
2663   }
2664
2665   // 3. Center of rotation aV0
2666   aV0 = theRefPoint;
2667   if ( !theHasRefPoint ) {
2668     aNb = 0;
2669     aGC.SetCoord( 0.,0.,0. );
2670
2671     itElem = theElements.begin();
2672     for ( ; itElem != theElements.end(); itElem++ ) {
2673       const SMDS_MeshElement* elem = (*itElem);
2674
2675       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2676       while ( itN->more() ) {
2677         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2678         aX = node->X();
2679         aY = node->Y();
2680         aZ = node->Z();
2681
2682         if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2683           list<const SMDS_MeshNode*> aLNx;
2684           mapNewNodes[node] = aLNx;
2685           //
2686           gp_XYZ aXYZ( aX, aY, aZ );
2687           aGC += aXYZ;
2688           ++aNb;
2689         }
2690       }
2691     }
2692     aGC /= aNb;
2693     aV0.SetXYZ( aGC );
2694   } // if (!theHasRefPoint) {
2695   mapNewNodes.clear();
2696
2697   // 4. Processing the elements
2698   SMESHDS_Mesh* aMesh = GetMeshDS();
2699
2700   for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2701     // check element type
2702     const SMDS_MeshElement* elem = (*itElem);
2703     aTypeE = elem->GetType();
2704     if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2705       continue;
2706
2707     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2708     newNodesItVec.reserve( elem->NbNodes() );
2709
2710     // loop on elem nodes
2711     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2712     while ( itN->more() ) {
2713
2714       // check if a node has been already processed
2715       const SMDS_MeshNode* node =
2716         static_cast<const SMDS_MeshNode*>( itN->next() );
2717       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2718       if ( nIt == mapNewNodes.end() ) {
2719         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2720         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2721
2722         // make new nodes
2723         aX = node->X();  aY = node->Y(); aZ = node->Z();
2724
2725         Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2726         gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2727         gp_Ax1 anAx1, anAxT1T0;
2728         gp_Dir aDT1x, aDT0x, aDT1T0;
2729
2730         aTolAng=1.e-4;
2731
2732         aV0x = aV0;
2733         aPN0.SetCoord(aX, aY, aZ);
2734
2735         const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2736         aP0x = aPP0.Pnt();
2737         aDT0x= aPP0.Tangent();
2738
2739         for ( j = 1; j < aNbTP; ++j ) {
2740           const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2741           aP1x = aPP1.Pnt();
2742           aDT1x = aPP1.Tangent();
2743           aAngle1x = aPP1.Angle();
2744
2745           gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2746           // Translation
2747           gp_Vec aV01x( aP0x, aP1x );
2748           aTrsf.SetTranslation( aV01x );
2749
2750           // traslated point
2751           aV1x = aV0x.Transformed( aTrsf );
2752           aPN1 = aPN0.Transformed( aTrsf );
2753
2754           // rotation 1 [ T1,T0 ]
2755           aAngleT1T0=-aDT1x.Angle( aDT0x );
2756           if (fabs(aAngleT1T0) > aTolAng) {
2757             aDT1T0=aDT1x^aDT0x;
2758             anAxT1T0.SetLocation( aV1x );
2759             anAxT1T0.SetDirection( aDT1T0 );
2760             aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2761
2762             aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2763           }
2764
2765           // rotation 2
2766           if ( theHasAngles ) {
2767             anAx1.SetLocation( aV1x );
2768             anAx1.SetDirection( aDT1x );
2769             aTrsfRot.SetRotation( anAx1, aAngle1x );
2770
2771             aPN1 = aPN1.Transformed( aTrsfRot );
2772           }
2773
2774           // make new node
2775           aX = aPN1.X();
2776           aY = aPN1.Y();
2777           aZ = aPN1.Z();
2778           const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2779           listNewNodes.push_back( newNode );
2780
2781           aPN0 = aPN1;
2782           aP0x = aP1x;
2783           aV0x = aV1x;
2784           aDT0x = aDT1x;
2785         }
2786       }
2787       newNodesItVec.push_back( nIt );
2788     }
2789     // make new elements
2790     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2791   }
2792
2793   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2794
2795   return EXTR_OK;
2796 }
2797
2798 //=======================================================================
2799 //function : Transform
2800 //purpose  :
2801 //=======================================================================
2802
2803 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2804                                   const gp_Trsf&                 theTrsf,
2805                                   const bool                     theCopy)
2806 {
2807   bool needReverse;
2808   switch ( theTrsf.Form() ) {
2809   case gp_PntMirror:
2810   case gp_Ax2Mirror:
2811     needReverse = true;
2812     break;
2813   default:
2814     needReverse = false;
2815   }
2816
2817   SMESHDS_Mesh* aMesh = GetMeshDS();
2818
2819   // map old node to new one
2820   TNodeNodeMap nodeMap;
2821
2822   // elements sharing moved nodes; those of them which have all
2823   // nodes mirrored but are not in theElems are to be reversed
2824   set<const SMDS_MeshElement*> inverseElemSet;
2825
2826   // loop on theElems
2827   set< const SMDS_MeshElement* >::iterator itElem;
2828   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2829   {
2830     const SMDS_MeshElement* elem = (*itElem);
2831     if ( !elem )
2832       continue;
2833
2834     // loop on elem nodes
2835     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2836     while ( itN->more() ) {
2837
2838       // check if a node has been already transformed
2839       const SMDS_MeshNode* node =
2840         static_cast<const SMDS_MeshNode*>( itN->next() );
2841       if (nodeMap.find( node ) != nodeMap.end() )
2842         continue;
2843
2844       double coord[3];
2845       coord[0] = node->X();
2846       coord[1] = node->Y();
2847       coord[2] = node->Z();
2848       theTrsf.Transforms( coord[0], coord[1], coord[2] );
2849       const SMDS_MeshNode * newNode = node;
2850       if ( theCopy )
2851         newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2852       else {
2853         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2854         // node position on shape becomes invalid
2855         const_cast< SMDS_MeshNode* > ( node )->SetPosition
2856           ( SMDS_SpacePosition::originSpacePosition() );
2857       }
2858       nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2859
2860       // keep inverse elements
2861       if ( !theCopy && needReverse ) {
2862         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2863         while ( invElemIt->more() )
2864           inverseElemSet.insert( invElemIt->next() );
2865       }
2866     }
2867   }
2868
2869   // either new elements are to be created
2870   // or a mirrored element are to be reversed
2871   if ( !theCopy && !needReverse)
2872     return;
2873
2874   if ( !inverseElemSet.empty()) {
2875     set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2876     for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2877       theElems.insert( *invElemIt );
2878   }
2879
2880   // replicate or reverse elements
2881
2882   enum {
2883     REV_TETRA   = 0,  //  = nbNodes - 4
2884     REV_PYRAMID = 1,  //  = nbNodes - 4
2885     REV_PENTA   = 2,  //  = nbNodes - 4
2886     REV_FACE    = 3,
2887     REV_HEXA    = 4,  //  = nbNodes - 4
2888     FORWARD     = 5
2889     };
2890   int index[][8] = {
2891     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA
2892     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
2893     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA
2894     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE
2895     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA
2896     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD
2897   };
2898
2899   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2900   {
2901     const SMDS_MeshElement* elem = (*itElem);
2902     if ( !elem || elem->GetType() == SMDSAbs_Node )
2903       continue;
2904
2905     int nbNodes = elem->NbNodes();
2906     int elemType = elem->GetType();
2907
2908     if (elem->IsPoly()) {
2909       // Polygon or Polyhedral Volume
2910       switch ( elemType ) {
2911       case SMDSAbs_Face:
2912         {
2913           vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2914           int iNode = 0;
2915           SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2916           while (itN->more()) {
2917             const SMDS_MeshNode* node =
2918               static_cast<const SMDS_MeshNode*>(itN->next());
2919             TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2920             if (nodeMapIt == nodeMap.end())
2921               break; // not all nodes transformed
2922             if (needReverse) {
2923               // reverse mirrored faces and volumes
2924               poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2925             } else {
2926               poly_nodes[iNode] = (*nodeMapIt).second;
2927             }
2928             iNode++;
2929           }
2930           if ( iNode != nbNodes )
2931             continue; // not all nodes transformed
2932
2933           if ( theCopy ) {
2934             aMesh->AddPolygonalFace(poly_nodes);
2935           } else {
2936             aMesh->ChangePolygonNodes(elem, poly_nodes);
2937           }
2938         }
2939         break;
2940       case SMDSAbs_Volume:
2941         {
2942           // ATTENTION: Reversing is not yet done!!!
2943           const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2944             (const SMDS_PolyhedralVolumeOfNodes*) elem;
2945           if (!aPolyedre) {
2946             MESSAGE("Warning: bad volumic element");
2947             continue;
2948           }
2949
2950           vector<const SMDS_MeshNode*> poly_nodes;
2951           vector<int> quantities;
2952
2953           bool allTransformed = true;
2954           int nbFaces = aPolyedre->NbFaces();
2955           for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2956             int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2957             for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2958               const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
2959               TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2960               if (nodeMapIt == nodeMap.end()) {
2961                 allTransformed = false; // not all nodes transformed
2962               } else {
2963                 poly_nodes.push_back((*nodeMapIt).second);
2964               }
2965             }
2966             quantities.push_back(nbFaceNodes);
2967           }
2968           if ( !allTransformed )
2969             continue; // not all nodes transformed
2970
2971           if ( theCopy ) {
2972             aMesh->AddPolyhedralVolume(poly_nodes, quantities);
2973           } else {
2974             aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
2975           }
2976         }
2977         break;
2978       default:;
2979       }
2980       continue;
2981     }
2982
2983     // Regular elements
2984     int* i = index[ FORWARD ];
2985     if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2986       if ( elemType == SMDSAbs_Face )
2987         i = index[ REV_FACE ];
2988       else
2989         i = index[ nbNodes - 4 ];
2990
2991     // find transformed nodes
2992     const SMDS_MeshNode* nodes[8];
2993     int iNode = 0;
2994     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2995     while ( itN->more() )
2996     {
2997       const SMDS_MeshNode* node =
2998         static_cast<const SMDS_MeshNode*>( itN->next() );
2999       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
3000       if ( nodeMapIt == nodeMap.end() )
3001         break; // not all nodes transformed
3002       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
3003     }
3004     if ( iNode != nbNodes )
3005       continue; // not all nodes transformed
3006
3007     if ( theCopy )
3008     {
3009       // add a new element
3010       switch ( elemType ) {
3011       case SMDSAbs_Edge:
3012         aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
3013         break;
3014       case SMDSAbs_Face:
3015         if ( nbNodes == 3 )
3016           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
3017         else
3018           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
3019         break;
3020       case SMDSAbs_Volume:
3021         if ( nbNodes == 4 )
3022           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
3023         else if ( nbNodes == 8 )
3024           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3025                             nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
3026         else if ( nbNodes == 6 )
3027           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3028                             nodes[ 4 ], nodes[ 5 ]);
3029         else if ( nbNodes == 5 )
3030           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3031                             nodes[ 4 ]);
3032         break;
3033       default:;
3034       }
3035     }
3036     else
3037     {
3038       // reverse element as it was reversed by transformation
3039       if ( nbNodes > 2 )
3040         aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3041     }
3042   }
3043 }
3044
3045 //=======================================================================
3046 //function : FindCoincidentNodes
3047 //purpose  : Return list of group of nodes close to each other within theTolerance
3048 //           Search among theNodes or in the whole mesh if theNodes is empty.
3049 //=======================================================================
3050
3051 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3052                                             const double                theTolerance,
3053                                             TListOfListOfNodes &        theGroupsOfNodes)
3054 {
3055   double tol2 = theTolerance * theTolerance;
3056
3057   list<const SMDS_MeshNode*> nodes;
3058   if ( theNodes.empty() )
3059   { // get all nodes in the mesh
3060     SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3061     while ( nIt->more() )
3062       nodes.push_back( nIt->next() );
3063   }
3064   else
3065   {
3066     nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3067   }
3068
3069   list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3070   for ( ; it1 != nodes.end(); it1++ )
3071   {
3072     const SMDS_MeshNode* n1 = *it1;
3073     gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3074
3075     list<const SMDS_MeshNode*> * groupPtr = 0;
3076     it2 = it1;
3077     for ( it2++; it2 != nodes.end(); it2++ )
3078     {
3079       const SMDS_MeshNode* n2 = *it2;
3080       gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3081       if ( p1.SquareDistance( p2 ) <= tol2 )
3082       {
3083         if ( !groupPtr ) {
3084           theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3085           groupPtr = & theGroupsOfNodes.back();
3086           groupPtr->push_back( n1 );
3087         }
3088         groupPtr->push_back( n2 );
3089         it2 = nodes.erase( it2 );
3090         it2--;
3091       }
3092     }
3093   }
3094 }
3095
3096 //=======================================================================
3097 //function : SimplifyFace
3098 //purpose  :
3099 //=======================================================================
3100 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3101                                     vector<const SMDS_MeshNode *>&      poly_nodes,
3102                                     vector<int>&                        quantities) const
3103 {
3104   int nbNodes = faceNodes.size();
3105
3106   if (nbNodes < 3)
3107     return 0;
3108
3109   set<const SMDS_MeshNode*> nodeSet;
3110
3111   // get simple seq of nodes
3112   const SMDS_MeshNode* simpleNodes[ nbNodes ];
3113   int iSimple = 0, nbUnique = 0;
3114
3115   simpleNodes[iSimple++] = faceNodes[0];
3116   nbUnique++;
3117   for (int iCur = 1; iCur < nbNodes; iCur++) {
3118     if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3119       simpleNodes[iSimple++] = faceNodes[iCur];
3120       if (nodeSet.insert( faceNodes[iCur] ).second)
3121         nbUnique++;
3122     }
3123   }
3124   int nbSimple = iSimple;
3125   if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3126     nbSimple--;
3127     iSimple--;
3128   }
3129
3130   if (nbUnique < 3)
3131     return 0;
3132
3133   // separate loops
3134   int nbNew = 0;
3135   bool foundLoop = (nbSimple > nbUnique);
3136   while (foundLoop) {
3137     foundLoop = false;
3138     set<const SMDS_MeshNode*> loopSet;
3139     for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3140       const SMDS_MeshNode* n = simpleNodes[iSimple];
3141       if (!loopSet.insert( n ).second) {
3142         foundLoop = true;
3143
3144         // separate loop
3145         int iC = 0, curLast = iSimple;
3146         for (; iC < curLast; iC++) {
3147           if (simpleNodes[iC] == n) break;
3148         }
3149         int loopLen = curLast - iC;
3150         if (loopLen > 2) {
3151           // create sub-element
3152           nbNew++;
3153           quantities.push_back(loopLen);
3154           for (; iC < curLast; iC++) {
3155             poly_nodes.push_back(simpleNodes[iC]);
3156           }
3157         }
3158         // shift the rest nodes (place from the first loop position)
3159         for (iC = curLast + 1; iC < nbSimple; iC++) {
3160           simpleNodes[iC - loopLen] = simpleNodes[iC];
3161         }
3162         nbSimple -= loopLen;
3163         iSimple -= loopLen;
3164       }
3165     } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3166   } // while (foundLoop)
3167
3168   if (iSimple > 2) {
3169     nbNew++;
3170     quantities.push_back(iSimple);
3171     for (int i = 0; i < iSimple; i++)
3172       poly_nodes.push_back(simpleNodes[i]);
3173   }
3174
3175   return nbNew;
3176 }
3177
3178 //=======================================================================
3179 //function : MergeNodes
3180 //purpose  : In each group, the cdr of nodes are substituted by the first one
3181 //           in all elements.
3182 //=======================================================================
3183
3184 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3185 {
3186   SMESHDS_Mesh* aMesh = GetMeshDS();
3187
3188   TNodeNodeMap nodeNodeMap; // node to replace - new node
3189   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3190   list< int > rmElemIds, rmNodeIds;
3191
3192   // Fill nodeNodeMap and elems
3193
3194   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3195   for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3196   {
3197     list<const SMDS_MeshNode*>& nodes = *grIt;
3198     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3199     const SMDS_MeshNode* nToKeep = *nIt;
3200     for ( ; nIt != nodes.end(); nIt++ )
3201     {
3202       const SMDS_MeshNode* nToRemove = *nIt;
3203       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3204       if ( nToRemove != nToKeep ) {
3205         rmNodeIds.push_back( nToRemove->GetID() );
3206         AddToSameGroups( nToKeep, nToRemove, aMesh );
3207       }
3208
3209       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3210       while ( invElemIt->more() )
3211         elems.insert( invElemIt->next() );
3212     }
3213   }
3214   // Change element nodes or remove an element
3215
3216   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3217   for ( ; eIt != elems.end(); eIt++ )
3218   {
3219     const SMDS_MeshElement* elem = *eIt;
3220     int nbNodes = elem->NbNodes();
3221     int aShapeId = FindShape( elem );
3222
3223     set<const SMDS_MeshNode*> nodeSet;
3224     const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3225     int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3226
3227     // get new seq of nodes
3228     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3229     while ( itN->more() )
3230     {
3231       const SMDS_MeshNode* n =
3232         static_cast<const SMDS_MeshNode*>( itN->next() );
3233
3234       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3235       if ( nnIt != nodeNodeMap.end() ) { // n sticks
3236         n = (*nnIt).second;
3237         iRepl[ nbRepl++ ] = iCur;
3238       }
3239       curNodes[ iCur ] = n;
3240       bool isUnique = nodeSet.insert( n ).second;
3241       if ( isUnique )
3242         uniqueNodes[ iUnique++ ] = n;
3243       iCur++;
3244     }
3245
3246     // Analyse element topology after replacement
3247
3248     bool isOk = true;
3249     int nbUniqueNodes = nodeSet.size();
3250     if ( nbNodes != nbUniqueNodes ) // some nodes stick
3251     {
3252       // Polygons and Polyhedral volumes
3253       if (elem->IsPoly()) {
3254
3255         if (elem->GetType() == SMDSAbs_Face) {
3256           // Polygon
3257           vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3258           int inode = 0;
3259           for (; inode < nbNodes; inode++) {
3260             face_nodes[inode] = curNodes[inode];
3261           }
3262
3263           vector<const SMDS_MeshNode *> polygons_nodes;
3264           vector<int> quantities;
3265           int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3266
3267           if (nbNew > 0) {
3268             inode = 0;
3269             for (int iface = 0; iface < nbNew - 1; iface++) {
3270               int nbNodes = quantities[iface];
3271               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3272               for (int ii = 0; ii < nbNodes; ii++, inode++) {
3273                 poly_nodes[ii] = polygons_nodes[inode];
3274               }
3275               SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3276               if (aShapeId)
3277                 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3278             }
3279             aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3280           } else {
3281             rmElemIds.push_back(elem->GetID());
3282           }
3283
3284         } else if (elem->GetType() == SMDSAbs_Volume) {
3285           // Polyhedral volume
3286           if (nbUniqueNodes < 4) {
3287             rmElemIds.push_back(elem->GetID());
3288           } else {
3289             // each face has to be analized in order to check volume validity
3290             const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3291               static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3292             if (aPolyedre) {
3293               int nbFaces = aPolyedre->NbFaces();
3294
3295               vector<const SMDS_MeshNode *> poly_nodes;
3296               vector<int> quantities;
3297
3298               for (int iface = 1; iface <= nbFaces; iface++) {
3299                 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3300                 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3301
3302                 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3303                   const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3304                   TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3305                   if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3306                     faceNode = (*nnIt).second;
3307                   }
3308                   faceNodes[inode - 1] = faceNode;
3309                 }
3310
3311                 SimplifyFace(faceNodes, poly_nodes, quantities);
3312               }
3313
3314               if (quantities.size() > 3) {
3315                 // to be done: remove coincident faces
3316               }
3317
3318               if (quantities.size() > 3)
3319                 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3320               else
3321                 rmElemIds.push_back(elem->GetID());
3322
3323             } else {
3324               rmElemIds.push_back(elem->GetID());
3325             }
3326           }
3327         } else {
3328         }
3329
3330         continue;
3331       }
3332
3333       // Regular elements
3334       switch ( nbNodes ) {
3335       case 2: ///////////////////////////////////// EDGE
3336         isOk = false; break;
3337       case 3: ///////////////////////////////////// TRIANGLE
3338         isOk = false; break;
3339       case 4:
3340         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3341           isOk = false;
3342         else { //////////////////////////////////// QUADRANGLE
3343           if ( nbUniqueNodes < 3 )
3344             isOk = false;
3345           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3346             isOk = false; // opposite nodes stick
3347         }
3348         break;
3349       case 6: ///////////////////////////////////// PENTAHEDRON
3350         if ( nbUniqueNodes == 4 ) {
3351           // ---------------------------------> tetrahedron
3352           if (nbRepl == 3 &&
3353               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3354             // all top nodes stick: reverse a bottom
3355             uniqueNodes[ 0 ] = curNodes [ 1 ];
3356             uniqueNodes[ 1 ] = curNodes [ 0 ];
3357           }
3358           else if (nbRepl == 3 &&
3359                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3360             // all bottom nodes stick: set a top before
3361             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3362             uniqueNodes[ 0 ] = curNodes [ 3 ];
3363             uniqueNodes[ 1 ] = curNodes [ 4 ];
3364             uniqueNodes[ 2 ] = curNodes [ 5 ];
3365           }
3366           else if (nbRepl == 4 &&
3367                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3368             // a lateral face turns into a line: reverse a bottom
3369             uniqueNodes[ 0 ] = curNodes [ 1 ];
3370             uniqueNodes[ 1 ] = curNodes [ 0 ];
3371           }
3372           else
3373             isOk = false;
3374         }
3375         else if ( nbUniqueNodes == 5 ) {
3376           // PENTAHEDRON --------------------> 2 tetrahedrons
3377           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3378             // a bottom node sticks with a linked top one
3379             // 1.
3380             SMDS_MeshElement* newElem =
3381               aMesh->AddVolume(curNodes[ 3 ],
3382                                curNodes[ 4 ],
3383                                curNodes[ 5 ],
3384                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3385             if ( aShapeId )
3386               aMesh->SetMeshElementOnShape( newElem, aShapeId );
3387             // 2. : reverse a bottom
3388             uniqueNodes[ 0 ] = curNodes [ 1 ];
3389             uniqueNodes[ 1 ] = curNodes [ 0 ];
3390             nbUniqueNodes = 4;
3391           }
3392           else
3393             isOk = false;
3394         }
3395         else
3396           isOk = false;
3397         break;
3398       case 8: { //////////////////////////////////// HEXAHEDRON
3399         isOk = false;
3400         SMDS_VolumeTool hexa (elem);
3401         hexa.SetExternalNormal();
3402         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3403           //////////////////////// ---> tetrahedron
3404           for ( int iFace = 0; iFace < 6; iFace++ ) {
3405             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3406             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3407                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3408                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3409               // one face turns into a point ...
3410               int iOppFace = hexa.GetOppFaceIndex( iFace );
3411               ind = hexa.GetFaceNodesIndices( iOppFace );
3412               int nbStick = 0;
3413               iUnique = 2; // reverse a tetrahedron bottom
3414               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3415                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3416                   nbStick++;
3417                 else if ( iUnique >= 0 )
3418                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3419               }
3420               if ( nbStick == 1 ) {
3421                 // ... and the opposite one - into a triangle.
3422                 // set a top node
3423                 ind = hexa.GetFaceNodesIndices( iFace );
3424                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3425                 isOk = true;
3426               }
3427               break;
3428             }
3429           }
3430         }
3431         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3432           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3433           for ( int iFace = 0; iFace < 6; iFace++ ) {
3434             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3435             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3436                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3437                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3438               // one face turns into a point ...
3439               int iOppFace = hexa.GetOppFaceIndex( iFace );
3440               ind = hexa.GetFaceNodesIndices( iOppFace );
3441               int nbStick = 0;
3442               iUnique = 2;  // reverse a tetrahedron 1 bottom
3443               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3444                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3445                   nbStick++;
3446                 else if ( iUnique >= 0 )
3447                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3448               }
3449               if ( nbStick == 0 ) {
3450                 // ... and the opposite one is a quadrangle
3451                 // set a top node
3452                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3453                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3454                 nbUniqueNodes = 4;
3455                 // tetrahedron 2
3456                 SMDS_MeshElement* newElem =
3457                   aMesh->AddVolume(curNodes[ind[ 0 ]],
3458                                    curNodes[ind[ 3 ]],
3459                                    curNodes[ind[ 2 ]],
3460                                    curNodes[indTop[ 0 ]]);
3461                 if ( aShapeId )
3462                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
3463                 isOk = true;
3464               }
3465               break;
3466             }
3467           }
3468         }
3469         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3470           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3471           // find indices of quad and tri faces
3472           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3473           for ( iFace = 0; iFace < 6; iFace++ ) {
3474             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3475             nodeSet.clear();
3476             for ( iCur = 0; iCur < 4; iCur++ )
3477               nodeSet.insert( curNodes[ind[ iCur ]] );
3478             nbUniqueNodes = nodeSet.size();
3479             if ( nbUniqueNodes == 3 )
3480               iTriFace[ nbTri++ ] = iFace;
3481             else if ( nbUniqueNodes == 4 )
3482               iQuadFace[ nbQuad++ ] = iFace;
3483           }
3484           if (nbQuad == 2 && nbTri == 4 &&
3485               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3486             // 2 opposite quadrangles stuck with a diagonal;
3487             // sample groups of merged indices: (0-4)(2-6)
3488             // --------------------------------------------> 2 tetrahedrons
3489             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3490             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3491             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3492             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3493                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3494               // stuck with 0-2 diagonal
3495               i0  = ind1[ 3 ];
3496               i1d = ind1[ 0 ];
3497               i2  = ind1[ 1 ];
3498               i3d = ind1[ 2 ];
3499               i0t = ind2[ 1 ];
3500               i2t = ind2[ 3 ];
3501             }
3502             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3503                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3504               // stuck with 1-3 diagonal
3505               i0  = ind1[ 0 ];
3506               i1d = ind1[ 1 ];
3507               i2  = ind1[ 2 ];
3508               i3d = ind1[ 3 ];
3509               i0t = ind2[ 0 ];
3510               i2t = ind2[ 1 ];
3511             }
3512             else {
3513               ASSERT(0);
3514             }
3515             // tetrahedron 1
3516             uniqueNodes[ 0 ] = curNodes [ i0 ];
3517             uniqueNodes[ 1 ] = curNodes [ i1d ];
3518             uniqueNodes[ 2 ] = curNodes [ i3d ];
3519             uniqueNodes[ 3 ] = curNodes [ i0t ];
3520             nbUniqueNodes = 4;
3521             // tetrahedron 2
3522             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3523                                                          curNodes[ i2 ],
3524                                                          curNodes[ i3d ],
3525                                                          curNodes[ i2t ]);
3526             if ( aShapeId )
3527               aMesh->SetMeshElementOnShape( newElem, aShapeId );
3528             isOk = true;
3529           }
3530           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3531                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3532             // --------------------------------------------> prism
3533             // find 2 opposite triangles
3534             nbUniqueNodes = 6;
3535             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3536               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3537                 // find indices of kept and replaced nodes
3538                 // and fill unique nodes of 2 opposite triangles
3539                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3540                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3541                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3542                 // fill unique nodes
3543                 iUnique = 0;
3544                 isOk = true;
3545                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3546                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
3547                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3548                   if ( n == nInit ) {
3549                     // iCur of a linked node of the opposite face (make normals co-directed):
3550                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3551                     // check that correspondent corners of triangles are linked
3552                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3553                       isOk = false;
3554                     else {
3555                       uniqueNodes[ iUnique ] = n;
3556                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3557                       iUnique++;
3558                     }
3559                   }
3560                 }
3561                 break;
3562               }
3563             }
3564           }
3565         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3566         break;
3567       } // HEXAHEDRON
3568
3569       default:
3570         isOk = false;
3571       } // switch ( nbNodes )
3572
3573     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3574
3575     if ( isOk ) {
3576       if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3577         // Change nodes of polyedre
3578         const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3579           static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3580         if (aPolyedre) {
3581           int nbFaces = aPolyedre->NbFaces();
3582
3583           vector<const SMDS_MeshNode *> poly_nodes;
3584           vector<int> quantities (nbFaces);
3585
3586           for (int iface = 1; iface <= nbFaces; iface++) {
3587             int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3588             quantities[iface - 1] = nbFaceNodes;
3589
3590             for (inode = 1; inode <= nbFaceNodes; inode++) {
3591               const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3592
3593               TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3594               if (nnIt != nodeNodeMap.end()) { // curNode sticks
3595                 curNode = (*nnIt).second;
3596               }
3597               poly_nodes.push_back(curNode);
3598             }
3599           }
3600           aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3601         }
3602       } else {
3603         // Change regular element or polygon
3604         aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3605       }
3606     } else {
3607       // Remove invalid regular element or invalid polygon
3608       rmElemIds.push_back( elem->GetID() );
3609     }
3610
3611   } // loop on elements
3612
3613   // Remove equal nodes and bad elements
3614
3615   Remove( rmNodeIds, true );
3616   Remove( rmElemIds, false );
3617
3618 }
3619
3620 //=======================================================================
3621 //function : MergeEqualElements
3622 //purpose  : Remove all but one of elements built on the same nodes.
3623 //=======================================================================
3624
3625 void SMESH_MeshEditor::MergeEqualElements()
3626 {
3627   SMESHDS_Mesh* aMesh = GetMeshDS();
3628
3629   SMDS_EdgeIteratorPtr   eIt = aMesh->edgesIterator();
3630   SMDS_FaceIteratorPtr   fIt = aMesh->facesIterator();
3631   SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3632
3633   list< int > rmElemIds; // IDs of elems to remove
3634
3635   for ( int iDim = 1; iDim <= 3; iDim++ ) {
3636
3637     set< set <const SMDS_MeshElement*> > setOfNodeSet;
3638
3639     while ( 1 ) {
3640       // get next element
3641       const SMDS_MeshElement* elem = 0;
3642       if ( iDim == 1 ) {
3643         if ( eIt->more() ) elem = eIt->next();
3644       } else if ( iDim == 2 ) {
3645         if ( fIt->more() ) elem = fIt->next();
3646       } else {
3647         if ( vIt->more() ) elem = vIt->next();
3648       }
3649       if ( !elem ) break;
3650
3651       // get elem nodes
3652       set <const SMDS_MeshElement*> nodeSet;
3653       SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3654       while ( nodeIt->more() )
3655         nodeSet.insert( nodeIt->next() );
3656
3657       // check uniqueness
3658       bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3659       if ( !isUnique )
3660         rmElemIds.push_back( elem->GetID() );
3661     }
3662   }
3663
3664   Remove( rmElemIds, false );
3665 }
3666
3667 //=======================================================================
3668 //function : FindFaceInSet
3669 //purpose  : Return a face having linked nodes n1 and n2 and which is
3670 //           - not in avoidSet,
3671 //           - in elemSet provided that !elemSet.empty()
3672 //=======================================================================
3673
3674 const SMDS_MeshElement*
3675   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*                n1,
3676                                   const SMDS_MeshNode*                n2,
3677                                   const set<const SMDS_MeshElement*>& elemSet,
3678                                   const set<const SMDS_MeshElement*>& avoidSet)
3679
3680 {
3681   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3682   while ( invElemIt->more() ) { // loop on inverse elements of n1
3683     const SMDS_MeshElement* elem = invElemIt->next();
3684     if (elem->GetType() != SMDSAbs_Face ||
3685         avoidSet.find( elem ) != avoidSet.end() )
3686       continue;
3687     if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3688       continue;
3689     // get face nodes and find index of n1
3690     int i1, nbN = elem->NbNodes(), iNode = 0;
3691     const SMDS_MeshNode* faceNodes[ nbN ], *n;
3692     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3693     while ( nIt->more() ) {
3694       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3695       if ( faceNodes[ iNode++ ] == n1 )
3696         i1 = iNode - 1;
3697     }
3698     // find a n2 linked to n1
3699     for ( iNode = 0; iNode < 2; iNode++ ) {
3700       if ( iNode ) // node before n1
3701         n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3702       else         // node after n1
3703         n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3704       if ( n == n2 )
3705         return elem;
3706     }
3707   }
3708   return 0;
3709 }
3710
3711 //=======================================================================
3712 //function : findAdjacentFace
3713 //purpose  :
3714 //=======================================================================
3715
3716 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3717                                                 const SMDS_MeshNode* n2,
3718                                                 const SMDS_MeshElement* elem)
3719 {
3720   set<const SMDS_MeshElement*> elemSet, avoidSet;
3721   if ( elem )
3722     avoidSet.insert ( elem );
3723   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3724 }
3725
3726 //=======================================================================
3727 //function : findFreeBorder
3728 //purpose  :
3729 //=======================================================================
3730
3731 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3732
3733 static bool findFreeBorder (const SMDS_MeshNode*                theFirstNode,
3734                             const SMDS_MeshNode*                theSecondNode,
3735                             const SMDS_MeshNode*                theLastNode,
3736                             list< const SMDS_MeshNode* > &      theNodes,
3737                             list< const SMDS_MeshElement* > &   theFaces)
3738 {
3739   if ( !theFirstNode || !theSecondNode )
3740     return false;
3741   // find border face between theFirstNode and theSecondNode
3742   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3743   if ( !curElem )
3744     return false;
3745
3746   theFaces.push_back( curElem );
3747   theNodes.push_back( theFirstNode );
3748   theNodes.push_back( theSecondNode );
3749
3750   const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3751   set < const SMDS_MeshElement* > foundElems;
3752   bool needTheLast = ( theLastNode != 0 );
3753
3754   while ( nStart != theLastNode )
3755   {
3756     if ( nStart == theFirstNode )
3757       return !needTheLast;
3758
3759     // find all free border faces sharing form nStart
3760
3761     list< const SMDS_MeshElement* > curElemList;
3762     list< const SMDS_MeshNode* > nStartList;
3763     SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3764     while ( invElemIt->more() ) {
3765       const SMDS_MeshElement* e = invElemIt->next();
3766       if ( e == curElem || foundElems.insert( e ).second )
3767       {
3768         // get nodes
3769         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3770         int iNode = 0, nbNodes = e->NbNodes();
3771         while ( nIt->more() )
3772           nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3773         nodes[ iNode ] = nodes[ 0 ];
3774         // check 2 links
3775         for ( iNode = 0; iNode < nbNodes; iNode++ )
3776           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3777                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3778               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3779           {
3780             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3781             curElemList.push_back( e );
3782           }
3783       }
3784     }
3785     // analyse the found
3786
3787     int nbNewBorders = curElemList.size();
3788     if ( nbNewBorders == 0 ) {
3789       // no free border furthermore
3790       return !needTheLast;
3791     }
3792     else if ( nbNewBorders == 1 ) {
3793       // one more element found
3794       nIgnore = nStart;
3795       nStart = nStartList.front();
3796       curElem = curElemList.front();
3797       theFaces.push_back( curElem );
3798       theNodes.push_back( nStart );
3799     }
3800     else {
3801       // several continuations found
3802       list< const SMDS_MeshElement* >::iterator curElemIt;
3803       list< const SMDS_MeshNode* >::iterator nStartIt;
3804       // check if one of them reached the last node
3805       if ( needTheLast ) {
3806         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3807              curElemIt!= curElemList.end();
3808              curElemIt++, nStartIt++ )
3809           if ( *nStartIt == theLastNode ) {
3810             theFaces.push_back( *curElemIt );
3811             theNodes.push_back( *nStartIt );
3812             return true;
3813           }
3814       }
3815       // find the best free border by the continuations
3816       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
3817       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3818       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3819            curElemIt!= curElemList.end();
3820            curElemIt++, nStartIt++ )
3821       {
3822         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3823         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3824         // find one more free border
3825         if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3826           cNL->clear();
3827           cFL->clear();
3828         }
3829         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3830           // choice: clear a worse one
3831           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3832           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3833           contNodes[ iWorse ].clear();
3834           contFaces[ iWorse ].clear();
3835         }
3836       }
3837       if ( contNodes[0].empty() && contNodes[1].empty() )
3838         return false;
3839
3840       // append the best free border
3841       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3842       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3843       theNodes.pop_back(); // remove nIgnore
3844       theNodes.pop_back(); // remove nStart
3845       theFaces.pop_back(); // remove curElem
3846       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3847       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3848       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3849       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3850       return true;
3851
3852     } // several continuations found
3853   } // while ( nStart != theLastNode )
3854
3855   return true;
3856 }
3857
3858 //=======================================================================
3859 //function : CheckFreeBorderNodes
3860 //purpose  : Return true if the tree nodes are on a free border
3861 //=======================================================================
3862
3863 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3864                                             const SMDS_MeshNode* theNode2,
3865                                             const SMDS_MeshNode* theNode3)
3866 {
3867   list< const SMDS_MeshNode* > nodes;
3868   list< const SMDS_MeshElement* > faces;
3869   return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3870 }
3871
3872 //=======================================================================
3873 //function : SewFreeBorder
3874 //purpose  :
3875 //=======================================================================
3876
3877 SMESH_MeshEditor::Sew_Error
3878   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3879                                    const SMDS_MeshNode* theBordSecondNode,
3880                                    const SMDS_MeshNode* theBordLastNode,
3881                                    const SMDS_MeshNode* theSideFirstNode,
3882                                    const SMDS_MeshNode* theSideSecondNode,
3883                                    const SMDS_MeshNode* theSideThirdNode,
3884                                    const bool           theSideIsFreeBorder,
3885                                    const bool           toCreatePolygons,
3886                                    const bool           toCreatePolyedrs)
3887 {
3888   MESSAGE("::SewFreeBorder()");
3889   Sew_Error aResult = SEW_OK;
3890
3891   // ====================================
3892   //    find side nodes and elements
3893   // ====================================
3894
3895   list< const SMDS_MeshNode* > nSide[ 2 ];
3896   list< const SMDS_MeshElement* > eSide[ 2 ];
3897   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3898   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3899
3900   // Free border 1
3901   // --------------
3902   if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3903                       nSide[0], eSide[0])) {
3904     MESSAGE(" Free Border 1 not found " );
3905     aResult = SEW_BORDER1_NOT_FOUND;
3906   }
3907   if (theSideIsFreeBorder)
3908   {
3909     // Free border 2
3910     // --------------
3911     if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3912                         nSide[1], eSide[1])) {
3913       MESSAGE(" Free Border 2 not found " );
3914       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3915     }
3916   }
3917   if ( aResult != SEW_OK )
3918     return aResult;
3919
3920   if (!theSideIsFreeBorder)
3921   {
3922     // Side 2
3923     // --------------
3924
3925     // -------------------------------------------------------------------------
3926     // Algo:
3927     // 1. If nodes to merge are not coincident, move nodes of the free border
3928     //    from the coord sys defined by the direction from the first to last
3929     //    nodes of the border to the correspondent sys of the side 2
3930     // 2. On the side 2, find the links most co-directed with the correspondent
3931     //    links of the free border
3932     // -------------------------------------------------------------------------
3933
3934     // 1. Since sewing may brake if there are volumes to split on the side 2,
3935     //    we wont move nodes but just compute new coordinates for them
3936     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3937     TNodeXYZMap nBordXYZ;
3938     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3939     list< const SMDS_MeshNode* >::iterator nBordIt;
3940
3941     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3942     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3943     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3944     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3945     double tol2 = 1.e-8;
3946     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3947     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3948     {
3949       // Need node movement.
3950
3951       // find X and Z axes to create trsf
3952       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3953       gp_Vec X = Zs ^ Zb;
3954       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3955         // Zb || Zs
3956         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3957
3958       // coord systems
3959       gp_Ax3 toBordAx( Pb1, Zb, X );
3960       gp_Ax3 fromSideAx( Ps1, Zs, X );
3961       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
3962       // set trsf
3963       gp_Trsf toBordSys, fromSide2Sys;
3964       toBordSys.SetTransformation( toBordAx );
3965       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
3966       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
3967
3968       // move
3969       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3970         const SMDS_MeshNode* n = *nBordIt;
3971         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
3972         toBordSys.Transforms( xyz );
3973         fromSide2Sys.Transforms( xyz );
3974         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
3975       }
3976     }
3977     else
3978     {
3979       // just insert nodes XYZ in the nBordXYZ map
3980       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3981         const SMDS_MeshNode* n = *nBordIt;
3982         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
3983       }
3984     }
3985
3986     // 2. On the side 2, find the links most co-directed with the correspondent
3987     //    links of the free border
3988
3989     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
3990     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
3991     sideNodes.push_back( theSideFirstNode );
3992
3993     bool hasVolumes = false;
3994     LinkID_Gen aLinkID_Gen( GetMeshDS() );
3995     set<long> foundSideLinkIDs, checkedLinkIDs;
3996     SMDS_VolumeTool volume;
3997     //const SMDS_MeshNode* faceNodes[ 4 ];
3998
3999     const SMDS_MeshNode*    sideNode;
4000     const SMDS_MeshElement* sideElem;
4001     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
4002     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
4003     nBordIt = bordNodes.begin();
4004     nBordIt++;
4005     // border node position and border link direction to compare with
4006     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
4007     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
4008     // choose next side node by link direction or by closeness to
4009     // the current border node:
4010     bool searchByDir = ( *nBordIt != theBordLastNode );
4011     do {
4012       // find the next node on the Side 2
4013       sideNode = 0;
4014       double maxDot = -DBL_MAX, minDist = DBL_MAX;
4015       long linkID;
4016       checkedLinkIDs.clear();
4017       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
4018
4019       SMDS_ElemIteratorPtr invElemIt
4020         = prevSideNode->GetInverseElementIterator();
4021       while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
4022         const SMDS_MeshElement* elem = invElemIt->next();
4023         // prepare data for a loop on links, of a face or a volume
4024         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
4025         const SMDS_MeshNode* faceNodes[ nbNodes ];
4026         bool isVolume = volume.Set( elem );
4027         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
4028         if ( isVolume ) // --volume
4029           hasVolumes = true;
4030         else if ( nbNodes > 2 ) { // --face
4031           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
4032           SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4033           while ( nIt->more() ) {
4034             nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4035             if ( nodes[ iNode++ ] == prevSideNode )
4036               iPrevNode = iNode - 1;
4037           }
4038           // there are 2 links to check
4039           nbNodes = 2;
4040         }
4041         else // --edge
4042           continue;
4043         // loop on links, to be precise, on the second node of links
4044         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4045           const SMDS_MeshNode* n = nodes[ iNode ];
4046           if ( isVolume ) {
4047             if ( !volume.IsLinked( n, prevSideNode ))
4048               continue;
4049           } else {
4050             if ( iNode ) // a node before prevSideNode
4051               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4052             else         // a node after prevSideNode
4053               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4054           }
4055           // check if this link was already used
4056           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4057           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4058           if (!isJustChecked &&
4059               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4060             // test a link geometrically
4061             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4062             bool linkIsBetter = false;
4063             double dot, dist;
4064             if ( searchByDir ) { // choose most co-directed link
4065               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4066               linkIsBetter = ( dot > maxDot );
4067             }
4068             else { // choose link with the node closest to bordPos
4069               dist = ( nextXYZ - bordPos ).SquareModulus();
4070               linkIsBetter = ( dist < minDist );
4071             }
4072             if ( linkIsBetter ) {
4073               maxDot = dot;
4074               minDist = dist;
4075               linkID = iLink;
4076               sideNode = n;
4077               sideElem = elem;
4078             }
4079           }
4080         }
4081       } // loop on inverse elements of prevSideNode
4082
4083       if ( !sideNode ) {
4084         MESSAGE(" Cant find path by links of the Side 2 ");
4085         return SEW_BAD_SIDE_NODES;
4086       }
4087       sideNodes.push_back( sideNode );
4088       sideElems.push_back( sideElem );
4089       foundSideLinkIDs.insert ( linkID );
4090       prevSideNode = sideNode;
4091
4092       if ( *nBordIt == theBordLastNode )
4093         searchByDir = false;
4094       else {
4095         // find the next border link to compare with
4096         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4097         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4098         while ( *nBordIt != theBordLastNode && !searchByDir ) {
4099           prevBordNode = *nBordIt;
4100           nBordIt++;
4101           bordPos = nBordXYZ[ *nBordIt ];
4102           bordDir = bordPos - nBordXYZ[ prevBordNode ];
4103           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4104         }
4105       }
4106     }
4107     while ( sideNode != theSideSecondNode );
4108
4109     if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4110       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4111       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4112     }
4113   } // end nodes search on the side 2
4114
4115   // ============================
4116   // sew the border to the side 2
4117   // ============================
4118
4119   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
4120   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4121
4122   TListOfListOfNodes nodeGroupsToMerge;
4123   if ( nbNodes[0] == nbNodes[1] ||
4124       ( theSideIsFreeBorder && !theSideThirdNode)) {
4125
4126     // all nodes are to be merged
4127
4128     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4129          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4130          nIt[0]++, nIt[1]++ )
4131     {
4132       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4133       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4134       nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4135     }
4136   }
4137   else {
4138
4139     // insert new nodes into the border and the side to get equal nb of segments
4140
4141     // get normalized parameters of nodes on the borders
4142     double param[ 2 ][ maxNbNodes ];
4143     int iNode, iBord;
4144     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4145       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4146       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4147       const SMDS_MeshNode* nPrev = *nIt;
4148       double bordLength = 0;
4149       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4150         const SMDS_MeshNode* nCur = *nIt;
4151         gp_XYZ segment (nCur->X() - nPrev->X(),
4152                         nCur->Y() - nPrev->Y(),
4153                         nCur->Z() - nPrev->Z());
4154         double segmentLen = segment.Modulus();
4155         bordLength += segmentLen;
4156         param[ iBord ][ iNode ] = bordLength;
4157         nPrev = nCur;
4158       }
4159       // normalize within [0,1]
4160       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4161         param[ iBord ][ iNode ] /= bordLength;
4162       }
4163     }
4164
4165     // loop on border segments
4166     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4167     int i[ 2 ] = { 0, 0 };
4168     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4169     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4170
4171     TElemOfNodeListMap insertMap;
4172     TElemOfNodeListMap::iterator insertMapIt;
4173     // insertMap is
4174     // key:   elem to insert nodes into
4175     // value: 2 nodes to insert between + nodes to be inserted
4176     do {
4177       bool next[ 2 ] = { false, false };
4178
4179       // find min adjacent segment length after sewing
4180       double nextParam = 10., prevParam = 0;
4181       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4182         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4183           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4184         if ( i[ iBord ] > 0 )
4185           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4186       }
4187       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4188       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4189       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4190
4191       // choose to insert or to merge nodes
4192       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4193       if ( Abs( du ) <= minSegLen * 0.2 ) {
4194         // merge
4195         // ------
4196         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4197         const SMDS_MeshNode* n0 = *nIt[0];
4198         const SMDS_MeshNode* n1 = *nIt[1];
4199         nodeGroupsToMerge.back().push_back( n1 );
4200         nodeGroupsToMerge.back().push_back( n0 );
4201         // position of node of the border changes due to merge
4202         param[ 0 ][ i[0] ] += du;
4203         // move n1 for the sake of elem shape evaluation during insertion.
4204         // n1 will be removed by MergeNodes() anyway
4205         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4206         next[0] = next[1] = true;
4207       }
4208       else {
4209         // insert
4210         // ------
4211         int intoBord = ( du < 0 ) ? 0 : 1;
4212         const SMDS_MeshElement* elem = *eIt[ intoBord ];
4213         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
4214         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
4215         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
4216         if ( intoBord == 1 ) {
4217           // move node of the border to be on a link of elem of the side
4218           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4219           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4220           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4221           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4222           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4223         }
4224         insertMapIt = insertMap.find( elem );
4225         bool notFound = ( insertMapIt == insertMap.end() );
4226         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4227         if ( otherLink ) {
4228           // insert into another link of the same element:
4229           // 1. perform insertion into the other link of the elem
4230           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4231           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4232           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4233           InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4234           // 2. perform insertion into the link of adjacent faces
4235           while (true) {
4236             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4237             if ( adjElem )
4238               InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4239             else
4240               break;
4241           }
4242           if (toCreatePolyedrs) {
4243             // perform insertion into the links of adjacent volumes
4244             UpdateVolumes(n12, n22, nodeList);
4245           }
4246           // 3. find an element appeared on n1 and n2 after the insertion
4247           insertMap.erase( elem );
4248           elem = findAdjacentFace( n1, n2, 0 );
4249         }
4250         if ( notFound || otherLink ) {
4251           // add element and nodes of the side into the insertMap
4252           insertMapIt = insertMap.insert
4253             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4254           (*insertMapIt).second.push_back( n1 );
4255           (*insertMapIt).second.push_back( n2 );
4256         }
4257         // add node to be inserted into elem
4258         (*insertMapIt).second.push_back( nIns );
4259         next[ 1 - intoBord ] = true;
4260       }
4261
4262       // go to the next segment
4263       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4264         if ( next[ iBord ] ) {
4265           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4266             eIt[ iBord ]++;
4267           nPrev[ iBord ] = *nIt[ iBord ];
4268           nIt[ iBord ]++; i[ iBord ]++;
4269         }
4270       }
4271     }
4272     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4273
4274     // perform insertion of nodes into elements
4275
4276     for (insertMapIt = insertMap.begin();
4277          insertMapIt != insertMap.end();
4278          insertMapIt++ )
4279     {
4280       const SMDS_MeshElement* elem = (*insertMapIt).first;
4281       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4282       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4283       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4284
4285       InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4286
4287       if ( !theSideIsFreeBorder ) {
4288         // look for and insert nodes into the faces adjacent to elem
4289         while (true) {
4290           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4291           if ( adjElem )
4292             InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4293           else
4294             break;
4295         }
4296       }
4297       if (toCreatePolyedrs) {
4298         // perform insertion into the links of adjacent volumes
4299         UpdateVolumes(n1, n2, nodeList);
4300       }
4301     }
4302
4303   } // end: insert new nodes
4304
4305   MergeNodes ( nodeGroupsToMerge );
4306
4307   return aResult;
4308 }
4309
4310 //=======================================================================
4311 //function : InsertNodesIntoLink
4312 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
4313 //           and theBetweenNode2 and split theElement
4314 //=======================================================================
4315
4316 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
4317                                            const SMDS_MeshNode*        theBetweenNode1,
4318                                            const SMDS_MeshNode*        theBetweenNode2,
4319                                            list<const SMDS_MeshNode*>& theNodesToInsert,
4320                                            const bool                  toCreatePoly)
4321 {
4322   if ( theFace->GetType() != SMDSAbs_Face ) return;
4323
4324   // find indices of 2 link nodes and of the rest nodes
4325   int iNode = 0, il1, il2, i3, i4;
4326   il1 = il2 = i3 = i4 = -1;
4327   const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4328   SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4329   while ( nodeIt->more() ) {
4330     const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4331     if ( n == theBetweenNode1 )
4332       il1 = iNode;
4333     else if ( n == theBetweenNode2 )
4334       il2 = iNode;
4335     else if ( i3 < 0 )
4336       i3 = iNode;
4337     else
4338       i4 = iNode;
4339     nodes[ iNode++ ] = n;
4340   }
4341   if ( il1 < 0 || il2 < 0 || i3 < 0 )
4342     return ;
4343
4344   // arrange link nodes to go one after another regarding the face orientation
4345   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4346   list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4347   if ( reverse ) {
4348     iNode = il1;
4349     il1 = il2;
4350     il2 = iNode;
4351     aNodesToInsert.reverse();
4352   }
4353   // check that not link nodes of a quadrangles are in good order
4354   int nbFaceNodes = theFace->NbNodes();
4355   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4356     iNode = i3;
4357     i3 = i4;
4358     i4 = iNode;
4359   }
4360
4361   if (toCreatePoly || theFace->IsPoly()) {
4362
4363     iNode = 0;
4364     vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4365
4366     // add nodes of face up to first node of link
4367     bool isFLN = false;
4368     nodeIt = theFace->nodesIterator();
4369     while ( nodeIt->more() && !isFLN ) {
4370       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4371       poly_nodes[iNode++] = n;
4372       if (n == nodes[il1]) {
4373         isFLN = true;
4374       }
4375     }
4376
4377     // add nodes to insert
4378     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4379     for (; nIt != aNodesToInsert.end(); nIt++) {
4380       poly_nodes[iNode++] = *nIt;
4381     }
4382
4383     // add nodes of face starting from last node of link
4384     while ( nodeIt->more() ) {
4385       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4386       poly_nodes[iNode++] = n;
4387     }
4388
4389     // edit or replace the face
4390     SMESHDS_Mesh *aMesh = GetMeshDS();
4391
4392     if (theFace->IsPoly()) {
4393       aMesh->ChangePolygonNodes(theFace, poly_nodes);
4394
4395     } else {
4396       int aShapeId = FindShape( theFace );
4397
4398       SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4399       if ( aShapeId && newElem )
4400         aMesh->SetMeshElementOnShape( newElem, aShapeId );
4401
4402       aMesh->RemoveElement(theFace);
4403     }
4404     return;
4405   }
4406
4407   // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4408   int nbLinkNodes = 2 + aNodesToInsert.size();
4409   const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4410   linkNodes[ 0 ] = nodes[ il1 ];
4411   linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4412   list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4413   for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4414     linkNodes[ iNode++ ] = *nIt;
4415   }
4416   // decide how to split a quadrangle: compare possible variants
4417   // and choose which of splits to be a quadrangle
4418   int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4419   if ( nbFaceNodes == 3 )
4420   {
4421     iBestQuad = nbSplits;
4422     i4 = i3;
4423   }
4424   else if ( nbFaceNodes == 4 )
4425   {
4426     SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4427     double aBestRate = DBL_MAX;
4428     for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4429       i1 = 0; i2 = 1;
4430       double aBadRate = 0;
4431       // evaluate elements quality
4432       for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4433         if ( iSplit == iQuad ) {
4434           SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4435                                  linkNodes[ i2++ ],
4436                                  nodes[ i3 ],
4437                                  nodes[ i4 ]);
4438           aBadRate += getBadRate( &quad, aCrit );
4439         }
4440         else {
4441           SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4442                                  linkNodes[ i2++ ],
4443                                  nodes[ iSplit < iQuad ? i4 : i3 ]);
4444           aBadRate += getBadRate( &tria, aCrit );
4445         }
4446       }
4447       // choice
4448       if ( aBadRate < aBestRate ) {
4449         iBestQuad = iQuad;
4450         aBestRate = aBadRate;
4451       }
4452     }
4453   }
4454
4455   // create new elements
4456   SMESHDS_Mesh *aMesh = GetMeshDS();
4457   int aShapeId = FindShape( theFace );
4458
4459   i1 = 0; i2 = 1;
4460   for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4461     SMDS_MeshElement* newElem = 0;
4462     if ( iSplit == iBestQuad )
4463       newElem = aMesh->AddFace (linkNodes[ i1++ ],
4464                                 linkNodes[ i2++ ],
4465                                 nodes[ i3 ],
4466                                 nodes[ i4 ]);
4467     else
4468       newElem = aMesh->AddFace (linkNodes[ i1++ ],
4469                                 linkNodes[ i2++ ],
4470                                 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4471     if ( aShapeId && newElem )
4472       aMesh->SetMeshElementOnShape( newElem, aShapeId );
4473   }
4474
4475   // change nodes of theFace
4476   const SMDS_MeshNode* newNodes[ 4 ];
4477   newNodes[ 0 ] = linkNodes[ i1 ];
4478   newNodes[ 1 ] = linkNodes[ i2 ];
4479   newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4480   newNodes[ 3 ] = nodes[ i4 ];
4481   aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4482 }
4483
4484 //=======================================================================
4485 //function : UpdateVolumes
4486 //purpose  :
4487 //=======================================================================
4488 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode*        theBetweenNode1,
4489                                       const SMDS_MeshNode*        theBetweenNode2,
4490                                       list<const SMDS_MeshNode*>& theNodesToInsert)
4491 {
4492   SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4493   while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4494     const SMDS_MeshElement* elem = invElemIt->next();
4495     if (elem->GetType() != SMDSAbs_Volume)
4496       continue;
4497
4498     // check, if current volume has link theBetweenNode1 - theBetweenNode2
4499     SMDS_VolumeTool aVolume (elem);
4500     if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4501       continue;
4502
4503     // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4504     int iface, nbFaces = aVolume.NbFaces();
4505     vector<const SMDS_MeshNode *> poly_nodes;
4506     vector<int> quantities (nbFaces);
4507
4508     for (iface = 0; iface < nbFaces; iface++) {
4509       int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4510       // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4511       const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4512
4513       for (int inode = 0; inode < nbFaceNodes; inode++) {
4514         poly_nodes.push_back(faceNodes[inode]);
4515
4516         if (nbInserted == 0) {
4517           if (faceNodes[inode] == theBetweenNode1) {
4518             if (faceNodes[inode + 1] == theBetweenNode2) {
4519               nbInserted = theNodesToInsert.size();
4520
4521               // add nodes to insert
4522               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4523               for (; nIt != theNodesToInsert.end(); nIt++) {
4524                 poly_nodes.push_back(*nIt);
4525               }
4526             }
4527           } else if (faceNodes[inode] == theBetweenNode2) {
4528             if (faceNodes[inode + 1] == theBetweenNode1) {
4529               nbInserted = theNodesToInsert.size();
4530
4531               // add nodes to insert in reversed order
4532               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4533               nIt--;
4534               for (; nIt != theNodesToInsert.begin(); nIt--) {
4535                 poly_nodes.push_back(*nIt);
4536               }
4537               poly_nodes.push_back(*nIt);
4538             }
4539           } else {
4540           }
4541         }
4542       }
4543       quantities[iface] = nbFaceNodes + nbInserted;
4544     }
4545
4546     // Replace or update the volume
4547     SMESHDS_Mesh *aMesh = GetMeshDS();
4548
4549     if (elem->IsPoly()) {
4550       aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4551
4552     } else {
4553       int aShapeId = FindShape( elem );
4554
4555       SMDS_MeshElement* newElem =
4556         aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4557       if (aShapeId && newElem)
4558         aMesh->SetMeshElementOnShape(newElem, aShapeId);
4559
4560       aMesh->RemoveElement(elem);
4561     }
4562   }
4563 }
4564
4565 //=======================================================================
4566 //function : SewSideElements
4567 //purpose  :
4568 //=======================================================================
4569
4570 SMESH_MeshEditor::Sew_Error
4571   SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4572                                      set<const SMDS_MeshElement*>& theSide2,
4573                                      const SMDS_MeshNode*          theFirstNode1,
4574                                      const SMDS_MeshNode*          theFirstNode2,
4575                                      const SMDS_MeshNode*          theSecondNode1,
4576                                      const SMDS_MeshNode*          theSecondNode2)
4577 {
4578   MESSAGE ("::::SewSideElements()");
4579   if ( theSide1.size() != theSide2.size() )
4580     return SEW_DIFF_NB_OF_ELEMENTS;
4581
4582   Sew_Error aResult = SEW_OK;
4583   // Algo:
4584   // 1. Build set of faces representing each side
4585   // 2. Find which nodes of the side 1 to merge with ones on the side 2
4586   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4587
4588   // =======================================================================
4589   // 1. Build set of faces representing each side:
4590   // =======================================================================
4591   // a. build set of nodes belonging to faces
4592   // b. complete set of faces: find missing fices whose nodes are in set of nodes
4593   // c. create temporary faces representing side of volumes if correspondent
4594   //    face does not exist
4595
4596   SMESHDS_Mesh* aMesh = GetMeshDS();
4597   SMDS_Mesh aTmpFacesMesh;
4598   set<const SMDS_MeshElement*> faceSet1, faceSet2;
4599   set<const SMDS_MeshElement*> volSet1,  volSet2;
4600   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
4601   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4602   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
4603   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4604   set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4605   int iSide, iFace, iNode;
4606
4607   for ( iSide = 0; iSide < 2; iSide++ ) {
4608     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
4609     set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4610     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4611     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
4612     set<const SMDS_MeshElement*>::iterator vIt, eIt;
4613     set<const SMDS_MeshNode*>::iterator    nIt;
4614
4615   // -----------------------------------------------------------
4616   // 1a. Collect nodes of existing faces
4617   //     and build set of face nodes in order to detect missing
4618   //     faces corresponing to sides of volumes
4619   // -----------------------------------------------------------
4620
4621     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4622
4623     // loop on the given element of a side
4624     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4625       const SMDS_MeshElement* elem = *eIt;
4626       if ( elem->GetType() == SMDSAbs_Face ) {
4627         faceSet->insert( elem );
4628         set <const SMDS_MeshNode*> faceNodeSet;
4629         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4630         while ( nodeIt->more() ) {
4631           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4632           nodeSet->insert( n );
4633           faceNodeSet.insert( n );
4634         }
4635         setOfFaceNodeSet.insert( faceNodeSet );
4636       }
4637       else if ( elem->GetType() == SMDSAbs_Volume )
4638         volSet->insert( elem );
4639     }
4640     // ------------------------------------------------------------------------------
4641     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4642     // ------------------------------------------------------------------------------
4643
4644     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4645       SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4646       while ( fIt->more() ) { // loop on faces sharing a node
4647         const SMDS_MeshElement* f = fIt->next();
4648         if ( faceSet->find( f ) == faceSet->end() ) {
4649           // check if all nodes are in nodeSet and
4650           // complete setOfFaceNodeSet if they are
4651           set <const SMDS_MeshNode*> faceNodeSet;
4652           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4653           bool allInSet = true;
4654           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4655             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4656             if ( nodeSet->find( n ) == nodeSet->end() )
4657               allInSet = false;
4658             else
4659               faceNodeSet.insert( n );
4660           }
4661           if ( allInSet ) {
4662             faceSet->insert( f );
4663             setOfFaceNodeSet.insert( faceNodeSet );
4664           }
4665         }
4666       }
4667     }
4668
4669     // -------------------------------------------------------------------------
4670     // 1c. Create temporary faces representing sides of volumes if correspondent
4671     //     face does not exist
4672     // -------------------------------------------------------------------------
4673
4674     if ( !volSet->empty() )
4675     {
4676       //int nodeSetSize = nodeSet->size();
4677
4678       // loop on given volumes
4679       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4680         SMDS_VolumeTool vol (*vIt);
4681         // loop on volume faces: find free faces
4682         // --------------------------------------
4683         list<const SMDS_MeshElement* > freeFaceList;
4684         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4685           if ( !vol.IsFreeFace( iFace ))
4686             continue;
4687           // check if there is already a face with same nodes in a face set
4688           const SMDS_MeshElement* aFreeFace = 0;
4689           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4690           int nbNodes = vol.NbFaceNodes( iFace );
4691           set <const SMDS_MeshNode*> faceNodeSet;
4692           vol.GetFaceNodes( iFace, faceNodeSet );
4693           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4694           if ( isNewFace ) {
4695             // no such a face is given but it still can exist, check it
4696             if ( nbNodes == 3 ) {
4697               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4698             } else if ( nbNodes == 4 ) {
4699               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4700             } else {
4701               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4702               for (int inode = 0; inode < nbNodes; inode++) {
4703                 poly_nodes[inode] = fNodes[inode];
4704               }
4705               aFreeFace = aMesh->FindFace(poly_nodes);
4706             }
4707           }
4708           if ( !aFreeFace ) {
4709             // create a temporary face
4710             if ( nbNodes == 3 ) {
4711               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4712             } else if ( nbNodes == 4 ) {
4713               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4714             } else {
4715               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4716               for (int inode = 0; inode < nbNodes; inode++) {
4717                 poly_nodes[inode] = fNodes[inode];
4718               }
4719               aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4720             }
4721           }
4722           if ( aFreeFace )
4723             freeFaceList.push_back( aFreeFace );
4724
4725         } // loop on faces of a volume
4726
4727         // choose one of several free faces
4728         // --------------------------------------
4729         if ( freeFaceList.size() > 1 ) {
4730           // choose a face having max nb of nodes shared by other elems of a side
4731           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4732           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4733           while ( fIt != freeFaceList.end() ) { // loop on free faces
4734             int nbSharedNodes = 0;
4735             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4736             while ( nodeIt->more() ) { // loop on free face nodes
4737               const SMDS_MeshNode* n =
4738                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4739               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4740               while ( invElemIt->more() ) {
4741                 const SMDS_MeshElement* e = invElemIt->next();
4742                 if ( faceSet->find( e ) != faceSet->end() )
4743                   nbSharedNodes++;
4744                 if ( elemSet->find( e ) != elemSet->end() )
4745                   nbSharedNodes++;
4746               }
4747             }
4748             if ( nbSharedNodes >= maxNbNodes ) {
4749               maxNbNodes = nbSharedNodes;
4750               fIt++;
4751             }
4752             else
4753               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4754           }
4755           if ( freeFaceList.size() > 1 )
4756           {
4757             // could not choose one face, use another way
4758             // choose a face most close to the bary center of the opposite side
4759             gp_XYZ aBC( 0., 0., 0. );
4760             set <const SMDS_MeshNode*> addedNodes;
4761             set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4762             eIt = elemSet2->begin();
4763             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4764               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4765               while ( nodeIt->more() ) { // loop on free face nodes
4766                 const SMDS_MeshNode* n =
4767                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4768                 if ( addedNodes.insert( n ).second )
4769                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4770               }
4771             }
4772             aBC /= addedNodes.size();
4773             double minDist = DBL_MAX;
4774             fIt = freeFaceList.begin();
4775             while ( fIt != freeFaceList.end() ) { // loop on free faces
4776               double dist = 0;
4777               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4778               while ( nodeIt->more() ) { // loop on free face nodes
4779                 const SMDS_MeshNode* n =
4780                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4781                 gp_XYZ p( n->X(),n->Y(),n->Z() );
4782                 dist += ( aBC - p ).SquareModulus();
4783               }
4784               if ( dist < minDist ) {
4785                 minDist = dist;
4786                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4787               }
4788               else
4789                 fIt = freeFaceList.erase( fIt++ );
4790             }
4791           }
4792         } // choose one of several free faces of a volume
4793
4794         if ( freeFaceList.size() == 1 ) {
4795           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4796           faceSet->insert( aFreeFace );
4797           // complete a node set with nodes of a found free face
4798 //           for ( iNode = 0; iNode < ; iNode++ )
4799 //             nodeSet->insert( fNodes[ iNode ] );
4800         }
4801
4802       } // loop on volumes of a side
4803
4804 //       // complete a set of faces if new nodes in a nodeSet appeared
4805 //       // ----------------------------------------------------------
4806 //       if ( nodeSetSize != nodeSet->size() ) {
4807 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4808 //           SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4809 //           while ( fIt->more() ) { // loop on faces sharing a node
4810 //             const SMDS_MeshElement* f = fIt->next();
4811 //             if ( faceSet->find( f ) == faceSet->end() ) {
4812 //               // check if all nodes are in nodeSet and
4813 //               // complete setOfFaceNodeSet if they are
4814 //               set <const SMDS_MeshNode*> faceNodeSet;
4815 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4816 //               bool allInSet = true;
4817 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4818 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4819 //                 if ( nodeSet->find( n ) == nodeSet->end() )
4820 //                   allInSet = false;
4821 //                 else
4822 //                   faceNodeSet.insert( n );
4823 //               }
4824 //               if ( allInSet ) {
4825 //                 faceSet->insert( f );
4826 //                 setOfFaceNodeSet.insert( faceNodeSet );
4827 //               }
4828 //             }
4829 //           }
4830 //         }
4831 //       }
4832     } // Create temporary faces, if there are volumes given
4833   } // loop on sides
4834
4835   if ( faceSet1.size() != faceSet2.size() ) {
4836     // delete temporary faces: they are in reverseElements of actual nodes
4837     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4838     while ( tmpFaceIt->more() )
4839       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4840     MESSAGE("Diff nb of faces");
4841     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4842   }
4843
4844   // ============================================================
4845   // 2. Find nodes to merge:
4846   //              bind a node to remove to a node to put instead
4847   // ============================================================
4848
4849   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4850   if ( theFirstNode1 != theFirstNode2 )
4851     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4852   if ( theSecondNode1 != theSecondNode2 )
4853     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4854
4855   LinkID_Gen aLinkID_Gen( GetMeshDS() );
4856   set< long > linkIdSet; // links to process
4857   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4858
4859   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4860   list< TPairOfNodes > linkList[2];
4861   linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4862   linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4863   // loop on links in linkList; find faces by links and append links
4864   // of the found faces to linkList
4865   list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4866   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4867   {
4868     TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4869     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4870     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4871       continue;
4872
4873     // by links, find faces in the face sets,
4874     // and find indices of link nodes in the found faces;
4875     // in a face set, there is only one or no face sharing a link
4876     // ---------------------------------------------------------------
4877
4878     const SMDS_MeshElement* face[] = { 0, 0 };
4879     const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4880     const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4881     int iLinkNode[2][2];
4882     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4883       const SMDS_MeshNode* n1 = link[iSide].first;
4884       const SMDS_MeshNode* n2 = link[iSide].second;
4885       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4886       set< const SMDS_MeshElement* > fMap;
4887       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4888         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4889         SMDS_ElemIteratorPtr fIt = n->facesIterator();
4890         while ( fIt->more() ) { // loop on faces sharing a node
4891           const SMDS_MeshElement* f = fIt->next();
4892           if (faceSet->find( f ) != faceSet->end() && // f is in face set
4893               ! fMap.insert( f ).second ) // f encounters twice
4894           {
4895             if ( face[ iSide ] ) {
4896               MESSAGE( "2 faces per link " );
4897               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4898               break;
4899             }
4900             face[ iSide ] = f;
4901             faceSet->erase( f );
4902             // get face nodes and find ones of a link
4903             iNode = 0;
4904             SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4905             while ( nIt->more() ) {
4906               const SMDS_MeshNode* n =
4907                 static_cast<const SMDS_MeshNode*>( nIt->next() );
4908               if ( n == n1 )
4909                 iLinkNode[ iSide ][ 0 ] = iNode;
4910               else if ( n == n2 )
4911                 iLinkNode[ iSide ][ 1 ] = iNode;
4912               else if ( notLinkNodes[ iSide ][ 0 ] )
4913                 notLinkNodes[ iSide ][ 1 ] = n;
4914               else
4915                 notLinkNodes[ iSide ][ 0 ] = n;
4916               faceNodes[ iSide ][ iNode++ ] = n;
4917             }
4918             faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4919           }
4920         }
4921       }
4922     }
4923     // check similarity of elements of the sides
4924     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4925       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4926       if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4927         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4928       else
4929         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4930       break; // do not return because it s necessary to remove tmp faces
4931     }
4932
4933     // set nodes to merge
4934     // -------------------
4935
4936     if ( face[0] && face[1] )
4937     {
4938       int nbNodes = face[0]->NbNodes();
4939       if ( nbNodes != face[1]->NbNodes() ) {
4940         MESSAGE("Diff nb of face nodes");
4941         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4942         break; // do not return because it s necessary to remove tmp faces
4943       }
4944       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4945       if ( nbNodes == 3 )
4946         nReplaceMap.insert( TNodeNodeMap::value_type
4947                            ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4948       else {
4949         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4950           // analyse link orientation in faces
4951           int i1 = iLinkNode[ iSide ][ 0 ];
4952           int i2 = iLinkNode[ iSide ][ 1 ];
4953           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4954           // if notLinkNodes are the first and the last ones, then
4955           // their order does not correspond to the link orientation
4956           if (( i1 == 1 && i2 == 2 ) ||
4957               ( i1 == 2 && i2 == 1 ))
4958             reverse[ iSide ] = !reverse[ iSide ];
4959         }
4960         if ( reverse[0] == reverse[1] ) {
4961           nReplaceMap.insert( TNodeNodeMap::value_type
4962                              ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4963           nReplaceMap.insert( TNodeNodeMap::value_type
4964                              ( notLinkNodes[0][1], notLinkNodes[1][1] ));
4965         }
4966         else {
4967           nReplaceMap.insert( TNodeNodeMap::value_type
4968                              ( notLinkNodes[0][0], notLinkNodes[1][1] ));
4969           nReplaceMap.insert( TNodeNodeMap::value_type
4970                              ( notLinkNodes[0][1], notLinkNodes[1][0] ));
4971         }
4972       }
4973
4974       // add other links of the faces to linkList
4975       // -----------------------------------------
4976
4977       const SMDS_MeshNode** nodes = faceNodes[ 0 ];
4978       for ( iNode = 0; iNode < nbNodes; iNode++ )
4979       {
4980         linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
4981         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
4982         if ( !iter_isnew.second ) { // already in a set: no need to process
4983           linkIdSet.erase( iter_isnew.first );
4984         }
4985         else // new in set == encountered for the first time: add
4986         {
4987           const SMDS_MeshNode* n1 = nodes[ iNode ];
4988           const SMDS_MeshNode* n2 = nodes[ iNode + 1];
4989           linkList[0].push_back ( TPairOfNodes( n1, n2 ));
4990           linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
4991         }
4992       }
4993     } // 2 faces found
4994   } // loop on link lists
4995
4996   if ( aResult == SEW_OK &&
4997       ( linkIt[0] != linkList[0].end() ||
4998        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
4999     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
5000             " " << (faceSetPtr[1]->empty()));
5001     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5002   }
5003
5004   // ====================================================================
5005   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
5006   // ====================================================================
5007
5008   // delete temporary faces: they are in reverseElements of actual nodes
5009   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
5010   while ( tmpFaceIt->more() )
5011     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
5012
5013   if ( aResult != SEW_OK)
5014     return aResult;
5015
5016   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
5017   // loop on nodes replacement map
5018   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
5019   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
5020     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
5021     {
5022       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
5023       nodeIDsToRemove.push_back( nToRemove->GetID() );
5024       // loop on elements sharing nToRemove
5025       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
5026       while ( invElemIt->more() ) {
5027         const SMDS_MeshElement* e = invElemIt->next();
5028         // get a new suite of nodes: make replacement
5029         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
5030         const SMDS_MeshNode* nodes[ 8 ];
5031         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5032         while ( nIt->more() ) {
5033           const SMDS_MeshNode* n =
5034             static_cast<const SMDS_MeshNode*>( nIt->next() );
5035           nnIt = nReplaceMap.find( n );
5036           if ( nnIt != nReplaceMap.end() ) {
5037             nbReplaced++;
5038             n = (*nnIt).second;
5039           }
5040           nodes[ i++ ] = n;
5041         }
5042         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5043         //         elemIDsToRemove.push_back( e->GetID() );
5044         //       else
5045         if ( nbReplaced )
5046           aMesh->ChangeElementNodes( e, nodes, nbNodes );
5047       }
5048   }
5049
5050   Remove( nodeIDsToRemove, true );
5051
5052   return aResult;
5053 }