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