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