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