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