Salome HOME
Merge from V6_main (04/10/2012)
[modules/smesh.git] / src / SMESH / SMESH_MesherHelper.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  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.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // File:      SMESH_MesherHelper.cxx
24 // Created:   15.02.06 15:22:41
25 // Author:    Sergey KUUL
26 //
27 #include "SMESH_MesherHelper.hxx"
28
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FaceOfNodes.hxx"
31 #include "SMDS_FacePosition.hxx" 
32 #include "SMDS_IteratorOnIterators.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMESH_ProxyMesh.hxx"
35 #include "SMESH_subMesh.hxx"
36
37 #include <BRepAdaptor_Curve.hxx>
38 #include <BRepAdaptor_Surface.hxx>
39 #include <BRepClass3d_SolidClassifier.hxx>
40 #include <BRepTools.hxx>
41 #include <BRepTools_WireExplorer.hxx>
42 #include <BRep_Tool.hxx>
43 #include <Geom2d_Curve.hxx>
44 #include <GeomAPI_ProjectPointOnCurve.hxx>
45 #include <GeomAPI_ProjectPointOnSurf.hxx>
46 #include <Geom_Curve.hxx>
47 #include <Geom_RectangularTrimmedSurface.hxx>
48 #include <Geom_Surface.hxx>
49 #include <ShapeAnalysis.hxx>
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_ListIteratorOfListOfShape.hxx>
53 #include <TopTools_MapIteratorOfMapOfShape.hxx>
54 #include <TopTools_MapOfShape.hxx>
55 #include <TopoDS.hxx>
56 #include <gp_Ax3.hxx>
57 #include <gp_Pnt2d.hxx>
58 #include <gp_Trsf.hxx>
59
60 #include <Standard_Failure.hxx>
61 #include <Standard_ErrorHandler.hxx>
62
63 #include <utilities.h>
64
65 #include <limits>
66
67 using namespace std;
68
69 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
70
71 namespace {
72
73   gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
74
75   enum { U_periodic = 1, V_periodic = 2 };
76 }
77
78 //================================================================================
79 /*!
80  * \brief Constructor
81  */
82 //================================================================================
83
84 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
85   : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false),
86     myFixNodeParameters(false)
87 {
88   myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
89   mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
90 }
91
92 //=======================================================================
93 //function : ~SMESH_MesherHelper
94 //purpose  : 
95 //=======================================================================
96
97 SMESH_MesherHelper::~SMESH_MesherHelper()
98 {
99   {
100     TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
101     for ( ; i_proj != myFace2Projector.end(); ++i_proj )
102       delete i_proj->second;
103   }
104   {
105     TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
106     for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
107       delete i_proj->second;
108   }
109 }
110
111 //=======================================================================
112 //function : IsQuadraticSubMesh
113 //purpose  : Check submesh for given shape: if all elements on this shape 
114 //           are quadratic, quadratic elements will be created.
115 //           Also fill myTLinkNodeMap
116 //=======================================================================
117
118 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
119 {
120   SMESHDS_Mesh* meshDS = GetMeshDS();
121   // we can create quadratic elements only if all elements
122   // created on sub-shapes of given shape are quadratic
123   // also we have to fill myTLinkNodeMap
124   myCreateQuadratic = true;
125   mySeamShapeIds.clear();
126   myDegenShapeIds.clear();
127   TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
128   if ( aSh.ShapeType()==TopAbs_COMPOUND )
129   {
130     TopoDS_Iterator subIt( aSh );
131     if ( subIt.More() )
132       subType = ( subIt.Value().ShapeType()==TopAbs_FACE ) ? TopAbs_EDGE : TopAbs_FACE;
133   }
134   SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
135
136
137   int nbOldLinks = myTLinkNodeMap.size();
138
139   if ( !myMesh->HasShapeToMesh() )
140   {
141     if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
142     {
143       SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
144       while ( fIt->more() )
145         AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
146     }
147   }
148   else
149   {
150     TopExp_Explorer exp( aSh, subType );
151     TopTools_MapOfShape checkedSubShapes;
152     for (; exp.More() && myCreateQuadratic; exp.Next()) {
153       if ( !checkedSubShapes.Add( exp.Current() ))
154         continue; // needed if aSh is compound of solids
155       if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
156         if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
157           while(it->more()) {
158             const SMDS_MeshElement* e = it->next();
159             if ( e->GetType() != elemType || !e->IsQuadratic() ) {
160               myCreateQuadratic = false;
161               break;
162             }
163             else {
164               // fill TLinkNodeMap
165               switch ( e->NbNodes() ) {
166               case 3:
167                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
168               case 6:
169                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
170                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
171                 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
172               case 8:
173                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
174                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
175                 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
176                 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
177                 break;
178               default:
179                 myCreateQuadratic = false;
180                 break;
181               }
182             }
183           }
184         }
185       }
186     }
187   }
188
189   if ( nbOldLinks == myTLinkNodeMap.size() )
190     myCreateQuadratic = false;
191
192   if(!myCreateQuadratic) {
193     myTLinkNodeMap.clear();
194   }
195   SetSubShape( aSh );
196
197   return myCreateQuadratic;
198 }
199
200 //=======================================================================
201 //function : SetSubShape
202 //purpose  : Set geomerty to make elements on
203 //=======================================================================
204
205 void SMESH_MesherHelper::SetSubShape(const int aShID)
206 {
207   if ( aShID == myShapeID )
208     return;
209   if ( aShID > 0 )
210     SetSubShape( GetMeshDS()->IndexToShape( aShID ));
211   else
212     SetSubShape( TopoDS_Shape() );
213 }
214
215 //=======================================================================
216 //function : SetSubShape
217 //purpose  : Set geomerty to create elements on
218 //=======================================================================
219
220 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
221 {
222   if ( myShape.IsSame( aSh ))
223     return;
224
225   myShape = aSh;
226   mySeamShapeIds.clear();
227   myDegenShapeIds.clear();
228
229   if ( myShape.IsNull() ) {
230     myShapeID  = 0;
231     return;
232   }
233   SMESHDS_Mesh* meshDS = GetMeshDS();
234   myShapeID = meshDS->ShapeToIndex(aSh);
235   myParIndex = 0;
236
237   // treatment of periodic faces
238   for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
239   {
240     const TopoDS_Face& face = TopoDS::Face( eF.Current() );
241     TopLoc_Location loc;
242     Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
243
244     if ( surface->IsUPeriodic() || surface->IsVPeriodic() ||
245          surface->IsUClosed()   || surface->IsVClosed() )
246     {
247       //while ( surface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
248       //surface = Handle(Geom_RectangularTrimmedSurface)::DownCast( surface )->BasisSurface();
249       GeomAdaptor_Surface surf( surface );
250
251       for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
252       {
253         // look for a seam edge
254         const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
255         if ( BRep_Tool::IsClosed( edge, face )) {
256           // initialize myPar1, myPar2 and myParIndex
257           gp_Pnt2d uv1, uv2;
258           BRep_Tool::UVPoints( edge, face, uv1, uv2 );
259           if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
260           {
261             myParIndex |= U_periodic;
262             myPar1[0] = surf.FirstUParameter();
263             myPar2[0] = surf.LastUParameter();
264           }
265           else {
266             myParIndex |= V_periodic;
267             myPar1[1] = surf.FirstVParameter();
268             myPar2[1] = surf.LastVParameter();
269           }
270           // store seam shape indices, negative if shape encounters twice
271           int edgeID = meshDS->ShapeToIndex( edge );
272           mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
273           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
274             int vertexID = meshDS->ShapeToIndex( v.Current() );
275             mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
276           }
277         }
278
279         // look for a degenerated edge
280         if ( BRep_Tool::Degenerated( edge )) {
281           myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
282           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
283             myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
284         }
285       }
286     }
287   }
288 }
289
290 //=======================================================================
291 //function : GetNodeUVneedInFaceNode
292 //purpose  : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
293 //           Return true if the face is periodic.
294 //           If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
295 //           * SetSubShape()
296 //=======================================================================
297
298 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
299 {
300   if ( F.IsNull() ) return !mySeamShapeIds.empty();
301
302   if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
303     return !mySeamShapeIds.empty();
304
305   TopLoc_Location loc;
306   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
307   if ( !aSurface.IsNull() )
308     return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
309
310   return false;
311 }
312
313 //=======================================================================
314 //function : IsMedium
315 //purpose  : 
316 //=======================================================================
317
318 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode*      node,
319                                   const SMDSAbs_ElementType typeToCheck)
320 {
321   return SMESH_MeshEditor::IsMedium( node, typeToCheck );
322 }
323
324 //=======================================================================
325 //function : GetSubShapeByNode
326 //purpose  : Return support shape of a node
327 //=======================================================================
328
329 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
330                                                    const SMESHDS_Mesh*  meshDS)
331 {
332   int shapeID = node->getshapeId();
333   if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
334     return meshDS->IndexToShape( shapeID );
335   else
336     return TopoDS_Shape();
337 }
338
339
340 //=======================================================================
341 //function : AddTLinkNode
342 //purpose  : add a link in my data structure
343 //=======================================================================
344
345 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
346                                       const SMDS_MeshNode* n2,
347                                       const SMDS_MeshNode* n12)
348 {
349   // add new record to map
350   SMESH_TLink link( n1, n2 );
351   myTLinkNodeMap.insert( make_pair(link,n12));
352 }
353
354 //================================================================================
355 /*!
356  * \brief Add quadratic links of edge to own data structure
357  */
358 //================================================================================
359
360 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
361 {
362   if ( edge->IsQuadratic() )
363     AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
364 }
365
366 //================================================================================
367 /*!
368  * \brief Add quadratic links of face to own data structure
369  */
370 //================================================================================
371
372 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
373 {
374   if ( !f->IsPoly() )
375     switch ( f->NbNodes() ) {
376     case 6:
377       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
378       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
379       AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
380     case 8:
381       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
382       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
383       AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
384       AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7));
385     default:;
386     }
387 }
388
389 //================================================================================
390 /*!
391  * \brief Add quadratic links of volume to own data structure
392  */
393 //================================================================================
394
395 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
396 {
397   if ( volume->IsQuadratic() )
398   {
399     SMDS_VolumeTool vTool( volume );
400     const SMDS_MeshNode** nodes = vTool.GetNodes();
401     set<int> addedLinks;
402     for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
403     {
404       const int nbN = vTool.NbFaceNodes( iF );
405       const int* iNodes = vTool.GetFaceNodesIndices( iF );
406       for ( int i = 0; i < nbN; )
407       {
408         int iN1  = iNodes[i++];
409         int iN12 = iNodes[i++];
410         int iN2  = iNodes[i];
411         if ( iN1 > iN2 ) std::swap( iN1, iN2 );
412         int linkID = iN1 * vTool.NbNodes() + iN2;
413         pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
414         if ( it_isNew.second )
415           AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
416         else
417           addedLinks.erase( it_isNew.first ); // each link encounters only twice
418       }
419     }
420   }
421 }
422
423 //================================================================================
424 /*!
425  * \brief Return true if position of nodes on the shape hasn't yet been checked or
426  * the positions proved to be invalid
427  */
428 //================================================================================
429
430 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
431 {
432   map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
433   return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
434 }
435
436 //================================================================================
437 /*!
438  * \brief Set validity of positions of nodes on the shape.
439  * Once set, validity is not changed
440  */
441 //================================================================================
442
443 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
444 {
445   ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok));
446 }
447
448 //=======================================================================
449 //function : ToFixNodeParameters
450 //purpose  : Enables fixing node parameters on EDGEs and FACEs in 
451 //           GetNodeU(...,check=true), GetNodeUV(...,check=true), CheckNodeUV() and
452 //           CheckNodeU() in case if a node lies on a shape set via SetSubShape().
453 //           Default is False
454 //=======================================================================
455
456 void SMESH_MesherHelper::ToFixNodeParameters(bool toFix)
457 {
458   myFixNodeParameters = toFix;
459 }
460
461
462 //=======================================================================
463 //function : GetUVOnSeam
464 //purpose  : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
465 //=======================================================================
466
467 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
468 {
469   gp_Pnt2d result = uv1;
470   for ( int i = U_periodic; i <= V_periodic ; ++i )
471   {
472     if ( myParIndex & i )
473     {
474       double p1 = uv1.Coord( i );
475       double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
476       if ( myParIndex == i ||
477            dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
478            dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
479       {
480         double p2 = uv2.Coord( i );
481         double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
482         if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
483           result.SetCoord( i, p1Alt );
484       }
485     }
486   }
487   return result;
488 }
489
490 //=======================================================================
491 //function : GetNodeUV
492 //purpose  : Return node UV on face
493 //=======================================================================
494
495 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face&   F,
496                                     const SMDS_MeshNode* n,
497                                     const SMDS_MeshNode* n2,
498                                     bool*                check) const
499 {
500   gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
501   const SMDS_PositionPtr Pos = n->GetPosition();
502   bool uvOK = false;
503   if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
504   {
505     // node has position on face
506     const SMDS_FacePosition* fpos =
507       static_cast<const SMDS_FacePosition*>(n->GetPosition());
508     uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
509     if ( check )
510       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
511   }
512   else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
513   {
514     // node has position on edge => it is needed to find
515     // corresponding edge from face, get pcurve for this
516     // edge and retrieve value from this pcurve
517     const SMDS_EdgePosition* epos =
518       static_cast<const SMDS_EdgePosition*>(n->GetPosition());
519     int edgeID = n->getshapeId();
520     TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
521     double f, l, u = epos->GetUParameter();
522     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
523     bool validU = ( f < u && u < l );
524     if ( validU )
525       uv = C2d->Value( u );
526     else
527       uv.SetCoord( Precision::Infinite(),0.);
528     if ( check || !validU )
529       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ),/*force=*/ !validU );
530
531     // for a node on a seam edge select one of UVs on 2 pcurves
532     if ( n2 && IsSeamShape( edgeID ) )
533     {
534       uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
535     }
536     else
537     { // adjust uv to period
538       TopLoc_Location loc;
539       Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
540       Standard_Boolean isUPeriodic = S->IsUPeriodic();
541       Standard_Boolean isVPeriodic = S->IsVPeriodic();
542       if ( isUPeriodic || isVPeriodic ) {
543         Standard_Real UF,UL,VF,VL;
544         S->Bounds(UF,UL,VF,VL);
545         if(isUPeriodic)
546           uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
547         if(isVPeriodic)
548           uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
549       }
550     }
551   }
552   else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
553   {
554     if ( int vertexID = n->getshapeId() ) {
555       const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
556       try {
557         uv = BRep_Tool::Parameters( V, F );
558         uvOK = true;
559       }
560       catch (Standard_Failure& exc) {
561       }
562       if ( !uvOK ) {
563         for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
564           uvOK = ( V == vert.Current() );
565         if ( !uvOK ) {
566 #ifdef _DEBUG_
567           MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
568                << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
569 #endif
570           // get UV of a vertex closest to the node
571           double dist = 1e100;
572           gp_Pnt pn = XYZ( n );
573           for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
574             TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
575             gp_Pnt p = BRep_Tool::Pnt( curV );
576             double curDist = p.SquareDistance( pn );
577             if ( curDist < dist ) {
578               dist = curDist;
579               uv = BRep_Tool::Parameters( curV, F );
580               uvOK = ( dist < DBL_MIN );
581             }
582           }
583         }
584         else {
585           uvOK = false;
586           TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
587           for ( ; it.More(); it.Next() ) {
588             if ( it.Value().ShapeType() == TopAbs_EDGE ) {
589               const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
590               double f,l;
591               Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
592               if ( !C2d.IsNull() ) {
593                 double u = ( V == TopExp::FirstVertex( edge ) ) ?  f : l;
594                 uv = C2d->Value( u );
595                 uvOK = true;
596                 break;
597               }
598             }
599           }
600         }
601       }
602       if ( n2 && IsSeamShape( vertexID ) )
603         uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
604     }
605   }
606   else
607   {
608     uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
609   }
610
611   if ( check )
612     *check = uvOK;
613
614   return uv.XY();
615 }
616
617 //=======================================================================
618 //function : CheckNodeUV
619 //purpose  : Check and fix node UV on a face
620 //=======================================================================
621
622 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face&   F,
623                                      const SMDS_MeshNode* n,
624                                      gp_XY&               uv,
625                                      const double         tol,
626                                      const bool           force,
627                                      double               distXYZ[4]) const
628 {
629   int shapeID = n->getshapeId();
630   bool infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ));
631   if ( force || toCheckPosOnShape( shapeID ) || infinit )
632   {
633     // check that uv is correct
634     TopLoc_Location loc;
635     Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
636     gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
637     double dist = 0;
638     if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
639     if ( infinit ||
640          (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
641     {
642       setPosOnShapeValidity( shapeID, false );
643       if ( !infinit && distXYZ ) {
644         surfPnt.Transform( loc );
645         distXYZ[0] = dist;
646         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
647       }
648       // uv incorrect, project the node to surface
649       GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
650       projector.Perform( nodePnt );
651       if ( !projector.IsDone() || projector.NbPoints() < 1 )
652       {
653         MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
654         return false;
655       }
656       Quantity_Parameter U,V;
657       projector.LowerDistanceParameters(U,V);
658       uv.SetCoord( U,V );
659       surfPnt = surface->Value( U, V );
660       dist = nodePnt.Distance( surfPnt );
661       if ( distXYZ ) {
662         surfPnt.Transform( loc );
663         distXYZ[0] = dist;
664         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
665       }
666       if ( dist > tol )
667       {
668         MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
669         return false;
670       }
671       // store the fixed UV on the face
672       if ( myShape.IsSame(F) && shapeID == myShapeID && myFixNodeParameters )
673         const_cast<SMDS_MeshNode*>(n)->SetPosition
674           ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
675     }
676     else if ( uv.Modulus() > numeric_limits<double>::min() )
677     {
678       setPosOnShapeValidity( shapeID, true );
679     }
680   }
681   return true;
682 }
683
684 //=======================================================================
685 //function : GetProjector
686 //purpose  : Return projector intitialized by given face without location, which is returned
687 //=======================================================================
688
689 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
690                                                              TopLoc_Location&   loc,
691                                                              double             tol ) const
692 {
693   Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
694   int faceID = GetMeshDS()->ShapeToIndex( F );
695   TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
696   TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
697   if ( i_proj == i2proj.end() )
698   {
699     if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
700     double U1, U2, V1, V2;
701     surface->Bounds(U1, U2, V1, V2);
702     GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
703     proj->Init( surface, U1, U2, V1, V2, tol );
704     i_proj = i2proj.insert( make_pair( faceID, proj )).first;
705   }
706   return *( i_proj->second );
707 }
708
709 namespace
710 {
711   gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
712   gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
713   gp_XY_FunPtr(Subtracted); 
714 }
715
716 //=======================================================================
717 //function : applyIn2D
718 //purpose  : Perform given operation on two 2d points in parameric space of given surface.
719 //           It takes into account period of the surface. Use gp_XY_FunPtr macro
720 //           to easily define pointer to function of gp_XY class.
721 //=======================================================================
722
723 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
724                                     const gp_XY&                uv1,
725                                     const gp_XY&                uv2,
726                                     xyFunPtr                    fun,
727                                     const bool                  resultInPeriod)
728 {
729   Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
730   Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
731   if ( !isUPeriodic && !isVPeriodic )
732     return fun(uv1,uv2);
733
734   // move uv2 not far than half-period from uv1
735   double u2 = 
736     uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
737   double v2 = 
738     uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
739
740   // execute operation
741   gp_XY res = fun( uv1, gp_XY(u2,v2) );
742
743   // move result within period
744   if ( resultInPeriod )
745   {
746     Standard_Real UF,UL,VF,VL;
747     surface->Bounds(UF,UL,VF,VL);
748     if ( isUPeriodic )
749       res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
750     if ( isVPeriodic )
751       res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
752   }
753
754   return res;
755 }
756 //=======================================================================
757 //function : GetMiddleUV
758 //purpose  : Return middle UV taking in account surface period
759 //=======================================================================
760
761 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
762                                       const gp_XY&                p1,
763                                       const gp_XY&                p2)
764 {
765   // NOTE:
766   // the proper place of getting basic surface seems to be in applyIn2D()
767   // but we put it here to decrease a risk of regressions just before releasing a version
768   Handle(Geom_Surface) surf = surface;
769   while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
770     surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
771
772   return applyIn2D( surf, p1, p2, & AverageUV );
773 }
774
775 //=======================================================================
776 //function : GetNodeU
777 //purpose  : Return node U on edge
778 //=======================================================================
779
780 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge&   E,
781                                     const SMDS_MeshNode* n,
782                                     const SMDS_MeshNode* inEdgeNode,
783                                     bool*                check)
784 {
785   double param = 0;
786   const SMDS_PositionPtr pos = n->GetPosition();
787   if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
788   {
789     const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
790     param =  epos->GetUParameter();
791   }
792   else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
793   {
794     if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
795     {
796       Standard_Real f,l;
797       BRep_Tool::Range( E, f,l );
798       double uInEdge = GetNodeU( E, inEdgeNode );
799       param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
800     }
801     else
802     {
803       SMESHDS_Mesh * meshDS = GetMeshDS();
804       int vertexID = n->getshapeId();
805       const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
806       param =  BRep_Tool::Parameter( V, E );
807     }
808   }
809   if ( check )
810   {
811     double tol = BRep_Tool::Tolerance( E );
812     double f,l;  BRep_Tool::Range( E, f,l );
813     bool force = ( param < f-tol || param > l+tol );
814     if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
815       force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
816
817     *check = CheckNodeU( E, n, param, 2*tol, force );
818   }
819   return param;
820 }
821
822 //=======================================================================
823 //function : CheckNodeU
824 //purpose  : Check and fix node U on an edge
825 //           Return false if U is bad and could not be fixed
826 //=======================================================================
827
828 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge&   E,
829                                     const SMDS_MeshNode* n,
830                                     double&              u,
831                                     const double         tol,
832                                     const bool           force,
833                                     double               distXYZ[4]) const
834 {
835   int shapeID = n->getshapeId();
836   if ( force || toCheckPosOnShape( shapeID ))
837   {
838     TopLoc_Location loc; double f,l;
839     Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
840     if ( curve.IsNull() ) // degenerated edge
841     {
842       if ( u+tol < f || u-tol > l )
843       {
844         double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
845         u =  f*r + l*(1-r);
846       }
847     }
848     else
849     {
850       gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
851       if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
852       gp_Pnt curvPnt = curve->Value( u );
853       double dist = nodePnt.Distance( curvPnt );
854       if ( distXYZ ) {
855         curvPnt.Transform( loc );
856         distXYZ[0] = dist;
857         distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
858       }
859       if ( dist > tol )
860       {
861         setPosOnShapeValidity( shapeID, false );
862         // u incorrect, project the node to the curve
863         int edgeID = GetMeshDS()->ShapeToIndex( E );
864         TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
865         TID2ProjectorOnCurve::iterator i_proj =
866           i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
867         if ( !i_proj->second  )
868         {
869           i_proj->second = new GeomAPI_ProjectPointOnCurve();
870           i_proj->second->Init( curve, f, l );
871         }
872         GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
873         projector->Perform( nodePnt );
874         if ( projector->NbPoints() < 1 )
875         {
876           MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
877           return false;
878         }
879         Quantity_Parameter U = projector->LowerDistanceParameter();
880         u = double( U );
881         curvPnt = curve->Value( u );
882         dist = nodePnt.Distance( curvPnt );
883         if ( distXYZ ) {
884           curvPnt.Transform( loc );
885           distXYZ[0] = dist;
886           distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
887         }
888         if ( dist > tol )
889         {
890           MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
891           MESSAGE("distance " << dist << " " << tol );
892           return false;
893         }
894         // store the fixed U on the edge
895         if ( myShape.IsSame(E) && shapeID == myShapeID && myFixNodeParameters )
896           const_cast<SMDS_MeshNode*>(n)->SetPosition
897             ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
898       }
899       else if ( fabs( u ) > numeric_limits<double>::min() )
900       {
901         setPosOnShapeValidity( shapeID, true );
902       }
903       if (( u < f-tol || u > l+tol ) && force )
904       {
905         // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
906         try
907         {
908           // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
909           double period = curve->Period();
910           u = ( u < f ) ? u + period : u - period;
911         }
912         catch (Standard_Failure& exc)
913         {
914           return false;
915         }
916       }
917     }
918   }
919   return true;
920 }
921
922 //=======================================================================
923 //function : GetMediumPos
924 //purpose  : Return index and type of the shape  (EDGE or FACE only) to
925 //          set a medium node on
926 //=======================================================================
927
928 std::pair<int, TopAbs_ShapeEnum> SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
929                                                                   const SMDS_MeshNode* n2)
930 {
931   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
932   int              shapeID = -1;
933   TopoDS_Shape     shape;
934
935   if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
936   {
937     shapeType = myShape.ShapeType();
938     shapeID   = myShapeID;
939   }
940   else if ( n1->getshapeId() == n2->getshapeId() )
941   {
942     shapeID = n2->getshapeId();
943     shape = GetSubShapeByNode( n1, GetMeshDS() );
944   }
945   else
946   {
947     const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
948     const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
949
950     if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
951     {
952     }
953     else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
954     {
955       if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE )
956       {
957         if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
958         TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
959         TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
960         if ( IsSubShape( S, F ))
961         {
962           shapeType = TopAbs_FACE;
963           shapeID   = n1->getshapeId();
964         }
965       }
966     }
967     else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
968     {
969       TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
970       TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
971       shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
972     }
973     else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
974     {
975       TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
976       TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
977       shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
978       if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
979     }
980     else // VERTEX and EDGE
981     {
982       if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
983       TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
984       TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
985       if ( IsSubShape( V, E ))
986         shape = E;
987       else
988         shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
989     }
990   }
991
992   if ( !shape.IsNull() )
993   {
994     if ( shapeID < 1 )
995       shapeID = GetMeshDS()->ShapeToIndex( shape );
996     shapeType = shape.ShapeType();
997   }
998   return make_pair( shapeID, shapeType );
999 }
1000
1001 //=======================================================================
1002 //function : GetMediumNode
1003 //purpose  : Return existing or create new medium nodes between given ones
1004 //=======================================================================
1005
1006 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
1007                                                        const SMDS_MeshNode* n2,
1008                                                        bool                 force3d)
1009 {
1010   // Find existing node
1011
1012   SMESH_TLink link(n1,n2);
1013   ItTLinkNode itLN = myTLinkNodeMap.find( link );
1014   if ( itLN != myTLinkNodeMap.end() ) {
1015     return (*itLN).second;
1016   }
1017
1018   // Create medium node
1019
1020   SMDS_MeshNode* n12;
1021   SMESHDS_Mesh* meshDS = GetMeshDS();
1022
1023   if ( IsSeamShape( n1->getshapeId() ))
1024     // to get a correct UV of a node on seam, the second node must have checked UV
1025     std::swap( n1, n2 );
1026
1027   // get type of shape for the new medium node
1028   int faceID = -1, edgeID = -1;
1029   TopoDS_Edge E; double u [2];
1030   TopoDS_Face F; gp_XY  uv[2];
1031   bool uvOK[2] = { false, false };
1032
1033   pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2 );
1034
1035   // get positions of the given nodes on shapes
1036   if ( pos.second == TopAbs_FACE )
1037   {
1038     F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1039     uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1040     uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1041   }
1042   else if ( pos.second == TopAbs_EDGE )
1043   {
1044     const SMDS_PositionPtr Pos1 = n1->GetPosition();
1045     const SMDS_PositionPtr Pos2 = n2->GetPosition();
1046     if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1047          Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1048          n1->getshapeId() != n2->getshapeId() )
1049     {
1050       // issue 0021006
1051       return getMediumNodeOnComposedWire(n1,n2,force3d);
1052     }
1053     E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1054     u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1055     u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1056   }
1057
1058   if ( !force3d & uvOK[0] && uvOK[1] )
1059   {
1060     // we try to create medium node using UV parameters of
1061     // nodes, else - medium between corresponding 3d points
1062     if( ! F.IsNull() )
1063     {
1064       //if ( uvOK[0] && uvOK[1] )
1065       {
1066         if ( IsDegenShape( n1->getshapeId() )) {
1067           if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1068           else                           uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1069         }
1070         else if ( IsDegenShape( n2->getshapeId() )) {
1071           if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1072           else                           uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1073         }
1074
1075         TopLoc_Location loc;
1076         Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1077         gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1078         gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1079         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1080         meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1081         myTLinkNodeMap.insert(make_pair(link,n12));
1082         return n12;
1083       }
1084     }
1085     else if ( !E.IsNull() )
1086     {
1087       double f,l;
1088       Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1089       if(!C.IsNull())
1090       {
1091         Standard_Boolean isPeriodic = C->IsPeriodic();
1092         double U;
1093         if(isPeriodic) {
1094           Standard_Real Period = C->Period();
1095           Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1096           Standard_Real pmid = (u[0]+p)/2.;
1097           U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1098         }
1099         else
1100           U = (u[0]+u[1])/2.;
1101
1102         gp_Pnt P = C->Value( U );
1103         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1104         meshDS->SetNodeOnEdge(n12, edgeID, U);
1105         myTLinkNodeMap.insert(make_pair(link,n12));
1106         return n12;
1107       }
1108     }
1109   }
1110
1111   // 3d variant
1112   double x = ( n1->X() + n2->X() )/2.;
1113   double y = ( n1->Y() + n2->Y() )/2.;
1114   double z = ( n1->Z() + n2->Z() )/2.;
1115   n12 = meshDS->AddNode(x,y,z);
1116
1117   if ( !F.IsNull() )
1118   {
1119     gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1120     CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1121     meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1122   }
1123   else if ( !E.IsNull() )
1124   {
1125     double U = ( u[0] + u[1] ) / 2.;
1126     CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
1127     meshDS->SetNodeOnEdge(n12, edgeID, U);
1128   }
1129   else if ( myShapeID > 0 )
1130   {
1131     meshDS->SetNodeInVolume(n12, myShapeID);
1132   }
1133
1134   myTLinkNodeMap.insert( make_pair( link, n12 ));
1135   return n12;
1136 }
1137
1138 //================================================================================
1139 /*!
1140  * \brief Makes a medium node if nodes reside different edges
1141  */
1142 //================================================================================
1143
1144 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1145                                                                      const SMDS_MeshNode* n2,
1146                                                                      bool                 force3d)
1147 {
1148   gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
1149   SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1150
1151   // To find position on edge and 3D position for n12,
1152   // project <middle> to 2 edges and select projection most close to <middle>
1153
1154   double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4];
1155   int iOkEdge = 0;
1156   TopoDS_Edge edges[2];
1157   for ( int is2nd = 0; is2nd < 2; ++is2nd )
1158   {
1159     // get an edge
1160     const SMDS_MeshNode* n = is2nd ? n2 : n1;
1161     TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
1162     if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
1163       continue;
1164
1165     // project to get U of projection and distance from middle to projection
1166     TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
1167     double node2MiddleDist = middle.Distance( XYZ(n) );
1168     double foundU = GetNodeU( edge, n );
1169     CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1170     if ( distXYZ[0] < node2MiddleDist )
1171     {
1172       distMiddleProj = distXYZ[0];
1173       u = foundU;
1174       iOkEdge = is2nd;
1175     }
1176   }
1177   if ( Precision::IsInfinite( distMiddleProj ))
1178   {
1179     // both projections failed; set n12 on the edge of n1 with U of a common vertex
1180     TopoDS_Vertex vCommon;
1181     if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1182       u = BRep_Tool::Parameter( vCommon, edges[0] );
1183     else
1184     {
1185       double f,l, u0 = GetNodeU( edges[0], n1 );
1186       BRep_Tool::Range( edges[0],f,l );
1187       u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1188     }
1189     iOkEdge = 0;
1190     distMiddleProj = 0;
1191   }
1192
1193   // move n12 to position of a successfull projection
1194   double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1195   if ( !force3d && distMiddleProj > 2*tol )
1196   {
1197     TopLoc_Location loc; double f,l;
1198     Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
1199     gp_Pnt p = curve->Value( u );
1200     GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1201   }
1202
1203   GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
1204
1205   myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1206
1207   return n12;
1208 }
1209
1210 //=======================================================================
1211 //function : AddNode
1212 //purpose  : Creates a node
1213 //=======================================================================
1214
1215 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID,
1216                                            double u, double v)
1217 {
1218   SMESHDS_Mesh * meshDS = GetMeshDS();
1219   SMDS_MeshNode* node = 0;
1220   if ( ID )
1221     node = meshDS->AddNodeWithID( x, y, z, ID );
1222   else
1223     node = meshDS->AddNode( x, y, z );
1224   if ( mySetElemOnShape && myShapeID > 0 ) {
1225     switch ( myShape.ShapeType() ) {
1226     case TopAbs_SOLID:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1227     case TopAbs_SHELL:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1228     case TopAbs_FACE:   meshDS->SetNodeOnFace(   node, myShapeID, u, v); break;
1229     case TopAbs_EDGE:   meshDS->SetNodeOnEdge(   node, myShapeID, u);    break;
1230     case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID);       break;
1231     default: ;
1232     }
1233   }
1234   return node;
1235 }
1236
1237 //=======================================================================
1238 //function : AddEdge
1239 //purpose  : Creates quadratic or linear edge
1240 //=======================================================================
1241
1242 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1243                                            const SMDS_MeshNode* n2,
1244                                            const int            id,
1245                                            const bool           force3d)
1246 {
1247   SMESHDS_Mesh * meshDS = GetMeshDS();
1248   
1249   SMDS_MeshEdge* edge = 0;
1250   if (myCreateQuadratic) {
1251     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1252     if(id)
1253       edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1254     else
1255       edge = meshDS->AddEdge(n1, n2, n12);
1256   }
1257   else {
1258     if(id)
1259       edge = meshDS->AddEdgeWithID(n1, n2, id);
1260     else
1261       edge = meshDS->AddEdge(n1, n2);
1262   }
1263
1264   if ( mySetElemOnShape && myShapeID > 0 )
1265     meshDS->SetMeshElementOnShape( edge, myShapeID );
1266
1267   return edge;
1268 }
1269
1270 //=======================================================================
1271 //function : AddFace
1272 //purpose  : Creates quadratic or linear triangle
1273 //=======================================================================
1274
1275 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1276                                            const SMDS_MeshNode* n2,
1277                                            const SMDS_MeshNode* n3,
1278                                            const int id,
1279                                            const bool force3d)
1280 {
1281   SMESHDS_Mesh * meshDS = GetMeshDS();
1282   SMDS_MeshFace* elem = 0;
1283
1284   if( n1==n2 || n2==n3 || n3==n1 )
1285     return elem;
1286
1287   if(!myCreateQuadratic) {
1288     if(id)
1289       elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1290     else
1291       elem = meshDS->AddFace(n1, n2, n3);
1292   }
1293   else {
1294     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1295     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1296     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1297
1298     if(id)
1299       elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1300     else
1301       elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1302   }
1303   if ( mySetElemOnShape && myShapeID > 0 )
1304     meshDS->SetMeshElementOnShape( elem, myShapeID );
1305
1306   return elem;
1307 }
1308
1309 //=======================================================================
1310 //function : AddFace
1311 //purpose  : Creates quadratic or linear quadrangle
1312 //=======================================================================
1313
1314 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1315                                            const SMDS_MeshNode* n2,
1316                                            const SMDS_MeshNode* n3,
1317                                            const SMDS_MeshNode* n4,
1318                                            const int            id,
1319                                            const bool           force3d)
1320 {
1321   SMESHDS_Mesh * meshDS = GetMeshDS();
1322   SMDS_MeshFace* elem = 0;
1323
1324   if( n1==n2 ) {
1325     return AddFace(n1,n3,n4,id,force3d);
1326   }
1327   if( n1==n3 ) {
1328     return AddFace(n1,n2,n4,id,force3d);
1329   }
1330   if( n1==n4 ) {
1331     return AddFace(n1,n2,n3,id,force3d);
1332   }
1333   if( n2==n3 ) {
1334     return AddFace(n1,n2,n4,id,force3d);
1335   }
1336   if( n2==n4 ) {
1337     return AddFace(n1,n2,n3,id,force3d);
1338   }
1339   if( n3==n4 ) {
1340     return AddFace(n1,n2,n3,id,force3d);
1341   }
1342
1343   if(!myCreateQuadratic) {
1344     if(id)
1345       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1346     else
1347       elem = meshDS->AddFace(n1, n2, n3, n4);
1348   }
1349   else {
1350     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1351     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1352     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1353     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1354
1355     if(id)
1356       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1357     else
1358       elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1359   }
1360   if ( mySetElemOnShape && myShapeID > 0 )
1361     meshDS->SetMeshElementOnShape( elem, myShapeID );
1362
1363   return elem;
1364 }
1365
1366 //=======================================================================
1367 //function : AddPolygonalFace
1368 //purpose  : Creates polygon, with additional nodes in quadratic mesh
1369 //=======================================================================
1370
1371 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1372                                                      const int                           id,
1373                                                      const bool                          force3d)
1374 {
1375   SMESHDS_Mesh * meshDS = GetMeshDS();
1376   SMDS_MeshFace* elem = 0;
1377
1378   if(!myCreateQuadratic) {
1379     if(id)
1380       elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1381     else
1382       elem = meshDS->AddPolygonalFace(nodes);
1383   }
1384   else {
1385     vector<const SMDS_MeshNode*> newNodes;
1386     for ( int i = 0; i < nodes.size(); ++i )
1387     {
1388       const SMDS_MeshNode* n1 = nodes[i];
1389       const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
1390       const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1391       newNodes.push_back( n1 );
1392       newNodes.push_back( n12 );
1393     }
1394     if(id)
1395       elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1396     else
1397       elem = meshDS->AddPolygonalFace(newNodes);
1398   }
1399   if ( mySetElemOnShape && myShapeID > 0 )
1400     meshDS->SetMeshElementOnShape( elem, myShapeID );
1401
1402   return elem;
1403 }
1404
1405 //=======================================================================
1406 //function : AddVolume
1407 //purpose  : Creates quadratic or linear prism
1408 //=======================================================================
1409
1410 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1411                                                const SMDS_MeshNode* n2,
1412                                                const SMDS_MeshNode* n3,
1413                                                const SMDS_MeshNode* n4,
1414                                                const SMDS_MeshNode* n5,
1415                                                const SMDS_MeshNode* n6,
1416                                                const int id,
1417                                                const bool force3d)
1418 {
1419   SMESHDS_Mesh * meshDS = GetMeshDS();
1420   SMDS_MeshVolume* elem = 0;
1421   if(!myCreateQuadratic) {
1422     if(id)
1423       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1424     else
1425       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1426   }
1427   else {
1428     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1429     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1430     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1431
1432     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1433     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1434     const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1435
1436     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1437     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1438     const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1439
1440     if(id)
1441       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, 
1442                                      n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1443     else
1444       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1445                                n12, n23, n31, n45, n56, n64, n14, n25, n36);
1446   }
1447   if ( mySetElemOnShape && myShapeID > 0 )
1448     meshDS->SetMeshElementOnShape( elem, myShapeID );
1449
1450   return elem;
1451 }
1452
1453 //=======================================================================
1454 //function : AddVolume
1455 //purpose  : Creates quadratic or linear tetrahedron
1456 //=======================================================================
1457
1458 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1459                                                const SMDS_MeshNode* n2,
1460                                                const SMDS_MeshNode* n3,
1461                                                const SMDS_MeshNode* n4,
1462                                                const int id, 
1463                                                const bool force3d)
1464 {
1465   SMESHDS_Mesh * meshDS = GetMeshDS();
1466   SMDS_MeshVolume* elem = 0;
1467   if(!myCreateQuadratic) {
1468     if(id)
1469       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1470     else
1471       elem = meshDS->AddVolume(n1, n2, n3, n4);
1472   }
1473   else {
1474     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1475     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1476     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1477
1478     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1479     const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1480     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1481
1482     if(id)
1483       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1484     else
1485       elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1486   }
1487   if ( mySetElemOnShape && myShapeID > 0 )
1488     meshDS->SetMeshElementOnShape( elem, myShapeID );
1489
1490   return elem;
1491 }
1492
1493 //=======================================================================
1494 //function : AddVolume
1495 //purpose  : Creates quadratic or linear pyramid
1496 //=======================================================================
1497
1498 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1499                                                const SMDS_MeshNode* n2,
1500                                                const SMDS_MeshNode* n3,
1501                                                const SMDS_MeshNode* n4,
1502                                                const SMDS_MeshNode* n5,
1503                                                const int id, 
1504                                                const bool force3d)
1505 {
1506   SMDS_MeshVolume* elem = 0;
1507   if(!myCreateQuadratic) {
1508     if(id)
1509       elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1510     else
1511       elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1512   }
1513   else {
1514     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1515     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1516     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1517     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1518
1519     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1520     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1521     const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1522     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1523
1524     if(id)
1525       elem = GetMeshDS()->AddVolumeWithID ( n1,  n2,  n3,  n4,  n5,
1526                                             n12, n23, n34, n41,
1527                                             n15, n25, n35, n45,
1528                                             id);
1529     else
1530       elem = GetMeshDS()->AddVolume( n1,  n2,  n3,  n4,  n5,
1531                                      n12, n23, n34, n41,
1532                                      n15, n25, n35, n45);
1533   }
1534   if ( mySetElemOnShape && myShapeID > 0 )
1535     GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1536
1537   return elem;
1538 }
1539
1540 //=======================================================================
1541 //function : AddVolume
1542 //purpose  : Creates quadratic or linear hexahedron
1543 //=======================================================================
1544
1545 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1546                                                const SMDS_MeshNode* n2,
1547                                                const SMDS_MeshNode* n3,
1548                                                const SMDS_MeshNode* n4,
1549                                                const SMDS_MeshNode* n5,
1550                                                const SMDS_MeshNode* n6,
1551                                                const SMDS_MeshNode* n7,
1552                                                const SMDS_MeshNode* n8,
1553                                                const int id,
1554                                                const bool force3d)
1555 {
1556   SMESHDS_Mesh * meshDS = GetMeshDS();
1557   SMDS_MeshVolume* elem = 0;
1558   if(!myCreateQuadratic) {
1559     if(id)
1560       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1561     else
1562       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1563   }
1564   else {
1565     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1566     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1567     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1568     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1569
1570     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1571     const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1572     const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1573     const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1574
1575     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1576     const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1577     const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1578     const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1579
1580     if(id)
1581       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1582                                      n12, n23, n34, n41, n56, n67,
1583                                      n78, n85, n15, n26, n37, n48, id);
1584     else
1585       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1586                                n12, n23, n34, n41, n56, n67,
1587                                n78, n85, n15, n26, n37, n48);
1588   }
1589   if ( mySetElemOnShape && myShapeID > 0 )
1590     meshDS->SetMeshElementOnShape( elem, myShapeID );
1591
1592   return elem;
1593 }
1594
1595 //=======================================================================
1596 //function : AddVolume
1597 //purpose  : Creates LINEAR!!!!!!!!! octahedron
1598 //=======================================================================
1599
1600 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1601                                                const SMDS_MeshNode* n2,
1602                                                const SMDS_MeshNode* n3,
1603                                                const SMDS_MeshNode* n4,
1604                                                const SMDS_MeshNode* n5,
1605                                                const SMDS_MeshNode* n6,
1606                                                const SMDS_MeshNode* n7,
1607                                                const SMDS_MeshNode* n8,
1608                                                const SMDS_MeshNode* n9,
1609                                                const SMDS_MeshNode* n10,
1610                                                const SMDS_MeshNode* n11,
1611                                                const SMDS_MeshNode* n12,
1612                                                const int id, 
1613                                                bool force3d)
1614 {
1615   SMESHDS_Mesh * meshDS = GetMeshDS();
1616   SMDS_MeshVolume* elem = 0;
1617   if(id)
1618     elem = meshDS->AddVolumeWithID(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,id);
1619   else
1620     elem = meshDS->AddVolume(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12);
1621   if ( mySetElemOnShape && myShapeID > 0 )
1622     meshDS->SetMeshElementOnShape( elem, myShapeID );
1623   return elem;
1624 }
1625
1626 //=======================================================================
1627 //function : AddPolyhedralVolume
1628 //purpose  : Creates polyhedron. In quadratic mesh, adds medium nodes
1629 //=======================================================================
1630
1631 SMDS_MeshVolume*
1632 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
1633                                          const std::vector<int>&                  quantities,
1634                                          const int                                id,
1635                                          const bool                               force3d)
1636 {
1637   SMESHDS_Mesh * meshDS = GetMeshDS();
1638   SMDS_MeshVolume* elem = 0;
1639   if(!myCreateQuadratic)
1640   {
1641     if(id)
1642       elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
1643     else
1644       elem = meshDS->AddPolyhedralVolume(nodes, quantities);
1645   }
1646   else
1647   {
1648     vector<const SMDS_MeshNode*> newNodes;
1649     vector<int> newQuantities;
1650     for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
1651     {
1652       int nbNodesInFace = quantities[iFace];
1653       newQuantities.push_back(0);
1654       for ( int i = 0; i < nbNodesInFace; ++i )
1655       {
1656         const SMDS_MeshNode* n1 = nodes[ iN + i ];
1657         newNodes.push_back( n1 );
1658         newQuantities.back()++;
1659         
1660         const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
1661 //         if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
1662 //              n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
1663         {
1664           const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1665           newNodes.push_back( n12 );
1666           newQuantities.back()++;
1667         }
1668       }
1669       iN += nbNodesInFace;
1670     }
1671     if(id)
1672       elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
1673     else
1674       elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
1675   }
1676   if ( mySetElemOnShape && myShapeID > 0 )
1677     meshDS->SetMeshElementOnShape( elem, myShapeID );
1678
1679   return elem;
1680 }
1681
1682 namespace
1683 {
1684   //================================================================================
1685   /*!
1686    * \brief Check if a node belongs to any face of sub-mesh
1687    */
1688   //================================================================================
1689
1690   bool isNodeInSubMesh( const SMDS_MeshNode* n, const SMESHDS_SubMesh* sm )
1691   {
1692     SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
1693     while ( fIt->more() )
1694       if ( sm->Contains( fIt->next() ))
1695         return true;
1696     return false;
1697   }
1698 }
1699
1700 //=======================================================================
1701 //function : LoadNodeColumns
1702 //purpose  : Load nodes bound to face into a map of node columns
1703 //=======================================================================
1704
1705 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1706                                          const TopoDS_Face& theFace,
1707                                          const TopoDS_Edge& theBaseEdge,
1708                                          SMESHDS_Mesh*      theMesh,
1709                                          SMESH_ProxyMesh*   theProxyMesh)
1710 {
1711   return LoadNodeColumns(theParam2ColumnMap,
1712                          theFace,
1713                          std::list<TopoDS_Edge>(1,theBaseEdge),
1714                          theMesh,
1715                          theProxyMesh);
1716 }
1717
1718 //=======================================================================
1719 //function : LoadNodeColumns
1720 //purpose  : Load nodes bound to face into a map of node columns
1721 //=======================================================================
1722
1723 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap &            theParam2ColumnMap,
1724                                          const TopoDS_Face&            theFace,
1725                                          const std::list<TopoDS_Edge>& theBaseSide,
1726                                          SMESHDS_Mesh*                 theMesh,
1727                                          SMESH_ProxyMesh*              theProxyMesh)
1728 {
1729   // get a right submesh of theFace
1730
1731   const SMESHDS_SubMesh* faceSubMesh = 0;
1732   if ( theProxyMesh )
1733   {
1734     faceSubMesh = theProxyMesh->GetSubMesh( theFace );
1735     if ( !faceSubMesh ||
1736          faceSubMesh->NbElements() == 0 ||
1737          theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
1738     {
1739       // can use a proxy sub-mesh with not temporary elements only
1740       faceSubMesh = 0;
1741       theProxyMesh = 0;
1742     }
1743   }
1744   if ( !faceSubMesh )
1745     faceSubMesh = theMesh->MeshElements( theFace );
1746   if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1747     return false;
1748
1749   // get data of edges for normalization of params
1750
1751   vector< double > length;
1752   double fullLen = 0;
1753   list<TopoDS_Edge>::const_iterator edge;
1754   {
1755     for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
1756     {
1757       double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
1758       fullLen += len;
1759       length.push_back( len );
1760     }
1761   }
1762
1763   // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1764   edge = theBaseSide.begin();
1765   for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
1766   {
1767     map< double, const SMDS_MeshNode*> sortedBaseNodes;
1768     SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNodes);
1769     if ( sortedBaseNodes.empty() ) continue;
1770
1771     map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNodes.begin();
1772     if ( theProxyMesh ) // from sortedBaseNodes remove nodes not shared by faces of faceSubMesh
1773     {
1774       const SMDS_MeshNode* n1 = sortedBaseNodes.begin()->second;
1775       const SMDS_MeshNode* n2 = sortedBaseNodes.rbegin()->second;
1776       bool allNodesAreProxy = ( n1 != theProxyMesh->GetProxyNode( n1 ) &&
1777                                 n2 != theProxyMesh->GetProxyNode( n2 ));
1778       if ( allNodesAreProxy )
1779         for ( u_n = sortedBaseNodes.begin(); u_n != sortedBaseNodes.end(); u_n++ )
1780           u_n->second = theProxyMesh->GetProxyNode( u_n->second );
1781
1782       if ( u_n = sortedBaseNodes.begin(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1783       {
1784         while ( ++u_n != sortedBaseNodes.end() && !isNodeInSubMesh( u_n->second, faceSubMesh ));
1785         sortedBaseNodes.erase( sortedBaseNodes.begin(), u_n );
1786       }
1787       else if ( u_n = --sortedBaseNodes.end(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1788       {
1789         while ( u_n != sortedBaseNodes.begin() && !isNodeInSubMesh( (--u_n)->second, faceSubMesh ));
1790         sortedBaseNodes.erase( ++u_n, sortedBaseNodes.end() );
1791       }
1792       if ( sortedBaseNodes.empty() ) continue;
1793     }
1794
1795     double f, l;
1796     BRep_Tool::Range( *edge, f, l );
1797     if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
1798     const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
1799     const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
1800     for ( u_n = sortedBaseNodes.begin(); u_n != sortedBaseNodes.end(); u_n++ )
1801     {
1802       double par = prevPar + coeff * ( u_n->first - f );
1803       TParam2ColumnMap::iterator u2nn =
1804         theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
1805       u2nn->second.push_back( u_n->second );
1806     }
1807   }
1808   if ( theParam2ColumnMap.empty() )
1809     return false;
1810
1811
1812   int nbRows = 1 + faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 );
1813
1814   // fill theParam2ColumnMap column by column by passing from nodes on
1815   // theBaseEdge up via mesh faces on theFace
1816
1817   TParam2ColumnMap::iterator par_nVec_1, par_nVec_2;
1818   par_nVec_2 = theParam2ColumnMap.begin();
1819   par_nVec_1 = par_nVec_2++;
1820   TIDSortedElemSet emptySet, avoidSet;
1821   for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1822   {
1823     vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1824     vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1825     nCol1.resize( nbRows );
1826     nCol2.resize( nbRows );
1827
1828     int i1, i2, iRow = 0;
1829     const SMDS_MeshNode *n1 = nCol1[0], *n2 = nCol2[0];
1830     // find face sharing node n1 and n2 and belonging to faceSubMesh
1831     while ( const SMDS_MeshElement* face =
1832             SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1833     {
1834       if ( faceSubMesh->Contains( face ))
1835       {
1836         int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
1837         if ( nbNodes != 4 )
1838           return false;
1839         n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1840         n2 = face->GetNode( (i1+2) % 4 );
1841         if ( ++iRow >= nbRows )
1842           return false;
1843         nCol1[ iRow ] = n1;
1844         nCol2[ iRow ] = n2;
1845         avoidSet.clear();
1846       }
1847       avoidSet.insert( face );
1848     }
1849     // set a real height
1850     nCol1.resize( iRow + 1 );
1851     nCol2.resize( iRow + 1 );
1852   }
1853   return theParam2ColumnMap.size() > 1 && theParam2ColumnMap.begin()->second.size() > 1;
1854 }
1855
1856 //=======================================================================
1857 //function : NbAncestors
1858 //purpose  : Return number of unique ancestors of the shape
1859 //=======================================================================
1860
1861 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1862                                     const SMESH_Mesh&   mesh,
1863                                     TopAbs_ShapeEnum    ancestorType/*=TopAbs_SHAPE*/)
1864 {
1865   TopTools_MapOfShape ancestors;
1866   TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1867   for ( ; ansIt.More(); ansIt.Next() ) {
1868     if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1869       ancestors.Add( ansIt.Value() );
1870   }
1871   return ancestors.Extent();
1872 }
1873
1874 //=======================================================================
1875 //function : GetSubShapeOri
1876 //purpose  : Return orientation of sub-shape in the main shape
1877 //=======================================================================
1878
1879 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
1880                                                       const TopoDS_Shape& subShape)
1881 {
1882   TopAbs_Orientation ori = TopAbs_Orientation(-1);
1883   if ( !shape.IsNull() && !subShape.IsNull() )
1884   {
1885     TopExp_Explorer e( shape, subShape.ShapeType() );
1886     if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
1887       e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
1888     for ( ; e.More(); e.Next())
1889       if ( subShape.IsSame( e.Current() ))
1890         break;
1891     if ( e.More() )
1892       ori = e.Current().Orientation();
1893   }
1894   return ori;
1895 }
1896
1897 //=======================================================================
1898 //function : IsSubShape
1899 //purpose  : 
1900 //=======================================================================
1901
1902 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
1903                                      const TopoDS_Shape& mainShape )
1904 {
1905   if ( !shape.IsNull() && !mainShape.IsNull() )
1906   {
1907     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1908           exp.More();
1909           exp.Next() )
1910       if ( shape.IsSame( exp.Current() ))
1911         return true;
1912   }
1913   SCRUTE((shape.IsNull()));
1914   SCRUTE((mainShape.IsNull()));
1915   return false;
1916 }
1917
1918 //=======================================================================
1919 //function : IsSubShape
1920 //purpose  : 
1921 //=======================================================================
1922
1923 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
1924 {
1925   if ( shape.IsNull() || !aMesh )
1926     return false;
1927   return
1928     aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1929     // PAL16202
1930     (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
1931 }
1932
1933 //================================================================================
1934 /*!
1935  * \brief Return maximal tolerance of shape
1936  */
1937 //================================================================================
1938
1939 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
1940 {
1941   double tol = Precision::Confusion();
1942   TopExp_Explorer exp;
1943   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
1944     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
1945   for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
1946     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
1947   for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
1948     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
1949
1950   return tol;
1951 }
1952
1953 //================================================================================
1954 /*!
1955  * \brief Check if the first and last vertices of an edge are the same
1956  * \param anEdge - the edge to check
1957  * \retval bool - true if same
1958  */
1959 //================================================================================
1960
1961 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
1962 {
1963   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
1964     return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
1965   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1966 }
1967
1968 //================================================================================
1969 /*!
1970  * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
1971  *  in the case of INTERNAL edge
1972  */
1973 //================================================================================
1974
1975 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool  is2nd,
1976                                              TopoDS_Edge anEdge,
1977                                              const bool  CumOri )
1978 {
1979   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
1980     anEdge.Orientation( TopAbs_FORWARD );
1981
1982   const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
1983   TopoDS_Iterator vIt( anEdge, CumOri );
1984   while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
1985     vIt.Next();
1986
1987   return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
1988 }
1989
1990 //================================================================================
1991 /*!
1992  * \brief Return type of shape contained in a group 
1993  *  \param group - a shape of type TopAbs_COMPOUND
1994  *  \param avoidCompound - not to return TopAbs_COMPOUND
1995  */
1996 //================================================================================
1997
1998 TopAbs_ShapeEnum SMESH_MesherHelper::GetGroupType(const TopoDS_Shape& group,
1999                                                   const bool          avoidCompound)
2000 {
2001   if ( !group.IsNull() )
2002   {
2003     if ( group.ShapeType() != TopAbs_COMPOUND )
2004       return group.ShapeType();
2005
2006     // iterate on a compound
2007     TopoDS_Iterator it( group );
2008     if ( it.More() )
2009       return avoidCompound ? GetGroupType( it.Value() ) : it.Value().ShapeType();
2010   }
2011   return TopAbs_SHAPE;
2012 }
2013
2014 //=======================================================================
2015 //function : IsQuadraticMesh
2016 //purpose  : Check mesh without geometry for: if all elements on this shape are quadratic,
2017 //           quadratic elements will be created.
2018 //           Used then generated 3D mesh without geometry.
2019 //=======================================================================
2020
2021 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
2022 {
2023   int NbAllEdgsAndFaces=0;
2024   int NbQuadFacesAndEdgs=0;
2025   int NbFacesAndEdges=0;
2026   //All faces and edges
2027   NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
2028   if ( NbAllEdgsAndFaces == 0 )
2029     return SMESH_MesherHelper::LINEAR;
2030   
2031   //Quadratic faces and edges
2032   NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
2033
2034   //Linear faces and edges
2035   NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
2036   
2037   if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
2038     //Quadratic mesh
2039     return SMESH_MesherHelper::QUADRATIC;
2040   }
2041   else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
2042     //Linear mesh
2043     return SMESH_MesherHelper::LINEAR;
2044   }
2045   else
2046     //Mesh with both type of elements
2047     return SMESH_MesherHelper::COMP;
2048 }
2049
2050 //=======================================================================
2051 //function : GetOtherParam
2052 //purpose  : Return an alternative parameter for a node on seam
2053 //=======================================================================
2054
2055 double SMESH_MesherHelper::GetOtherParam(const double param) const
2056 {
2057   int i = myParIndex & U_periodic ? 0 : 1;
2058   return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
2059 }
2060
2061 namespace {
2062
2063   //=======================================================================
2064   /*!
2065    * \brief Iterator on ancestors of the given type
2066    */
2067   //=======================================================================
2068
2069   struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
2070   {
2071     TopTools_ListIteratorOfListOfShape _ancIter;
2072     TopAbs_ShapeEnum                   _type;
2073     TopTools_MapOfShape                _encountered;
2074     TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
2075       : _ancIter( ancestors ), _type( type )
2076     {
2077       if ( _ancIter.More() ) {
2078         if ( _ancIter.Value().ShapeType() != _type ) next();
2079         else _encountered.Add( _ancIter.Value() );
2080       }
2081     }
2082     virtual bool more()
2083     {
2084       return _ancIter.More();
2085     }
2086     virtual const TopoDS_Shape* next()
2087     {
2088       const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
2089       if ( _ancIter.More() )
2090         for ( _ancIter.Next();  _ancIter.More(); _ancIter.Next())
2091           if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
2092             break;
2093       return s;
2094     }
2095   };
2096
2097 } // namespace
2098
2099 //=======================================================================
2100 /*!
2101  * \brief Return iterator on ancestors of the given type
2102  */
2103 //=======================================================================
2104
2105 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
2106                                                    const SMESH_Mesh&   mesh,
2107                                                    TopAbs_ShapeEnum    ancestorType)
2108 {
2109   return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
2110 }
2111
2112 //=======================================================================
2113 //function : GetCommonAncestor
2114 //purpose  : Find a common ancestors of two shapes of the given type
2115 //=======================================================================
2116
2117 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
2118                                                    const TopoDS_Shape& shape2,
2119                                                    const SMESH_Mesh&   mesh,
2120                                                    TopAbs_ShapeEnum    ancestorType)
2121 {
2122   TopoDS_Shape commonAnc;
2123   if ( !shape1.IsNull() && !shape2.IsNull() )
2124   {
2125     PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
2126     while ( const TopoDS_Shape* anc = ancIt->next() )
2127       if ( IsSubShape( shape2, *anc ))
2128       {
2129         commonAnc = *anc;
2130         break;
2131       }
2132   }
2133   return commonAnc;
2134 }
2135
2136 //#include <Perf_Meter.hxx>
2137
2138 //=======================================================================
2139 namespace { // Structures used by FixQuadraticElements()
2140 //=======================================================================
2141
2142 #define __DMP__(txt) \
2143   //cout << txt
2144 #define MSG(txt) __DMP__(txt<<endl)
2145 #define MSGBEG(txt) __DMP__(txt)
2146
2147   //const double straightTol2 = 1e-33; // to detect straing links
2148   bool isStraightLink(double linkLen2, double middleNodeMove2)
2149   {
2150     // straight if <node move> < 1/15 * <link length>
2151     return middleNodeMove2 < 1/15./15. * linkLen2;
2152   }
2153
2154   struct QFace;
2155   // ---------------------------------------
2156   /*!
2157    * \brief Quadratic link knowing its faces
2158    */
2159   struct QLink: public SMESH_TLink
2160   {
2161     const SMDS_MeshNode*          _mediumNode;
2162     mutable vector<const QFace* > _faces;
2163     mutable gp_Vec                _nodeMove;
2164     mutable int                   _nbMoves;
2165
2166     QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
2167       SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
2168       _faces.reserve(4);
2169       //if ( MediumPos() != SMDS_TOP_3DSPACE )
2170         _nodeMove = MediumPnt() - MiddlePnt();
2171     }
2172     void SetContinuesFaces() const;
2173     const QFace* GetContinuesFace( const QFace* face ) const;
2174     bool OnBoundary() const;
2175     gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
2176     gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
2177
2178     SMDS_TypeOfPosition MediumPos() const
2179     { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
2180     SMDS_TypeOfPosition EndPos(bool isSecond) const
2181     { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
2182     const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
2183     { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
2184
2185     void Move(const gp_Vec& move, bool sum=false) const
2186     { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
2187     gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
2188     bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
2189     bool IsStraight() const
2190     { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
2191                              _nodeMove.SquareMagnitude());
2192     }
2193     bool operator<(const QLink& other) const {
2194       return (node1()->GetID() == other.node1()->GetID() ?
2195               node2()->GetID() < other.node2()->GetID() :
2196               node1()->GetID() < other.node1()->GetID());
2197     }
2198 //     struct PtrComparator {
2199 //       bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
2200 //     };
2201   };
2202   // ---------------------------------------------------------
2203   /*!
2204    * \brief Link in the chain of links; it connects two faces
2205    */
2206   struct TChainLink
2207   {
2208     const QLink*         _qlink;
2209     mutable const QFace* _qfaces[2];
2210
2211     TChainLink(const QLink* qlink=0):_qlink(qlink) {
2212       _qfaces[0] = _qfaces[1] = 0;
2213     }
2214     void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
2215
2216     bool IsBoundary() const { return !_qfaces[1]; }
2217
2218     void RemoveFace( const QFace* face ) const
2219     { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
2220
2221     const QFace* NextFace( const QFace* f ) const
2222     { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
2223
2224     const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
2225     { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
2226
2227     bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
2228
2229     operator bool() const { return (_qlink); }
2230
2231     const QLink* operator->() const { return _qlink; }
2232
2233     gp_Vec Normal() const;
2234
2235     bool IsStraight() const;
2236   };
2237   // --------------------------------------------------------------------
2238   typedef list< TChainLink > TChain;
2239   typedef set < TChainLink > TLinkSet;
2240   typedef TLinkSet::const_iterator TLinkInSet;
2241
2242   const int theFirstStep = 5;
2243
2244   enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
2245   // --------------------------------------------------------------------
2246   /*!
2247    * \brief Face shared by two volumes and bound by QLinks
2248    */
2249   struct QFace: public TIDSortedNodeSet
2250   {
2251     mutable const SMDS_MeshElement* _volumes[2];
2252     mutable vector< const QLink* >  _sides;
2253     mutable bool                    _sideIsAdded[4]; // added in chain of links
2254     gp_Vec                          _normal;
2255 #ifdef _DEBUG_
2256     mutable const SMDS_MeshElement* _face;
2257 #endif
2258
2259     QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
2260
2261     void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
2262
2263     int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
2264
2265     void AddSelfToLinks() const {
2266       for ( int i = 0; i < _sides.size(); ++i )
2267         _sides[i]->_faces.push_back( this );
2268     }
2269     int LinkIndex( const QLink* side ) const {
2270       for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
2271       return -1;
2272     }
2273     bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
2274
2275     bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
2276     {
2277       int i = LinkIndex( link._qlink );
2278       if ( i < 0 ) return true;
2279       _sideIsAdded[i] = true;
2280       link.SetFace( this );
2281       // continue from opposite link
2282       return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
2283     }
2284     bool IsBoundary() const { return !_volumes[1]; }
2285
2286     bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
2287
2288     bool IsSpoiled(const QLink* bentLink ) const;
2289
2290     TLinkInSet GetBoundaryLink( const TLinkSet&      links,
2291                                 const TChainLink&    avoidLink,
2292                                 TLinkInSet *         notBoundaryLink = 0,
2293                                 const SMDS_MeshNode* nodeToContain = 0,
2294                                 bool *               isAdjacentUsed = 0,
2295                                 int                  nbRecursionsLeft = -1) const;
2296
2297     TLinkInSet GetLinkByNode( const TLinkSet&      links,
2298                               const TChainLink&    avoidLink,
2299                               const SMDS_MeshNode* nodeToContain) const;
2300
2301     const SMDS_MeshNode* GetNodeInFace() const {
2302       for ( int iL = 0; iL < _sides.size(); ++iL )
2303         if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
2304       return 0;
2305     }
2306
2307     gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
2308
2309     double MoveByBoundary( const TChainLink&   theLink,
2310                            const gp_Vec&       theRefVec,
2311                            const TLinkSet&     theLinks,
2312                            SMESH_MesherHelper* theFaceHelper=0,
2313                            const double        thePrevLen=0,
2314                            const int           theStep=theFirstStep,
2315                            gp_Vec*             theLinkNorm=0,
2316                            double              theSign=1.0) const;
2317   };
2318
2319   //================================================================================
2320   /*!
2321    * \brief Dump QLink and QFace
2322    */
2323   ostream& operator << (ostream& out, const QLink& l)
2324   {
2325     out <<"QLink nodes: "
2326         << l.node1()->GetID() << " - "
2327         << l._mediumNode->GetID() << " - "
2328         << l.node2()->GetID() << endl;
2329     return out;
2330   }
2331   ostream& operator << (ostream& out, const QFace& f)
2332   {
2333     out <<"QFace nodes: "/*<< &f << "  "*/;
2334     for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
2335       out << (*n)->GetID() << " ";
2336     out << " \tvolumes: "
2337         << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
2338         << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
2339     out << "  \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
2340     return out;
2341   }
2342
2343   //================================================================================
2344   /*!
2345    * \brief Construct QFace from QLinks 
2346    */
2347   //================================================================================
2348
2349   QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
2350   {
2351     _volumes[0] = _volumes[1] = 0;
2352     _sides = links;
2353     _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
2354     _normal.SetCoord(0,0,0);
2355     for ( int i = 1; i < _sides.size(); ++i ) {
2356       const QLink *l1 = _sides[i-1], *l2 = _sides[i];
2357       insert( l1->node1() ); insert( l1->node2() );
2358       // compute normal
2359       gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
2360       gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
2361       if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
2362         v1.Reverse(); 
2363       _normal += v1 ^ v2;
2364     }
2365     double normSqSize = _normal.SquareMagnitude();
2366     if ( normSqSize > numeric_limits<double>::min() )
2367       _normal /= sqrt( normSqSize );
2368     else
2369       _normal.SetCoord(1e-33,0,0);
2370
2371 #ifdef _DEBUG_
2372     _face = face;
2373 #endif
2374   }
2375   //================================================================================
2376   /*!
2377    * \brief Make up a chain of links
2378    *  \param iSide - link to add first
2379    *  \param chain - chain to fill in
2380    *  \param pos   - postion of medium nodes the links should have
2381    *  \param error - out, specifies what is wrong
2382    *  \retval bool - false if valid chain can't be built; "valid" means that links
2383    *                 of the chain belongs to rectangles bounding hexahedrons
2384    */
2385   //================================================================================
2386
2387   bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
2388   {
2389     if ( iSide >= _sides.size() ) // wrong argument iSide
2390       return false;
2391     if ( _sideIsAdded[ iSide ]) // already in chain
2392       return true;
2393
2394     if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
2395       MSGBEG( *this );
2396       TLinkSet links;
2397       list< const QFace* > faces( 1, this );
2398       while ( !faces.empty() ) {
2399         const QFace* face = faces.front();
2400         for ( int i = 0; i < face->_sides.size(); ++i ) {
2401           if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
2402             face->_sideIsAdded[i] = true;
2403             // find a face side in the chain
2404             TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
2405 //             TChain::iterator chLink = chain.begin();
2406 //             for ( ; chLink != chain.end(); ++chLink )
2407 //               if ( chLink->_qlink == face->_sides[i] )
2408 //                 break;
2409 //             if ( chLink == chain.end() )
2410 //               chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
2411             // add a face to a chained link and put a continues face in the queue
2412             chLink->SetFace( face );
2413             if ( face->_sides[i]->MediumPos() == pos )
2414               if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
2415                 if ( contFace->_sides.size() == 3 )
2416                   faces.push_back( contFace );
2417           }
2418         }
2419         faces.pop_front();
2420       }
2421       if ( error < ERR_TRI )
2422         error = ERR_TRI;
2423       chain.insert( chain.end(), links.begin(),links.end() );
2424       return false;
2425     }
2426     _sideIsAdded[iSide] = true; // not to add this link to chain again
2427     const QLink* link = _sides[iSide];
2428     if ( !link)
2429       return true;
2430
2431     // add link into chain
2432     TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
2433     chLink->SetFace( this );
2434     MSGBEG( *this );
2435
2436     // propagate from quadrangle to neighbour faces
2437     if ( link->MediumPos() >= pos ) {
2438       int nbLinkFaces = link->_faces.size();
2439       if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
2440         // hexahedral mesh or boundary quadrangles - goto a continous face
2441         if ( const QFace* f = link->GetContinuesFace( this ))
2442           if ( f->_sides.size() == 4 )
2443             return f->GetLinkChain( *chLink, chain, pos, error );
2444       }
2445       else {
2446         TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
2447         for ( int i = 0; i < nbLinkFaces; ++i )
2448           if ( link->_faces[i] )
2449             link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
2450         if ( error < ERR_PRISM )
2451           error = ERR_PRISM;
2452         return false;
2453       }
2454     }
2455     return true;
2456   }
2457
2458   //================================================================================
2459   /*!
2460    * \brief Return a boundary link of the triangle face
2461    *  \param links - set of all links
2462    *  \param avoidLink - link not to return
2463    *  \param notBoundaryLink - out, neither the returned link nor avoidLink
2464    *  \param nodeToContain - node the returned link must contain; if provided, search
2465    *                         also performed on adjacent faces
2466    *  \param isAdjacentUsed - returns true if link is found in adjacent faces
2467    *  \param nbRecursionsLeft - to limit recursion
2468    */
2469   //================================================================================
2470
2471   TLinkInSet QFace::GetBoundaryLink( const TLinkSet&      links,
2472                                      const TChainLink&    avoidLink,
2473                                      TLinkInSet *         notBoundaryLink,
2474                                      const SMDS_MeshNode* nodeToContain,
2475                                      bool *               isAdjacentUsed,
2476                                      int                  nbRecursionsLeft) const
2477   {
2478     TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
2479
2480     typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
2481     TFaceLinkList adjacentFaces;
2482
2483     for ( int iL = 0; iL < _sides.size(); ++iL )
2484     {
2485       if ( avoidLink._qlink == _sides[iL] )
2486         continue;
2487       TLinkInSet link = links.find( _sides[iL] );
2488       if ( link == linksEnd ) continue;
2489       if ( (*link)->MediumPos() > SMDS_TOP_FACE )
2490         continue; // We work on faces here, don't go inside a solid
2491
2492       // check link
2493       if ( link->IsBoundary() ) {
2494         if ( !nodeToContain ||
2495              (*link)->node1() == nodeToContain ||
2496              (*link)->node2() == nodeToContain )
2497         {
2498           boundaryLink = link;
2499           if ( !notBoundaryLink ) break;
2500         }
2501       }
2502       else if ( notBoundaryLink ) {
2503         *notBoundaryLink = link;
2504         if ( boundaryLink != linksEnd ) break;
2505       }
2506
2507       if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
2508         if ( const QFace* adj = link->NextFace( this ))
2509           if ( adj->Contains( nodeToContain ))
2510             adjacentFaces.push_back( make_pair( adj, link ));
2511     }
2512
2513     if ( isAdjacentUsed ) *isAdjacentUsed = false;
2514     if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
2515     {
2516       if ( nbRecursionsLeft < 0 )
2517         nbRecursionsLeft = nodeToContain->NbInverseElements();
2518       TFaceLinkList::iterator adj = adjacentFaces.begin();
2519       for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
2520         boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
2521                                                     isAdjacentUsed, nbRecursionsLeft-1);
2522       if ( isAdjacentUsed ) *isAdjacentUsed = true;
2523     }
2524     return boundaryLink;
2525   }
2526   //================================================================================
2527   /*!
2528    * \brief Return a link ending at the given node but not avoidLink
2529    */
2530   //================================================================================
2531
2532   TLinkInSet QFace::GetLinkByNode( const TLinkSet&      links,
2533                                    const TChainLink&    avoidLink,
2534                                    const SMDS_MeshNode* nodeToContain) const
2535   {
2536     for ( int i = 0; i < _sides.size(); ++i )
2537       if ( avoidLink._qlink != _sides[i] &&
2538            (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
2539         return links.find( _sides[ i ]);
2540     return links.end();
2541   }
2542
2543   //================================================================================
2544   /*!
2545    * \brief Return normal to the i-th side pointing outside the face
2546    */
2547   //================================================================================
2548
2549   gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
2550   {
2551     gp_Vec norm, vecOut;
2552 //     if ( uvHelper ) {
2553 //       TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
2554 //       const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
2555 //       gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
2556 //       gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
2557 //       norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
2558
2559 //       const QLink* otherLink = _sides[(i + 1) % _sides.size()];
2560 //       const SMDS_MeshNode* otherNode =
2561 //         otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
2562 //       gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
2563 //       vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
2564 //     }
2565 //     else {
2566       norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2567       gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
2568                      XYZ( _sides[0]->node2() ) +
2569                      XYZ( _sides[1]->node1() )) / 3.;
2570       vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
2571       //}
2572     if ( norm * vecOut < 0 )
2573       norm.Reverse();
2574     double mag2 = norm.SquareMagnitude();
2575     if ( mag2 > numeric_limits<double>::min() )
2576       norm /= sqrt( mag2 );
2577     return norm;
2578   }
2579   //================================================================================
2580   /*!
2581    * \brief Move medium node of theLink according to its distance from boundary
2582    *  \param theLink - link to fix
2583    *  \param theRefVec - movement of boundary
2584    *  \param theLinks - all adjacent links of continous triangles
2585    *  \param theFaceHelper - helper is not used so far
2586    *  \param thePrevLen - distance from the boundary
2587    *  \param theStep - number of steps till movement propagation limit
2588    *  \param theLinkNorm - out normal to theLink
2589    *  \param theSign - 1 or -1 depending on movement of boundary
2590    *  \retval double - distance from boundary to propagation limit or other boundary
2591    */
2592   //================================================================================
2593
2594   double QFace::MoveByBoundary( const TChainLink&   theLink,
2595                                 const gp_Vec&       theRefVec,
2596                                 const TLinkSet&     theLinks,
2597                                 SMESH_MesherHelper* theFaceHelper,
2598                                 const double        thePrevLen,
2599                                 const int           theStep,
2600                                 gp_Vec*             theLinkNorm,
2601                                 double              theSign) const
2602   {
2603     if ( !theStep )
2604       return thePrevLen; // propagation limit reached
2605
2606     int iL; // index of theLink
2607     for ( iL = 0; iL < _sides.size(); ++iL )
2608       if ( theLink._qlink == _sides[ iL ])
2609         break;
2610
2611     MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
2612         <<" thePrevLen " << thePrevLen);
2613     MSG(string(theStep,'.')<<" "<<*theLink._qlink);
2614
2615     gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
2616     double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
2617     if ( theStep == theFirstStep )
2618       theSign = refProj < 0. ? -1. : 1.;
2619     else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
2620       return thePrevLen; // to propagate movement forward only, not in side dir or backward
2621
2622     int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
2623     TLinkInSet link1 = theLinks.find( _sides[iL1] );
2624     TLinkInSet link2 = theLinks.find( _sides[iL2] );
2625     if ( link1 == theLinks.end() || link2 == theLinks.end() )
2626       return thePrevLen;
2627     const QFace* f1 = link1->NextFace( this ); // adjacent faces
2628     const QFace* f2 = link2->NextFace( this );
2629
2630     // propagate to adjacent faces till limit step or boundary
2631     double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2632     double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2633     gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
2634     gp_Vec linkDir2(0,0,0);
2635     try {
2636       OCC_CATCH_SIGNALS;
2637       if ( f1 && theLink->MediumPos() <= (*link1)->MediumPos() )
2638         len1 = f1->MoveByBoundary
2639           ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2640       else
2641         linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2642     } catch (...) {
2643       MSG( " --------------- EXCEPTION");
2644       return thePrevLen;
2645     }
2646     try {
2647       OCC_CATCH_SIGNALS;
2648       if ( f2 && theLink->MediumPos() <= (*link2)->MediumPos() )
2649         len2 = f2->MoveByBoundary
2650           ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2651       else
2652         linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2653     } catch (...) {
2654       MSG( " --------------- EXCEPTION");
2655       return thePrevLen;
2656     }
2657
2658     double fullLen = 0;
2659     if ( theStep != theFirstStep )
2660     {
2661       // choose chain length by direction of propagation most codirected with theRefVec
2662       bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2663       fullLen = choose1 ? len1 : len2;
2664       double r = thePrevLen / fullLen;
2665
2666       gp_Vec move = linkNorm * refProj * ( 1 - r );
2667       theLink->Move( move, true );
2668
2669       MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2670           " by " << refProj * ( 1 - r ) << " following " <<
2671           (choose1 ? *link1->_qlink : *link2->_qlink));
2672
2673       if ( theLinkNorm ) *theLinkNorm = linkNorm;
2674     }
2675     return fullLen;
2676   }
2677
2678   //================================================================================
2679   /*!
2680    * \brief Checks if the face is distorted due to bentLink
2681    */
2682   //================================================================================
2683
2684   bool QFace::IsSpoiled(const QLink* bentLink ) const
2685   {
2686     // code is valid for convex faces only
2687     gp_XYZ gc(0,0,0);
2688     for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
2689       gc += XYZ( *n ) / size();
2690     for (unsigned i = 0; i < _sides.size(); ++i )
2691     {
2692       if ( _sides[i] == bentLink ) continue;
2693       gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2694       gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
2695       if ( linkNorm * vecOut < 0 )
2696         linkNorm.Reverse();
2697       double mag2 = linkNorm.SquareMagnitude();
2698       if ( mag2 > numeric_limits<double>::min() )
2699         linkNorm /= sqrt( mag2 );
2700       gp_Vec vecBent    ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
2701       gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
2702       if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
2703         return true;
2704     }
2705     return false;
2706     
2707   }
2708
2709   //================================================================================
2710   /*!
2711    * \brief Find pairs of continues faces 
2712    */
2713   //================================================================================
2714
2715   void QLink::SetContinuesFaces() const
2716   {
2717     //       x0         x - QLink, [-|] - QFace, v - volume
2718     //   v0  |   v1   
2719     //       |          Between _faces of link x2 two vertical faces are continues
2720     // x1----x2-----x3  and two horizontal faces are continues. We set vertical faces
2721     //       |          to _faces[0] and _faces[1] and horizontal faces to
2722     //   v2  |   v3     _faces[2] and _faces[3] (or vise versa).
2723     //       x4
2724
2725     if ( _faces.empty() )
2726       return;
2727     int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
2728     if ( _faces[0]->IsBoundary() )
2729       iBoundary[ nbBoundary++ ] = 0;
2730     for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2731     {
2732       // look for a face bounding none of volumes bound by _faces[0]
2733       bool sameVol = false;
2734       int nbVol = _faces[iF]->NbVolumes();
2735       for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2736         sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2737                     _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2738       if ( !sameVol )
2739         iFaceCont = iF;
2740       if ( _faces[iF]->IsBoundary() )
2741         iBoundary[ nbBoundary++ ] = iF;
2742     }
2743     // Set continues faces: arrange _faces to have
2744     // _faces[0] continues to _faces[1]
2745     // _faces[2] continues to _faces[3]
2746     if ( nbBoundary == 2 ) // bnd faces are continues
2747     {
2748       if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
2749       {
2750         int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
2751         std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
2752       }
2753     }
2754     else if ( iFaceCont > 0 ) // continues faces found
2755     {
2756       if ( iFaceCont != 1 )
2757         std::swap( _faces[1], _faces[iFaceCont] );
2758     }
2759     else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2760     {
2761       _faces.insert( ++_faces.begin(), 0 );
2762     }
2763   }
2764   //================================================================================
2765   /*!
2766    * \brief Return a face continues to the given one
2767    */
2768   //================================================================================
2769
2770   const QFace* QLink::GetContinuesFace( const QFace* face ) const
2771   {
2772     for ( int i = 0; i < _faces.size(); ++i ) {
2773       if ( _faces[i] == face ) {
2774         int iF = i < 2 ? 1-i : 5-i;
2775         return iF < _faces.size() ? _faces[iF] : 0;
2776       }
2777     }
2778     return 0;
2779   }
2780   //================================================================================
2781   /*!
2782    * \brief True if link is on mesh boundary
2783    */
2784   //================================================================================
2785
2786   bool QLink::OnBoundary() const
2787   {
2788     for ( int i = 0; i < _faces.size(); ++i )
2789       if (_faces[i] && _faces[i]->IsBoundary()) return true;
2790     return false;
2791   }
2792   //================================================================================
2793   /*!
2794    * \brief Return normal of link of the chain
2795    */
2796   //================================================================================
2797
2798   gp_Vec TChainLink::Normal() const {
2799     gp_Vec norm;
2800     if (_qfaces[0]) norm  = _qfaces[0]->_normal;
2801     if (_qfaces[1]) norm += _qfaces[1]->_normal;
2802     return norm;
2803   }
2804   //================================================================================
2805   /*!
2806    * \brief Test link curvature taking into account size of faces
2807    */
2808   //================================================================================
2809
2810   bool TChainLink::IsStraight() const
2811   {
2812     bool isStraight = _qlink->IsStraight();
2813     if ( isStraight && _qfaces[0] && !_qfaces[1] )
2814     {
2815       int i = _qfaces[0]->LinkIndex( _qlink );
2816       int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
2817       gp_XYZ mid1 = _qlink->MiddlePnt();
2818       gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
2819       double faceSize2 = (mid1-mid2).SquareModulus();
2820       isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
2821     }
2822     return isStraight;
2823   }
2824   
2825   //================================================================================
2826   /*!
2827    * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
2828    */
2829   //================================================================================
2830
2831   void fixPrism( TChain& allLinks )
2832   {
2833     // separate boundary links from internal ones
2834     typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
2835     QLinkSet interLinks, bndLinks1, bndLink2;
2836
2837     bool isCurved = false;
2838     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2839       if ( (*lnk)->OnBoundary() )
2840         bndLinks1.insert( lnk->_qlink );
2841       else
2842         interLinks.insert( lnk->_qlink );
2843       isCurved = isCurved || !lnk->IsStraight();
2844     }
2845     if ( !isCurved )
2846       return; // no need to move
2847
2848     QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
2849
2850     while ( !interLinks.empty() && !curBndLinks->empty() )
2851     {
2852       // propagate movement from boundary links to connected internal links
2853       QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
2854       for ( ; bnd != bndEnd; ++bnd )
2855       {
2856         const QLink* bndLink = *bnd;
2857         for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
2858         {
2859           const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
2860           if ( !face ) continue;
2861           // find and move internal link opposite to bndLink within the face
2862           int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
2863           const QLink* interLink = face->_sides[ interInd ];
2864           QLinkSet::iterator pInterLink = interLinks.find( interLink );
2865           if ( pInterLink == interLinks.end() ) continue; // not internal link
2866           interLink->Move( bndLink->_nodeMove );
2867           // treated internal links become new boundary ones
2868           interLinks. erase( pInterLink );
2869           newBndLinks->insert( interLink );
2870         }
2871       }
2872       curBndLinks->clear();
2873       std::swap( curBndLinks, newBndLinks );
2874     }
2875   }
2876
2877   //================================================================================
2878   /*!
2879    * \brief Fix links of continues triangles near curved boundary
2880    */
2881   //================================================================================
2882
2883   void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2884   {
2885     if ( allLinks.empty() ) return;
2886
2887     TLinkSet linkSet( allLinks.begin(), allLinks.end());
2888     TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2889
2890     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2891     {
2892       if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
2893       {
2894         // move iff a boundary link is bent towards inside of a face (issue 0021084)
2895         const QFace* face = linkIt->_qfaces[0];
2896         gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
2897                        face->_sides[1]->MiddlePnt() +
2898                        face->_sides[2]->MiddlePnt() ) / 3.;
2899         gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
2900         bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
2901         //if ( face->IsSpoiled( linkIt->_qlink ))
2902         if ( linkBentInside )
2903           face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2904       }
2905     }
2906   }
2907
2908   //================================================================================
2909   /*!
2910    * \brief Detect rectangular structure of links and build chains from them
2911    */
2912   //================================================================================
2913
2914   enum TSplitTriaResult {
2915     _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2916     _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
2917
2918   TSplitTriaResult splitTrianglesIntoChains( TChain &            allLinks,
2919                                              vector< TChain> &   resultChains,
2920                                              SMDS_TypeOfPosition pos )
2921   {
2922     // put links in the set and evalute number of result chains by number of boundary links
2923     TLinkSet linkSet;
2924     int nbBndLinks = 0;
2925     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2926       linkSet.insert( *lnk );
2927       nbBndLinks += lnk->IsBoundary();
2928     }
2929     resultChains.clear();
2930     resultChains.reserve( nbBndLinks / 2 );
2931
2932     TLinkInSet linkIt, linksEnd = linkSet.end();
2933
2934     // find a boundary link with corner node; corner node has position pos-2
2935     // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2936     // links in volume
2937     SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2938     const SMDS_MeshNode* corner = 0;
2939     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2940       if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2941         break;
2942     if ( !corner)
2943       return _NO_CORNERS;
2944
2945     TLinkInSet           startLink = linkIt;
2946     const SMDS_MeshNode* startCorner = corner;
2947     vector< TChain* >    rowChains;
2948     int iCol = 0;
2949
2950     while ( startLink != linksEnd) // loop on columns
2951     {
2952       // We suppose we have a rectangular structure like shown here. We have found a
2953       //               corner of the rectangle (startCorner) and a boundary link sharing  
2954       //    |/  |/  |  the startCorner (startLink). We are going to loop on rows of the   
2955       //  --o---o---o  structure making several chains at once. One chain (columnChain)   
2956       //    |\  |  /|  starts at startLink and continues upward (we look at the structure 
2957       //  \ | \ | / |  from such point that startLink is on the bottom of the structure). 
2958       //   \|  \|/  |  While going upward we also fill horizontal chains (rowChains) we   
2959       //  --o---o---o  encounter.                                                         
2960       //   /|\  |\  |
2961       //  / | \ | \ |  startCorner
2962       //    |  \|  \|,'
2963       //  --o---o---o
2964       //          `.startLink
2965
2966       if ( resultChains.size() == nbBndLinks / 2 )
2967         return _NOT_RECT;
2968       resultChains.push_back( TChain() );
2969       TChain& columnChain = resultChains.back();
2970
2971       TLinkInSet botLink = startLink; // current horizontal link to go up from
2972       corner = startCorner; // current corner the botLink ends at
2973       int iRow = 0;
2974       while ( botLink != linksEnd ) // loop on rows
2975       {
2976         // add botLink to the columnChain
2977         columnChain.push_back( *botLink );
2978
2979         const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2980         if ( !botTria )
2981         { // the column ends
2982           if ( botLink == startLink )
2983             return _TWISTED_CHAIN; // issue 0020951
2984           linkSet.erase( botLink );
2985           if ( iRow != rowChains.size() )
2986             return _FEW_ROWS; // different nb of rows in columns
2987           break;
2988         }
2989         // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2990         // link ending at <corner> (sideLink); there are two cases:
2991         // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2992         //   since midQuadLink is not at boundary while sideLink is.
2993         // 2) midQuadLink ends at <corner>
2994         bool isCase2;
2995         TLinkInSet midQuadLink = linksEnd;
2996         TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2997                                                         corner, &isCase2 );
2998         if ( isCase2 ) { // find midQuadLink among links of botTria
2999           midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
3000           if ( midQuadLink->IsBoundary() )
3001             return _BAD_MIDQUAD;
3002         }
3003         if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
3004           return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
3005
3006         // fill chains
3007         columnChain.push_back( *midQuadLink );
3008         if ( iRow >= rowChains.size() ) {
3009           if ( iCol > 0 )
3010             return _MANY_ROWS; // different nb of rows in columns
3011           if ( resultChains.size() == nbBndLinks / 2 )
3012             return _NOT_RECT;
3013           resultChains.push_back( TChain() );
3014           rowChains.push_back( & resultChains.back() );
3015         }
3016         rowChains[iRow]->push_back( *sideLink );
3017         rowChains[iRow]->push_back( *midQuadLink );
3018
3019         const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
3020         if ( !upTria)
3021           return _NO_UPTRIA;
3022         if ( iRow == 0 ) {
3023           // prepare startCorner and startLink for the next column
3024           startCorner = startLink->NextNode( startCorner );
3025           if (isCase2)
3026             startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
3027           else
3028             startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
3029           // check if no more columns remains
3030           if ( startLink != linksEnd ) {
3031             const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
3032             if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
3033               startLink = linksEnd; // startLink bounds upTria or botTria
3034             else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
3035               return _BAD_START;
3036           }
3037         }
3038         // find bottom link and corner for the next row
3039         corner = sideLink->NextNode( corner );
3040         // next bottom link ends at the new corner
3041         linkSet.erase( botLink );
3042         botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
3043         if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
3044           return _NO_BOTLINK;
3045         if ( midQuadLink == startLink || sideLink == startLink )
3046           return _TWISTED_CHAIN; // issue 0020951
3047         linkSet.erase( midQuadLink );
3048         linkSet.erase( sideLink );
3049
3050         // make faces neighboring the found ones be boundary
3051         if ( startLink != linksEnd ) {
3052           const QFace* tria = isCase2 ? botTria : upTria;
3053           for ( int iL = 0; iL < 3; ++iL ) {
3054             linkIt = linkSet.find( tria->_sides[iL] );
3055             if ( linkIt != linksEnd )
3056               linkIt->RemoveFace( tria );
3057           }
3058         }
3059         if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
3060           botLink->RemoveFace( upTria ); // make next botTria first in vector
3061
3062         iRow++;
3063       } // loop on rows
3064
3065       iCol++;
3066     }
3067     // In the linkSet, there must remain the last links of rowChains; add them
3068     if ( linkSet.size() != rowChains.size() )
3069       return _BAD_SET_SIZE;
3070     for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
3071       // find the link (startLink) ending at startCorner
3072       corner = 0;
3073       for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
3074         if ( (*startLink)->node1() == startCorner ) {
3075           corner = (*startLink)->node2(); break;
3076         }
3077         else if ( (*startLink)->node2() == startCorner) {
3078           corner = (*startLink)->node1(); break;
3079         }
3080       }
3081       if ( startLink == linksEnd )
3082         return _BAD_CORNER;
3083       rowChains[ iRow ]->push_back( *startLink );
3084       linkSet.erase( startLink );
3085       startCorner = corner;
3086     }
3087
3088     return _OK;
3089   }
3090
3091   //================================================================================
3092   /*!
3093    * \brief Place medium nodes at the link middle for elements whose corner nodes
3094    *        are out of geometrical boundary to prevent distorting elements.
3095    *        Issue 0020982, note 0013990
3096    */
3097   //================================================================================
3098
3099   void force3DOutOfBoundary( SMESH_MesherHelper&    theHelper,
3100                              SMESH_ComputeErrorPtr& theError)
3101   {
3102     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
3103     TopoDS_Shape  shape = theHelper.GetSubShape().Oriented( TopAbs_FORWARD );
3104     if ( shape.IsNull() ) return;
3105
3106     if ( !theError ) theError = SMESH_ComputeError::New();
3107
3108     gp_XYZ faceNorm;
3109
3110     if ( shape.ShapeType() == TopAbs_FACE ) // 2D
3111     {
3112       if ( theHelper.GetMesh()->NbTriangles( ORDER_QUADRATIC ) < 1 ) return;
3113
3114       SMESHDS_SubMesh* faceSM = meshDS->MeshElements( shape );
3115       if ( !faceSM ) return;
3116
3117       const TopoDS_Face&      face = TopoDS::Face( shape );
3118       Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3119
3120       TopExp_Explorer edgeIt( face, TopAbs_EDGE );
3121       for ( ; edgeIt.More(); edgeIt.Next() ) // loop on EDGEs of a FACE
3122       {
3123         // check if the EDGE needs checking
3124         const TopoDS_Edge& edge = TopoDS::Edge( edgeIt.Current() );
3125         if ( BRep_Tool::Degenerated( edge ) )
3126           continue;
3127         if ( theHelper.IsRealSeam( edge ) &&
3128              edge.Orientation() == TopAbs_REVERSED )
3129           continue;
3130
3131         SMESHDS_SubMesh* edgeSM = meshDS->MeshElements( edge );
3132         if ( !edgeSM ) continue;
3133
3134         double f,l;
3135         Handle(Geom2d_Curve) pcurve  = BRep_Tool::CurveOnSurface( edge, face, f, l );
3136         BRepAdaptor_Curve    curve3D( edge );
3137         switch ( curve3D.GetType() ) {
3138         case GeomAbs_Line: continue;
3139         case GeomAbs_Circle:
3140         case GeomAbs_Ellipse:
3141         case GeomAbs_Hyperbola:
3142         case GeomAbs_Parabola:
3143           try
3144           {
3145             gp_Vec D1, D2, Du1, Dv1; gp_Pnt p;
3146             curve3D.D2( 0.5 * ( f + l ), p, D1, D2 );
3147             gp_Pnt2d uv = pcurve->Value( 0.5 * ( f + l ) );
3148             surface->D1( uv.X(), uv.Y(), p, Du1, Dv1 );
3149             gp_Vec fNorm = Du1 ^ Dv1;
3150             if ( fNorm.IsParallel( D2, M_PI * 25./180. ))
3151               continue; // face is normal to the curve3D
3152
3153             gp_Vec curvNorm = fNorm ^ D1;
3154             if ( edge.Orientation() == TopAbs_REVERSED ) curvNorm.Reverse();
3155             if ( curvNorm * D2 > 0 )
3156               continue; // convex edge
3157           }
3158           catch ( Standard_Failure )
3159           {
3160             continue;
3161           }
3162         }
3163         // get nodes shared by faces that may be distorted
3164         SMDS_NodeIteratorPtr nodeIt;
3165         if ( edgeSM->NbNodes() > 0 ) {
3166           nodeIt = edgeSM->GetNodes();
3167         }
3168         else {
3169           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( theHelper.IthVertex( 0, edge ));
3170           if ( !vertexSM )
3171             vertexSM = meshDS->MeshElements( theHelper.IthVertex( 1, edge ));
3172           if ( !vertexSM ) continue;
3173           nodeIt = vertexSM->GetNodes();
3174         }
3175
3176         // find suspicious faces
3177         TIDSortedElemSet checkedFaces;
3178         vector< const SMDS_MeshNode* > nOnEdge( 2 );
3179         const SMDS_MeshNode*           nOnFace;
3180         while ( nodeIt->more() )
3181         {
3182           const SMDS_MeshNode* n      = nodeIt->next();
3183           SMDS_ElemIteratorPtr faceIt = n->GetInverseElementIterator( SMDSAbs_Face );
3184           while ( faceIt->more() )
3185           {
3186             const SMDS_MeshElement* f = faceIt->next();
3187             if ( !faceSM->Contains( f ) ||
3188                  f->NbNodes() != 6      || // check quadratic triangles only
3189                  !checkedFaces.insert( f ).second )
3190               continue;
3191
3192             // get nodes on EDGE and on FACE of a suspicious face
3193             nOnEdge.clear(); nOnFace = 0;
3194             SMDS_MeshElement::iterator triNode = f->begin_nodes();
3195             for ( int nbN = 0; nbN < 3; ++triNode, ++nbN )
3196             {
3197               n = *triNode;
3198               if ( n->GetPosition()->GetDim() == 2 )
3199                 nOnFace = n;
3200               else
3201                 nOnEdge.push_back( n );
3202             }
3203
3204             // check if nOnFace is inside the FACE
3205             if ( nOnFace && nOnEdge.size() == 2 )
3206             {
3207               theHelper.AddTLinks( static_cast< const SMDS_MeshFace* > ( f ));
3208               if ( !SMESH_Algo::FaceNormal( f, faceNorm, /*normalized=*/false ))
3209                 continue;
3210               gp_XYZ edgeDir  = SMESH_TNodeXYZ( nOnEdge[0] ) - SMESH_TNodeXYZ( nOnEdge[1] );
3211               gp_XYZ edgeNorm = faceNorm ^ edgeDir;
3212               n = theHelper.GetMediumNode( nOnEdge[0], nOnEdge[1], true );
3213               gp_XYZ pN0     = SMESH_TNodeXYZ( nOnEdge[0] );
3214               gp_XYZ pMedium = SMESH_TNodeXYZ( n );                   // on-edge node location
3215               gp_XYZ pFaceN  = SMESH_TNodeXYZ( nOnFace );             // on-face node location
3216               double hMedium = edgeNorm * gp_Vec( pN0, pMedium ).XYZ();
3217               double hFace   = edgeNorm * gp_Vec( pN0, pFaceN ).XYZ();
3218               if ( Abs( hMedium ) > Abs( hFace * 0.6 ))
3219               {
3220                 // nOnFace is out of FACE, move a medium on-edge node to the middle
3221                 gp_XYZ pMid3D = 0.5 * ( pN0 + SMESH_TNodeXYZ( nOnEdge[1] ));
3222                 meshDS->MoveNode( n, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
3223                 MSG( "move OUT of face " << n );
3224                 theError->myBadElements.push_back( f );
3225               }
3226             }
3227           }
3228         }
3229       }
3230       if ( !theError->myBadElements.empty() )
3231         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
3232       return;
3233
3234     } // 2D ==============================================================================
3235
3236     if ( shape.ShapeType() == TopAbs_SOLID ) // 3D
3237     {
3238       if ( theHelper.GetMesh()->NbTetras  ( ORDER_QUADRATIC ) < 1 &&
3239            theHelper.GetMesh()->NbPyramids( ORDER_QUADRATIC ) < 1 ) return;
3240
3241       SMESHDS_SubMesh* solidSM = meshDS->MeshElements( shape );
3242       if ( !solidSM ) return;
3243
3244       // check if the SOLID is bound by concave FACEs
3245       vector< TopoDS_Face > concaveFaces;
3246       TopExp_Explorer faceIt( shape, TopAbs_FACE );
3247       for ( ; faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3248       {
3249         const TopoDS_Face&  face = TopoDS::Face( faceIt.Current() );
3250         if ( !meshDS->MeshElements( face )) continue;
3251
3252         BRepAdaptor_Surface surface( face );
3253         switch ( surface.GetType() ) {
3254         case GeomAbs_Plane: continue;
3255         case GeomAbs_Cylinder:
3256         case GeomAbs_Cone:
3257         case GeomAbs_Sphere:
3258           try
3259           {
3260             double u = 0.5 * ( surface.FirstUParameter() + surface.LastUParameter() );
3261             double v = 0.5 * ( surface.FirstVParameter() + surface.LastVParameter() );
3262             gp_Vec Du1, Dv1, Du2, Dv2, Duv2; gp_Pnt p;
3263             surface.D2( u,v, p, Du1, Dv1, Du2, Dv2, Duv2 );
3264             gp_Vec fNorm = Du1 ^ Dv1;
3265             if ( face.Orientation() == TopAbs_REVERSED ) fNorm.Reverse();
3266             bool concaveU = ( fNorm * Du2 > 1e-100 );
3267             bool concaveV = ( fNorm * Dv2 > 1e-100 );
3268             if ( concaveU || concaveV )
3269               concaveFaces.push_back( face );
3270           }
3271           catch ( Standard_Failure )
3272           {
3273             concaveFaces.push_back( face );
3274           }
3275         }
3276       }
3277       if ( concaveFaces.empty() )
3278         return;
3279
3280       // fix 2D mesh on the SOLID
3281       for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3282       {
3283         SMESH_MesherHelper faceHelper( *theHelper.GetMesh() );
3284         faceHelper.SetSubShape( faceIt.Current() );
3285         force3DOutOfBoundary( faceHelper, theError );
3286       }
3287
3288       // get an iterator over faces on concaveFaces
3289       vector< SMDS_ElemIteratorPtr > faceIterVec( concaveFaces.size() );
3290       for ( size_t i = 0; i < concaveFaces.size(); ++i )
3291         faceIterVec[i] = meshDS->MeshElements( concaveFaces[i] )->GetElements();
3292       typedef SMDS_IteratorOnIterators
3293         < const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIterOnIter;
3294       SMDS_ElemIteratorPtr faceIter( new TIterOnIter( faceIterVec ));
3295
3296       // a seacher to check if a volume is close to a concave face
3297       std::auto_ptr< SMESH_ElementSearcher > faceSearcher
3298         ( SMESH_MeshEditor( theHelper.GetMesh() ).GetElementSearcher( faceIter ));
3299
3300       // classifier
3301       //BRepClass3d_SolidClassifier solidClassifier( shape );
3302
3303       TIDSortedElemSet checkedVols, movedNodes;
3304       for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3305       {
3306         const TopoDS_Shape& face = faceIt.Current();
3307         SMESHDS_SubMesh*  faceSM = meshDS->MeshElements( face );
3308         if ( !faceSM ) continue;
3309
3310         // get nodes shared by volumes (tet and pyra) on the FACE that may be distorted
3311         SMDS_NodeIteratorPtr nodeIt;
3312         if ( faceSM->NbNodes() > 0 ) {
3313           nodeIt = faceSM->GetNodes();
3314         }
3315         else {
3316           TopExp_Explorer vertex( face, TopAbs_VERTEX );
3317           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( vertex.Current() );
3318           if ( !vertexSM ) continue;
3319           nodeIt = vertexSM->GetNodes();
3320         }
3321
3322         // find suspicious volumes adjacent to the FACE
3323         vector< const SMDS_MeshNode* >    nOnFace( 4 );
3324         const SMDS_MeshNode*              nInSolid;
3325         //vector< const SMDS_MeshElement* > intersectedFaces;
3326         while ( nodeIt->more() )
3327         {
3328           const SMDS_MeshNode* n     = nodeIt->next();
3329           SMDS_ElemIteratorPtr volIt = n->GetInverseElementIterator( SMDSAbs_Volume );
3330           while ( volIt->more() )
3331           {
3332             const SMDS_MeshElement* vol = volIt->next();
3333             int nbN = vol->NbCornerNodes();
3334             if ( ( nbN != 4 && nbN != 5 )  ||
3335                  !solidSM->Contains( vol ) ||
3336                  !checkedVols.insert( vol ).second )
3337               continue;
3338
3339             // get nodes on FACE and in SOLID of a suspicious volume
3340             nOnFace.clear(); nInSolid = 0;
3341             SMDS_MeshElement::iterator volNode = vol->begin_nodes();
3342             for ( int nb = nbN; nb > 0; ++volNode, --nb )
3343             {
3344               n = *volNode;
3345               if ( n->GetPosition()->GetDim() == 3 )
3346                 nInSolid = n;
3347               else
3348                 nOnFace.push_back( n );
3349             }
3350             if ( !nInSolid || nOnFace.size() != nbN - 1 )
3351               continue;
3352
3353             // get size of the vol
3354             SMESH_TNodeXYZ pInSolid( nInSolid ), pOnFace0( nOnFace[0] );
3355             double volLength = pInSolid.SquareDistance( nOnFace[0] );
3356             for ( size_t i = 1; i < nOnFace.size(); ++i )
3357             {
3358               volLength = Max( volLength, pOnFace0.SquareDistance( nOnFace[i] ));
3359             }
3360
3361             // check if vol is close to concaveFaces
3362             const SMDS_MeshElement* closeFace =
3363               faceSearcher->FindClosestTo( pInSolid, SMDSAbs_Face );
3364             if ( !closeFace ||
3365                  pInSolid.SquareDistance( closeFace->GetNode(0) ) > 4 * volLength )
3366               continue;
3367
3368             // check if vol is distorted, i.e. a medium node is much closer
3369             // to nInSolid than the link middle
3370             bool isDistorted = false;
3371             SMDS_FaceOfNodes onFaceTria( nOnFace[0], nOnFace[1], nOnFace[2] );
3372             if ( !SMESH_Algo::FaceNormal( &onFaceTria, faceNorm, /*normalized=*/false ))
3373               continue;
3374             theHelper.AddTLinks( static_cast< const SMDS_MeshVolume* > ( vol ));
3375             vector< pair< SMESH_TLink, const SMDS_MeshNode* > > links;
3376             for ( size_t i = 0; i < nOnFace.size(); ++i ) // loop on links between nOnFace
3377               for ( size_t j = i+1; j < nOnFace.size(); ++j )
3378               {
3379                 SMESH_TLink link( nOnFace[i], nOnFace[j] );
3380                 TLinkNodeMap::const_iterator linkIt =
3381                   theHelper.GetTLinkNodeMap().find( link );
3382                 if ( linkIt != theHelper.GetTLinkNodeMap().end() )
3383                 {
3384                   links.push_back( make_pair( linkIt->first, linkIt->second  ));
3385                   if ( !isDistorted ) {
3386                     // compare projections of nInSolid and nMedium to face normal
3387                     gp_Pnt pMedium = SMESH_TNodeXYZ( linkIt->second );
3388                     double hMedium = faceNorm * gp_Vec( pOnFace0, pMedium ).XYZ();
3389                     double hVol    = faceNorm * gp_Vec( pOnFace0, pInSolid ).XYZ();
3390                     isDistorted = ( Abs( hMedium ) > Abs( hVol * 0.5 ));
3391                   }
3392                 }
3393               }
3394             // move medium nodes to link middle
3395             if ( isDistorted )
3396             {
3397               for ( size_t i = 0; i < links.size(); ++i )
3398               {
3399                 const SMDS_MeshNode* nMedium = links[i].second;
3400                 if ( movedNodes.insert( nMedium ).second )
3401                 {
3402                   gp_Pnt pMid3D = 0.5 * ( SMESH_TNodeXYZ( links[i].first.node1() ) +
3403                                           SMESH_TNodeXYZ( links[i].first.node2() ));
3404                   meshDS->MoveNode( nMedium, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
3405                   MSG( "move OUT of solid " << nMedium );
3406                 }
3407               }
3408               theError->myBadElements.push_back( vol );
3409             }
3410           } // loop on volumes sharing a node on FACE
3411         } // loop on nodes on FACE
3412       }  // loop on FACEs of a SOLID
3413
3414       if ( !theError->myBadElements.empty() )
3415         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
3416     } // 3D case
3417   }
3418
3419 } //namespace
3420
3421 //=======================================================================
3422 /*!
3423  * \brief Move medium nodes of faces and volumes to fix distorted elements
3424  * \param error - container of fixed distorted elements
3425  * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
3426  * 
3427  * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
3428  */
3429 //=======================================================================
3430
3431 void SMESH_MesherHelper::FixQuadraticElements(SMESH_ComputeErrorPtr& error,
3432                                               bool                   volumeOnly)
3433 {
3434   // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
3435   if ( getenv("NO_FixQuadraticElements") )
3436     return;
3437
3438   // 0. Apply algorithm to SOLIDs or FACEs
3439   // ----------------------------------------------
3440   if ( myShape.IsNull() ) {
3441     if ( !myMesh->HasShapeToMesh() ) return;
3442     SetSubShape( myMesh->GetShapeToMesh() );
3443
3444 #ifdef _DEBUG_
3445     int nbSolids = 0;
3446     TopTools_IndexedMapOfShape solids;
3447     TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
3448     nbSolids = solids.Extent();
3449 #endif
3450     TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
3451     for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
3452       faces.Add( f.Current() ); // not in solid
3453     }
3454     for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
3455       if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
3456         for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
3457           faces.Add( f.Current() ); // in not meshed solid
3458       }
3459       else { // fix nodes in the solid and its faces
3460 #ifdef _DEBUG_
3461         MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
3462 #endif
3463         SMESH_MesherHelper h(*myMesh);
3464         h.SetSubShape( s.Current() );
3465         h.FixQuadraticElements( error, false );
3466       }
3467     }
3468     // fix nodes on geom faces
3469 #ifdef _DEBUG_
3470     int nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--; 
3471 #endif
3472     for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
3473       MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
3474       SMESH_MesherHelper h(*myMesh);
3475       h.SetSubShape( fIt.Key() );
3476       h.FixQuadraticElements( error, true);
3477       h.ToFixNodeParameters(true);
3478     }
3479     //perf_print_all_meters(1);
3480     if ( error && error->myName == EDITERR_NO_MEDIUM_ON_GEOM )
3481       error->myComment = "during conversion to quadratic, "
3482         "some medium nodes were not placed on geometry to avoid distorting elements";
3483     return;
3484   }
3485
3486   // 1. Find out type of elements and get iterator on them
3487   // ---------------------------------------------------
3488
3489   SMDS_ElemIteratorPtr elemIt;
3490   SMDSAbs_ElementType elemType = SMDSAbs_All;
3491
3492   SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
3493   if ( !submesh )
3494     return;
3495   if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
3496     elemIt = smDS->GetElements();
3497     if ( elemIt->more() ) {
3498       elemType = elemIt->next()->GetType();
3499       elemIt = smDS->GetElements();
3500     }
3501   }
3502   if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
3503     return;
3504
3505   // 2. Fill in auxiliary data structures
3506   // ----------------------------------
3507
3508   set< QLink > links;
3509   set< QFace > faces;
3510   set< QLink >::iterator pLink;
3511   set< QFace >::iterator pFace;
3512
3513   bool isCurved = false;
3514   //bool hasRectFaces = false;
3515   //set<int> nbElemNodeSet;
3516   SMDS_VolumeTool volTool;
3517
3518   TIDSortedNodeSet apexOfPyramid;
3519   const int apexIndex = 4;
3520
3521   // Issue 0020982
3522   // Move medium nodes to the link middle for elements whose corner nodes
3523   // are out of geometrical boundary to fix distorted elements.
3524   force3DOutOfBoundary( *this, error );
3525
3526   if ( elemType == SMDSAbs_Volume )
3527   {
3528     while ( elemIt->more() ) // loop on volumes
3529     {
3530       const SMDS_MeshElement* vol = elemIt->next();
3531       if ( !vol->IsQuadratic() || !volTool.Set( vol ))
3532         return;
3533       double volMinSize2 = -1.;
3534       for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
3535       {
3536         int nbN = volTool.NbFaceNodes( iF );
3537         //nbElemNodeSet.insert( nbN );
3538         const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
3539         vector< const QLink* > faceLinks( nbN/2 );
3540         for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
3541         {
3542           // store QLink
3543           QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
3544           pLink = links.insert( link ).first;
3545           faceLinks[ iN/2 ] = & *pLink;
3546
3547           if ( link.MediumPos() == SMDS_TOP_3DSPACE )
3548           {
3549             if ( !link.IsStraight() )
3550               return; // already fixed
3551           }
3552           else if ( !isCurved )
3553           {
3554             if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
3555             isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
3556           }
3557         }
3558         // store QFace
3559         pFace = faces.insert( QFace( faceLinks )).first;
3560         if ( pFace->NbVolumes() == 0 )
3561           pFace->AddSelfToLinks();
3562         pFace->SetVolume( vol );
3563 //         hasRectFaces = hasRectFaces ||
3564 //           ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
3565 //             volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
3566 #ifdef _DEBUG_
3567         if ( nbN == 6 )
3568           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
3569         else
3570           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
3571                                                faceNodes[4],faceNodes[6] );
3572 #endif
3573       }
3574       // collect pyramid apexes for further correction
3575       if ( vol->NbCornerNodes() == 5 )
3576         apexOfPyramid.insert( vol->GetNode( apexIndex ));
3577     }
3578     set< QLink >::iterator pLink = links.begin();
3579     for ( ; pLink != links.end(); ++pLink )
3580       pLink->SetContinuesFaces();
3581   }
3582   else
3583   {
3584     while ( elemIt->more() ) // loop on faces
3585     {
3586       const SMDS_MeshElement* face = elemIt->next();
3587       if ( !face->IsQuadratic() )
3588         continue;
3589       //nbElemNodeSet.insert( face->NbNodes() );
3590       int nbN = face->NbNodes()/2;
3591       vector< const QLink* > faceLinks( nbN );
3592       for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
3593       {
3594         // store QLink
3595         QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
3596         pLink = links.insert( link ).first;
3597         faceLinks[ iN ] = & *pLink;
3598         if ( !isCurved )
3599           isCurved = !link.IsStraight();
3600       }
3601       // store QFace
3602       pFace = faces.insert( QFace( faceLinks )).first;
3603       pFace->AddSelfToLinks();
3604       //hasRectFaces = ( hasRectFaces || nbN == 4 );
3605     }
3606   }
3607   if ( !isCurved )
3608     return; // no curved edges of faces
3609
3610   // 3. Compute displacement of medium nodes
3611   // ---------------------------------------
3612
3613   // two loops on QFaces: the first is to treat boundary links, the second is for internal ones
3614   TopLoc_Location loc;
3615   // not treat boundary of volumic submesh
3616   int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
3617   for ( ; isInside < 2; ++isInside ) {
3618     MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
3619     SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
3620     SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
3621
3622     for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
3623       if ( bool(isInside) == pFace->IsBoundary() )
3624         continue;
3625       for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
3626       {
3627         MSG( "CHAIN");
3628         // make chain of links connected via continues faces
3629         int error = ERR_OK;
3630         TChain rawChain;
3631         if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
3632         rawChain.reverse();
3633         if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
3634
3635         vector< TChain > chains;
3636         if ( error == ERR_OK ) { // chain contains continues rectangles
3637           chains.resize(1);
3638           chains[0].splice( chains[0].begin(), rawChain );
3639         }
3640         else if ( error == ERR_TRI ) {  // chain contains continues triangles
3641           TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
3642           if ( res != _OK ) { // not quadrangles split into triangles
3643             fixTriaNearBoundary( rawChain, *this );
3644             break;
3645           }
3646         }
3647         else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
3648           fixPrism( rawChain );
3649           break;
3650         }
3651         else {
3652           continue;
3653         }
3654         for ( int iC = 0; iC < chains.size(); ++iC )
3655         {
3656           TChain& chain = chains[iC];
3657           if ( chain.empty() ) continue;
3658           if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
3659             MSG("3D straight - ignore");
3660             continue;
3661           }
3662           if ( chain.front()->MediumPos() > bndPos ||
3663                chain.back() ->MediumPos() > bndPos ) {
3664             MSG("Internal chain - ignore");
3665             continue;
3666           }
3667           // mesure chain length and compute link position along the chain
3668           double chainLen = 0;
3669           vector< double > linkPos;
3670           MSGBEG( "Link medium nodes: ");
3671           TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
3672           for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
3673             MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
3674             double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3675             while ( len < numeric_limits<double>::min() ) { // remove degenerated link
3676               link1 = chain.erase( link1 );
3677               if ( link1 == chain.end() )
3678                 break;
3679               len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3680             }
3681             chainLen += len;
3682             linkPos.push_back( chainLen );
3683           }
3684           MSG("");
3685           if ( linkPos.size() < 2 )
3686             continue;
3687
3688           gp_Vec move0 = chain.front()->_nodeMove;
3689           gp_Vec move1 = chain.back ()->_nodeMove;
3690
3691           TopoDS_Face face;
3692           bool checkUV = true;
3693           if ( !isInside )
3694           {
3695             // compute node displacement of end links of chain in parametric space of face
3696             TChainLink& linkOnFace = *(++chain.begin());
3697             const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
3698             TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
3699             if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
3700             {
3701               face = TopoDS::Face( f );
3702               Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
3703               bool isStraight[2];
3704               for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
3705               {
3706                 TChainLink& link = is1 ? chain.back() : chain.front();
3707                 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
3708                 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
3709                 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
3710                 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3711                 // uvMove = uvm - uv12
3712                 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
3713                 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
3714                 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
3715                   nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
3716                 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
3717                                                   10 * uvMove.SquareModulus());
3718               }
3719               if ( isStraight[0] && isStraight[1] ) {
3720                 MSG("2D straight - ignore");
3721                 continue; // straight - no need to move nodes of internal links
3722               }
3723
3724               // check if a chain is already fixed
3725               gp_XY uvm = GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV);
3726               gp_XY uv1 = GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV);
3727               gp_XY uv2 = GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV);
3728               gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3729               if (( uvm - uv12 ).SquareModulus() > 1e-10 )
3730               {
3731                 MSG("Already fixed - ignore");
3732                 continue;
3733               }
3734             }
3735           }
3736           gp_Trsf trsf;
3737           if ( isInside || face.IsNull() )
3738           {
3739             // compute node displacement of end links in their local coord systems
3740             {
3741               TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
3742               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
3743                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3744               move0.Transform(trsf);
3745             }
3746             {
3747               TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
3748               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
3749                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3750               move1.Transform(trsf);
3751             }
3752           }
3753           // compute displacement of medium nodes
3754           link2 = chain.begin();
3755           link0 = link2++;
3756           link1 = link2++;
3757           for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
3758           {
3759             double r = linkPos[i] / chainLen;
3760             // displacement in local coord system
3761             gp_Vec move = (1. - r) * move0 + r * move1;
3762             if ( isInside || face.IsNull()) {
3763               // transform to global
3764               gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
3765               gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
3766               gp_Vec x = x01.Normalized() + x12.Normalized();
3767               trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
3768               move.Transform(trsf);
3769             }
3770             else {
3771               // compute 3D displacement by 2D one
3772               Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
3773               gp_XY oldUV   = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
3774               gp_XY newUV   = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
3775               gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
3776               move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
3777 #ifdef _DEBUG_
3778               if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
3779                    move.SquareMagnitude())
3780               {
3781                 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
3782                 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
3783                 MSG( "TOO LONG MOVE \t" <<
3784                      "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
3785                      "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
3786                      "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
3787                      "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
3788               }
3789 #endif
3790             }
3791             (*link1)->Move( move );
3792             MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
3793                  << chain.front()->_mediumNode->GetID() <<"-"
3794                  << chain.back ()->_mediumNode->GetID() <<
3795                  " by " << move.Magnitude());
3796           }
3797         } // loop on chains of links
3798       } // loop on 2 directions of propagation from quadrangle
3799     } // loop on faces
3800   } // fix faces and/or volumes
3801
3802   // 4. Move nodes
3803   // -------------
3804
3805   for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
3806     if ( pLink->IsMoved() ) {
3807       gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
3808       GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
3809     }
3810   }
3811
3812   // Issue 0020982
3813   // Move the apex of pyramid together with the most curved link.
3814   // TIDSortedNodeSet::iterator apexIt = apexOfPyramid.begin();
3815   // for ( ; apexIt != apexOfPyramid.end(); ++apexIt )
3816   // {
3817   //   SMESH_TNodeXYZ apex = *apexIt;
3818
3819   //   gp_Vec maxMove( 0,0,0 );
3820   //   double maxMoveSize2 = 0;
3821
3822   //   // shift of node index to get medium nodes between the base nodes
3823   //   const int base2MediumShift = 5;
3824
3825   //   // find maximal movement of medium node
3826   //   SMDS_ElemIteratorPtr volIt = apex._node->GetInverseElementIterator( SMDSAbs_Volume );
3827   //   vector< const SMDS_MeshElement* > pyramids;
3828   //   while ( volIt->more() )
3829   //   {
3830   //     const SMDS_MeshElement* pyram = volIt->next();
3831   //     if ( pyram->GetEntityType() != SMDSEntity_Quad_Pyramid ) continue;
3832   //     pyramids.push_back( pyram );
3833
3834   //     for ( int iBase = 0; iBase < apexIndex; ++iBase )
3835   //     {
3836   //       SMESH_TNodeXYZ medium = pyram->GetNode( iBase + base2MediumShift );
3837   //       if ( medium._node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
3838   //       {
3839   //         SMESH_TNodeXYZ n1 = pyram->GetNode( iBase );
3840   //         SMESH_TNodeXYZ n2 = pyram->GetNode( ( iBase+1 ) % 4 );
3841   //         gp_Pnt middle = 0.5 * ( n1 + n2 );
3842   //         gp_Vec move( middle, medium );
3843   //         double moveSize2 = move.SquareMagnitude();
3844   //         if ( moveSize2 > maxMoveSize2 )
3845   //           maxMove = move, maxMoveSize2 = moveSize2;
3846   //       }
3847   //     }
3848   //   }
3849
3850   //   // move the apex
3851   //   if ( maxMoveSize2 > 1e-20 )
3852   //   {
3853   //     apex += maxMove.XYZ();
3854   //     GetMeshDS()->MoveNode( apex._node, apex.X(), apex.Y(), apex.Z());
3855
3856   //     // move medium nodes neighboring the apex to the middle
3857   //     const int base2MediumShift_2 = 9;
3858   //     for ( unsigned i = 0; i < pyramids.size(); ++i )
3859   //       for ( int iBase = 0; iBase < apexIndex; ++iBase )
3860   //       {
3861   //         SMESH_TNodeXYZ         base = pyramids[i]->GetNode( iBase );
3862   //         const SMDS_MeshNode* medium = pyramids[i]->GetNode( iBase + base2MediumShift_2 );
3863   //         gp_XYZ middle = 0.5 * ( apex + base );
3864   //         GetMeshDS()->MoveNode( medium, middle.X(), middle.Y(), middle.Z());
3865   //       }
3866   //   }
3867   // }
3868 }
3869