Salome HOME
Update copyright notes (for 2010)
[modules/smesh.git] / src / SMESH / SMESH_MesherHelper.cxx
1 //  Copyright (C) 2007-2010  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_FacePosition.hxx" 
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeTool.hxx"
32 #include "SMESH_subMesh.hxx"
33
34 #include <BRepAdaptor_Surface.hxx>
35 #include <BRepTools.hxx>
36 #include <BRepTools_WireExplorer.hxx>
37 #include <BRep_Tool.hxx>
38 #include <Geom2d_Curve.hxx>
39 #include <GeomAPI_ProjectPointOnCurve.hxx>
40 #include <GeomAPI_ProjectPointOnSurf.hxx>
41 #include <Geom_Curve.hxx>
42 #include <Geom_Surface.hxx>
43 #include <ShapeAnalysis.hxx>
44 #include <TopExp.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_MapIteratorOfMapOfShape.hxx>
48 #include <TopTools_MapOfShape.hxx>
49 #include <TopoDS.hxx>
50 #include <gp_Ax3.hxx>
51 #include <gp_Pnt2d.hxx>
52 #include <gp_Trsf.hxx>
53
54 #include <Standard_Failure.hxx>
55 #include <Standard_ErrorHandler.hxx>
56
57 #include <utilities.h>
58
59 #include <limits>
60
61 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
62
63 namespace {
64
65   gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
66
67   enum { U_periodic = 1, V_periodic = 2 };
68 }
69
70 //================================================================================
71 /*!
72  * \brief Constructor
73  */
74 //================================================================================
75
76 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
77   : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false)
78 {
79   myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
80   mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
81 }
82
83 //=======================================================================
84 //function : ~SMESH_MesherHelper
85 //purpose  : 
86 //=======================================================================
87
88 SMESH_MesherHelper::~SMESH_MesherHelper()
89 {
90   TID2Projector::iterator i_proj = myFace2Projector.begin();
91   for ( ; i_proj != myFace2Projector.end(); ++i_proj )
92     delete i_proj->second;
93 }
94
95 //=======================================================================
96 //function : IsQuadraticSubMesh
97 //purpose  : Check submesh for given shape: if all elements on this shape 
98 //           are quadratic, quadratic elements will be created.
99 //           Also fill myTLinkNodeMap
100 //=======================================================================
101
102 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
103 {
104   SMESHDS_Mesh* meshDS = GetMeshDS();
105   // we can create quadratic elements only if all elements
106   // created on subshapes of given shape are quadratic
107   // also we have to fill myTLinkNodeMap
108   myCreateQuadratic = true;
109   mySeamShapeIds.clear();
110   myDegenShapeIds.clear();
111   TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
112   SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
113
114   int nbOldLinks = myTLinkNodeMap.size();
115
116   TopExp_Explorer exp( aSh, subType );
117   for (; exp.More() && myCreateQuadratic; exp.Next()) {
118     if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
119       if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
120         while(it->more()) {
121           const SMDS_MeshElement* e = it->next();
122           if ( e->GetType() != elemType || !e->IsQuadratic() ) {
123             myCreateQuadratic = false;
124             break;
125           }
126           else {
127             // fill TLinkNodeMap
128             switch ( e->NbNodes() ) {
129             case 3:
130               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
131             case 6:
132               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
133               AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
134               AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
135             case 8:
136               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
137               AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
138               AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
139               AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
140               break;
141             default:
142               myCreateQuadratic = false;
143               break;
144             }
145           }
146         }
147       }
148     }
149   }
150
151   if ( nbOldLinks == myTLinkNodeMap.size() )
152     myCreateQuadratic = false;
153
154   if(!myCreateQuadratic) {
155     myTLinkNodeMap.clear();
156   }
157   SetSubShape( aSh );
158
159   return myCreateQuadratic;
160 }
161
162 //=======================================================================
163 //function : SetSubShape
164 //purpose  : Set geomerty to make elements on
165 //=======================================================================
166
167 void SMESH_MesherHelper::SetSubShape(const int aShID)
168 {
169   if ( aShID == myShapeID )
170     return;
171   if ( aShID > 1 )
172     SetSubShape( GetMeshDS()->IndexToShape( aShID ));
173   else
174     SetSubShape( TopoDS_Shape() );
175 }
176
177 //=======================================================================
178 //function : SetSubShape
179 //purpose  : Set geomerty to create elements on
180 //=======================================================================
181
182 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
183 {
184   if ( myShape.IsSame( aSh ))
185     return;
186
187   myShape = aSh;
188   mySeamShapeIds.clear();
189   myDegenShapeIds.clear();
190
191   if ( myShape.IsNull() ) {
192     myShapeID  = 0;
193     return;
194   }
195   SMESHDS_Mesh* meshDS = GetMeshDS();
196   myShapeID = meshDS->ShapeToIndex(aSh);
197   myParIndex = 0;
198
199   // treatment of periodic faces
200   for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
201   {
202     const TopoDS_Face& face = TopoDS::Face( eF.Current() );
203     BRepAdaptor_Surface surface( face );
204     if ( surface.IsUPeriodic() || surface.IsVPeriodic() )
205     {
206       for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
207       {
208         // look for a seam edge
209         const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
210         if ( BRep_Tool::IsClosed( edge, face )) {
211           // initialize myPar1, myPar2 and myParIndex
212           gp_Pnt2d uv1, uv2;
213           BRep_Tool::UVPoints( edge, face, uv1, uv2 );
214           if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
215           {
216             myParIndex |= U_periodic;
217             myPar1[0] = surface.FirstUParameter();
218             myPar2[0] = surface.LastUParameter();
219           }
220           else {
221             myParIndex |= V_periodic;
222             myPar1[1] = surface.FirstVParameter();
223             myPar2[1] = surface.LastVParameter();
224           }
225           // store seam shape indices, negative if shape encounters twice
226           int edgeID = meshDS->ShapeToIndex( edge );
227           mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
228           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
229             int vertexID = meshDS->ShapeToIndex( v.Current() );
230             mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
231           }
232         }
233
234         // look for a degenerated edge
235         if ( BRep_Tool::Degenerated( edge )) {
236           myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
237           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
238             myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
239         }
240       }
241     }
242   }
243 }
244
245 //=======================================================================
246 //function : GetNodeUVneedInFaceNode
247 //purpose  : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
248 //           Return true if the face is periodic.
249 //           If F is Null, answer about subshape set through IsQuadraticSubMesh() or
250 //           * SetSubShape()
251 //=======================================================================
252
253 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
254 {
255   if ( F.IsNull() ) return !mySeamShapeIds.empty();
256
257   if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
258     return !mySeamShapeIds.empty();
259
260   TopLoc_Location loc;
261   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
262   if ( !aSurface.IsNull() )
263     return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
264
265   return false;
266 }
267
268 //=======================================================================
269 //function : IsMedium
270 //purpose  : 
271 //=======================================================================
272
273 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode*      node,
274                                   const SMDSAbs_ElementType typeToCheck)
275 {
276   return SMESH_MeshEditor::IsMedium( node, typeToCheck );
277 }
278
279 //=======================================================================
280 //function : GetSubShapeByNode
281 //purpose  : Return support shape of a node
282 //=======================================================================
283
284 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
285                                                    SMESHDS_Mesh*        meshDS)
286 {
287   int shapeID = node->GetPosition()->GetShapeId();
288   if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
289     return meshDS->IndexToShape( shapeID );
290   else
291     return TopoDS_Shape();
292 }
293
294
295 //=======================================================================
296 //function : AddTLinkNode
297 //purpose  : add a link in my data structure
298 //=======================================================================
299
300 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
301                                       const SMDS_MeshNode* n2,
302                                       const SMDS_MeshNode* n12)
303 {
304   // add new record to map
305   SMESH_TLink link( n1, n2 );
306   myTLinkNodeMap.insert( make_pair(link,n12));
307 }
308
309 //=======================================================================
310 //function : GetUVOnSeam
311 //purpose  : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
312 //=======================================================================
313
314 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
315 {
316   gp_Pnt2d result = uv1;
317   for ( int i = U_periodic; i <= V_periodic ; ++i )
318   {
319     if ( myParIndex & i )
320     {
321       double p1 = uv1.Coord( i );
322       double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
323       if ( myParIndex == i ||
324            dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
325            dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
326       {
327         double p2 = uv2.Coord( i );
328         double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
329         if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
330           result.SetCoord( i, p1Alt );
331       }
332     }
333   }
334   return result;
335 }
336
337 //=======================================================================
338 //function : GetNodeUV
339 //purpose  : Return node UV on face
340 //=======================================================================
341
342 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face&   F,
343                                     const SMDS_MeshNode* n,
344                                     const SMDS_MeshNode* n2,
345                                     bool*                check) const
346 {
347   gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
348   const SMDS_PositionPtr Pos = n->GetPosition();
349   bool uvOK = false;
350   if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
351   {
352     // node has position on face
353     const SMDS_FacePosition* fpos =
354       static_cast<const SMDS_FacePosition*>(n->GetPosition().get());
355     uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
356     if ( check )
357       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), BRep_Tool::Tolerance( F ));
358   }
359   else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
360   {
361     // node has position on edge => it is needed to find
362     // corresponding edge from face, get pcurve for this
363     // edge and retrieve value from this pcurve
364     const SMDS_EdgePosition* epos =
365       static_cast<const SMDS_EdgePosition*>(n->GetPosition().get());
366     int edgeID = Pos->GetShapeId();
367     TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
368     double f, l, u = epos->GetUParameter();
369     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
370     bool validU = ( f < u && u < l );
371     if ( validU )
372       uv = C2d->Value( u );
373     else
374       uv.SetCoord(0.,0.);
375     if ( check || !validU )
376       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), BRep_Tool::Tolerance( E ),/*force=*/ !validU );
377
378     // for a node on a seam edge select one of UVs on 2 pcurves
379     if ( n2 && IsSeamShape( edgeID ) )
380     {
381       uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
382     }
383     else
384     { // adjust uv to period
385       TopLoc_Location loc;
386       Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
387       Standard_Boolean isUPeriodic = S->IsUPeriodic();
388       Standard_Boolean isVPeriodic = S->IsVPeriodic();
389       if ( isUPeriodic || isVPeriodic ) {
390         Standard_Real UF,UL,VF,VL;
391         S->Bounds(UF,UL,VF,VL);
392         if(isUPeriodic)
393           uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
394         if(isVPeriodic)
395           uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
396       }
397     }
398   }
399   else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
400   {
401     if ( int vertexID = n->GetPosition()->GetShapeId() ) {
402       const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
403       try {
404         uv = BRep_Tool::Parameters( V, F );
405         uvOK = true;
406       }
407       catch (Standard_Failure& exc) {
408       }
409       if ( !uvOK ) {
410         for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
411           uvOK = ( V == vert.Current() );
412         if ( !uvOK ) {
413 #ifdef _DEBUG_
414           MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
415                << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
416 #endif
417           // get UV of a vertex closest to the node
418           double dist = 1e100;
419           gp_Pnt pn = XYZ( n );
420           for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
421             TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
422             gp_Pnt p = BRep_Tool::Pnt( curV );
423             double curDist = p.SquareDistance( pn );
424             if ( curDist < dist ) {
425               dist = curDist;
426               uv = BRep_Tool::Parameters( curV, F );
427               uvOK = ( dist < DBL_MIN );
428             }
429           }
430         }
431         else {
432           uvOK = false;
433           TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
434           for ( ; it.More(); it.Next() ) {
435             if ( it.Value().ShapeType() == TopAbs_EDGE ) {
436               const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
437               double f,l;
438               Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
439               if ( !C2d.IsNull() ) {
440                 double u = ( V == TopExp::FirstVertex( edge ) ) ?  f : l;
441                 uv = C2d->Value( u );
442                 uvOK = true;
443                 break;
444               }
445             }
446           }
447         }
448       }
449       if ( n2 && IsSeamShape( vertexID ) )
450         uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
451     }
452   }
453
454   if ( check )
455     *check = uvOK;
456
457   return uv.XY();
458 }
459
460 //=======================================================================
461 //function : CheckNodeUV
462 //purpose  : Check and fix node UV on a face
463 //=======================================================================
464
465 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face&   F,
466                                      const SMDS_MeshNode* n,
467                                      gp_XY&               uv,
468                                      const double         tol,
469                                      const bool           force) const
470 {
471   if ( force || !myOkNodePosShapes.count( n->GetPosition()->GetShapeId() ))
472   {
473     // check that uv is correct
474     TopLoc_Location loc;
475     Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
476     gp_Pnt nodePnt = XYZ( n );
477     if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
478     if ( Precision::IsInfinite( uv.X() ) ||
479          Precision::IsInfinite( uv.Y() ) ||
480          nodePnt.Distance( surface->Value( uv.X(), uv.Y() )) > tol )
481     {
482       // uv incorrect, project the node to surface
483       GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
484       projector.Perform( nodePnt );
485       if ( !projector.IsDone() || projector.NbPoints() < 1 )
486       {
487         MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
488         return false;
489       }
490       Quantity_Parameter U,V;
491       projector.LowerDistanceParameters(U,V);
492       if ( nodePnt.Distance( surface->Value( U, V )) > tol )
493       {
494         MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
495         return false;
496       }
497       uv.SetCoord( U,V );
498     }
499     else if ( uv.Modulus() > numeric_limits<double>::min() )
500     {
501       ((SMESH_MesherHelper*) this)->myOkNodePosShapes.insert( n->GetPosition()->GetShapeId() );
502     }
503   }
504   return true;
505 }
506
507 //=======================================================================
508 //function : GetProjector
509 //purpose  : Return projector intitialized by given face without location, which is returned
510 //=======================================================================
511
512 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
513                                                              TopLoc_Location&   loc,
514                                                              double             tol ) const
515 {
516   Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
517   int faceID = GetMeshDS()->ShapeToIndex( F );
518   TID2Projector& i2proj = const_cast< TID2Projector&>( myFace2Projector );
519   TID2Projector::iterator i_proj = i2proj.find( faceID );
520   if ( i_proj == i2proj.end() )
521   {
522     if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
523     double U1, U2, V1, V2;
524     surface->Bounds(U1, U2, V1, V2);
525     GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
526     proj->Init( surface, U1, U2, V1, V2, tol );
527     i_proj = i2proj.insert( make_pair( faceID, proj )).first;
528   }
529   return *( i_proj->second );
530 }
531
532 namespace
533 {
534   gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
535   gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
536   gp_XY_FunPtr(Subtracted); 
537 }
538
539 //=======================================================================
540 //function : applyIn2D
541 //purpose  : Perform given operation on two 2d points in parameric space of given surface.
542 //           It takes into account period of the surface. Use gp_XY_FunPtr macro
543 //           to easily define pointer to function of gp_XY class.
544 //=======================================================================
545
546 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
547                                     const gp_XY&                uv1,
548                                     const gp_XY&                uv2,
549                                     xyFunPtr                    fun,
550                                     const bool                  resultInPeriod)
551 {
552   Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
553   Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
554   if ( !isUPeriodic && !isVPeriodic )
555     return fun(uv1,uv2);
556
557   // move uv2 not far than half-period from uv1
558   double u2 = 
559     uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
560   double v2 = 
561     uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
562
563   // execute operation
564   gp_XY res = fun( uv1, gp_XY(u2,v2) );
565
566   // move result within period
567   if ( resultInPeriod )
568   {
569     Standard_Real UF,UL,VF,VL;
570     surface->Bounds(UF,UL,VF,VL);
571     if ( isUPeriodic )
572       res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
573     if ( isVPeriodic )
574       res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
575   }
576
577   return res;
578 }
579 //=======================================================================
580 //function : GetMiddleUV
581 //purpose  : Return middle UV taking in account surface period
582 //=======================================================================
583
584 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
585                                       const gp_XY&                p1,
586                                       const gp_XY&                p2)
587 {
588   return applyIn2D( surface, p1, p2, & AverageUV );
589 }
590
591 //=======================================================================
592 //function : GetNodeU
593 //purpose  : Return node U on edge
594 //=======================================================================
595
596 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge&   E,
597                                     const SMDS_MeshNode* n,
598                                     bool*                check)
599 {
600   double param = 0;
601   const SMDS_PositionPtr Pos = n->GetPosition();
602   if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE) {
603     const SMDS_EdgePosition* epos =
604       static_cast<const SMDS_EdgePosition*>(n->GetPosition().get());
605     param =  epos->GetUParameter();
606   }
607   else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX) {
608     SMESHDS_Mesh * meshDS = GetMeshDS();
609     int vertexID = n->GetPosition()->GetShapeId();
610     const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
611     param =  BRep_Tool::Parameter( V, E );
612   }
613   if ( check )
614     *check = CheckNodeU( E, n, param, BRep_Tool::Tolerance( E ));
615   return param;
616 }
617
618 //=======================================================================
619 //function : CheckNodeU
620 //purpose  : Check and fix node U on an edge
621 //           Return false if U is bad and could not be fixed
622 //=======================================================================
623
624 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge&   E,
625                                     const SMDS_MeshNode* n,
626                                     double&              u,
627                                     const double         tol,
628                                     const bool           force) const
629 {
630   if ( force || !myOkNodePosShapes.count( n->GetPosition()->GetShapeId() ))
631   {
632     // check that u is correct
633     TopLoc_Location loc; double f,l;
634     Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
635     if ( curve.IsNull() ) // degenerated edge
636     {
637       if ( u+tol < f || u-tol > l )
638       {
639         double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
640         u =  f*r + l*(1-r);
641       }
642     }
643     else
644     {
645       gp_Pnt nodePnt = SMESH_MeshEditor::TNodeXYZ( n );
646       if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
647       if ( nodePnt.Distance( curve->Value( u )) > tol )
648       {
649         // u incorrect, project the node to the curve
650         GeomAPI_ProjectPointOnCurve projector( nodePnt, curve, f, l );
651         if ( projector.NbPoints() < 1 )
652         {
653           MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
654           return false;
655         }
656         Quantity_Parameter U = projector.LowerDistanceParameter();
657         if ( nodePnt.Distance( curve->Value( U )) > tol )
658         {
659           MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
660           return false;
661         }
662         u = double( U );
663       }
664       else if ( fabs( u ) > numeric_limits<double>::min() )
665       {
666         ((SMESH_MesherHelper*) this)->myOkNodePosShapes.insert( n->GetPosition()->GetShapeId() );
667       }
668     }
669   }
670   return true;
671 }
672
673 //=======================================================================
674 //function : GetMediumNode
675 //purpose  : Return existing or create new medium nodes between given ones
676 //=======================================================================
677
678 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
679                                                        const SMDS_MeshNode* n2,
680                                                        bool                 force3d)
681 {
682   // Find existing node
683
684   SMESH_TLink link(n1,n2);
685   ItTLinkNode itLN = myTLinkNodeMap.find( link );
686   if ( itLN != myTLinkNodeMap.end() ) {
687     return (*itLN).second;
688   }
689
690   // Create medium node
691
692   SMDS_MeshNode* n12;
693   SMESHDS_Mesh* meshDS = GetMeshDS();
694
695   // get type of shape for the new medium node
696   int faceID = -1, edgeID = -1;
697   const SMDS_PositionPtr Pos1 = n1->GetPosition();
698   const SMDS_PositionPtr Pos2 = n2->GetPosition();
699
700   if( myShape.IsNull() )
701   {
702     if( Pos1->GetTypeOfPosition()==SMDS_TOP_FACE ) {
703       faceID = Pos1->GetShapeId();
704     }
705     else if( Pos2->GetTypeOfPosition()==SMDS_TOP_FACE ) {
706       faceID = Pos2->GetShapeId();
707     }
708
709     if( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
710       edgeID = Pos1->GetShapeId();
711     }
712     if( Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
713       edgeID = Pos2->GetShapeId();
714     }
715   }
716   // get positions of the given nodes on shapes
717   TopoDS_Edge E; double u [2];
718   TopoDS_Face F; gp_XY  uv[2];
719   bool uvOK[2] = { false, false };
720   TopAbs_ShapeEnum shapeType = myShape.IsNull() ? TopAbs_SHAPE : myShape.ShapeType();
721   if ( faceID>0 || shapeType == TopAbs_FACE)
722   {
723     if( myShape.IsNull() )
724       F = TopoDS::Face(meshDS->IndexToShape(faceID));
725     else {
726       F = TopoDS::Face(myShape);
727       faceID = myShapeID;
728     }
729     uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
730     uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
731   }
732   else if (edgeID>0 || shapeType == TopAbs_EDGE)
733   {
734     if( myShape.IsNull() )
735       E = TopoDS::Edge(meshDS->IndexToShape(edgeID));
736     else {
737       E = TopoDS::Edge(myShape);
738       edgeID = myShapeID;
739     }
740     u[0] = GetNodeU(E,n1, force3d ? 0 : &uvOK[0]);
741     u[1] = GetNodeU(E,n2, force3d ? 0 : &uvOK[1]);
742   }
743   if(!force3d)
744   {
745     // we try to create medium node using UV parameters of
746     // nodes, else - medium between corresponding 3d points
747     if( ! F.IsNull() )
748     {
749       if ( uvOK[0] && uvOK[1] )
750       {
751         if ( IsDegenShape( Pos1->GetShapeId() ))
752           if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
753           else                           uv[0].SetCoord( 2, uv[1].Coord( 2 ));
754         else if ( IsDegenShape( Pos2->GetShapeId() ))
755           if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
756           else                           uv[1].SetCoord( 2, uv[0].Coord( 2 ));
757
758         TopLoc_Location loc;
759         Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
760         gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
761         gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
762         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
763         meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
764         myTLinkNodeMap.insert(make_pair(link,n12));
765         return n12;
766       }
767     }
768     else if ( !E.IsNull() )
769     {
770       double f,l;
771       Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
772       if(!C.IsNull())
773       {
774         Standard_Boolean isPeriodic = C->IsPeriodic();
775         double U;
776         if(isPeriodic) {
777           Standard_Real Period = C->Period();
778           Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
779           Standard_Real pmid = (u[0]+p)/2.;
780           U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
781         }
782         else
783           U = (u[0]+u[1])/2.;
784
785         gp_Pnt P = C->Value( U );
786         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
787         meshDS->SetNodeOnEdge(n12, edgeID, U);
788         myTLinkNodeMap.insert(make_pair(link,n12));
789         return n12;
790       }
791     }
792   }
793   // 3d variant
794   double x = ( n1->X() + n2->X() )/2.;
795   double y = ( n1->Y() + n2->Y() )/2.;
796   double z = ( n1->Z() + n2->Z() )/2.;
797   n12 = meshDS->AddNode(x,y,z);
798   if ( !F.IsNull() )
799   {
800     gp_XY UV = ( uv[0] + uv[1] ) / 2.;
801     CheckNodeUV( F, n12, UV, BRep_Tool::Tolerance( F ), /*force=*/true);
802     meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
803   }
804   else if ( !E.IsNull() )
805   {
806     double U = ( u[0] + u[1] ) / 2.;
807     CheckNodeU( E, n12, U, BRep_Tool::Tolerance( E ), /*force=*/true);
808     meshDS->SetNodeOnEdge(n12, edgeID, U);
809   }
810   else
811   {
812     meshDS->SetNodeInVolume(n12, myShapeID);
813   }
814   myTLinkNodeMap.insert( make_pair( link, n12 ));
815   return n12;
816 }
817
818 //=======================================================================
819 //function : AddNode
820 //purpose  : Creates a node
821 //=======================================================================
822
823 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID)
824 {
825   SMESHDS_Mesh * meshDS = GetMeshDS();
826   SMDS_MeshNode* node = 0;
827   if ( ID )
828     node = meshDS->AddNodeWithID( x, y, z, ID );
829   else
830     node = meshDS->AddNode( x, y, z );
831   if ( mySetElemOnShape && myShapeID > 0 ) {
832     switch ( myShape.ShapeType() ) {
833     case TopAbs_SOLID:  meshDS->SetNodeInVolume( node, myShapeID); break;
834     case TopAbs_SHELL:  meshDS->SetNodeInVolume( node, myShapeID); break;
835     case TopAbs_FACE:   meshDS->SetNodeOnFace(   node, myShapeID); break;
836     case TopAbs_EDGE:   meshDS->SetNodeOnEdge(   node, myShapeID); break;
837     case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
838     default: ;
839     }
840   }
841   return node;
842 }
843
844 //=======================================================================
845 //function : AddEdge
846 //purpose  : Creates quadratic or linear edge
847 //=======================================================================
848
849 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
850                                            const SMDS_MeshNode* n2,
851                                            const int            id,
852                                            const bool           force3d)
853 {
854   SMESHDS_Mesh * meshDS = GetMeshDS();
855   
856   SMDS_MeshEdge* edge = 0;
857   if (myCreateQuadratic) {
858     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
859     if(id)
860       edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
861     else
862       edge = meshDS->AddEdge(n1, n2, n12);
863   }
864   else {
865     if(id)
866       edge = meshDS->AddEdgeWithID(n1, n2, id);
867     else
868       edge = meshDS->AddEdge(n1, n2);
869   }
870
871   if ( mySetElemOnShape && myShapeID > 0 )
872     meshDS->SetMeshElementOnShape( edge, myShapeID );
873
874   return edge;
875 }
876
877 //=======================================================================
878 //function : AddFace
879 //purpose  : Creates quadratic or linear triangle
880 //=======================================================================
881
882 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
883                                            const SMDS_MeshNode* n2,
884                                            const SMDS_MeshNode* n3,
885                                            const int id,
886                                            const bool force3d)
887 {
888   SMESHDS_Mesh * meshDS = GetMeshDS();
889   SMDS_MeshFace* elem = 0;
890
891   if( n1==n2 || n2==n3 || n3==n1 )
892     return elem;
893
894   if(!myCreateQuadratic) {
895     if(id)
896       elem = meshDS->AddFaceWithID(n1, n2, n3, id);
897     else
898       elem = meshDS->AddFace(n1, n2, n3);
899   }
900   else {
901     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
902     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
903     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
904
905     if(id)
906       elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
907     else
908       elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
909   }
910   if ( mySetElemOnShape && myShapeID > 0 )
911     meshDS->SetMeshElementOnShape( elem, myShapeID );
912
913   return elem;
914 }
915
916 //=======================================================================
917 //function : AddFace
918 //purpose  : Creates quadratic or linear quadrangle
919 //=======================================================================
920
921 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
922                                            const SMDS_MeshNode* n2,
923                                            const SMDS_MeshNode* n3,
924                                            const SMDS_MeshNode* n4,
925                                            const int            id,
926                                            const bool           force3d)
927 {
928   SMESHDS_Mesh * meshDS = GetMeshDS();
929   SMDS_MeshFace* elem = 0;
930
931   if( n1==n2 ) {
932     return AddFace(n1,n3,n4,id,force3d);
933   }
934   if( n1==n3 ) {
935     return AddFace(n1,n2,n4,id,force3d);
936   }
937   if( n1==n4 ) {
938     return AddFace(n1,n2,n3,id,force3d);
939   }
940   if( n2==n3 ) {
941     return AddFace(n1,n2,n4,id,force3d);
942   }
943   if( n2==n4 ) {
944     return AddFace(n1,n2,n3,id,force3d);
945   }
946   if( n3==n4 ) {
947     return AddFace(n1,n2,n3,id,force3d);
948   }
949
950   if(!myCreateQuadratic) {
951     if(id)
952       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
953     else
954       elem = meshDS->AddFace(n1, n2, n3, n4);
955   }
956   else {
957     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
958     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
959     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
960     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
961
962     if(id)
963       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
964     else
965       elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
966   }
967   if ( mySetElemOnShape && myShapeID > 0 )
968     meshDS->SetMeshElementOnShape( elem, myShapeID );
969
970   return elem;
971 }
972
973 //=======================================================================
974 //function : AddVolume
975 //purpose  : Creates quadratic or linear prism
976 //=======================================================================
977
978 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
979                                                const SMDS_MeshNode* n2,
980                                                const SMDS_MeshNode* n3,
981                                                const SMDS_MeshNode* n4,
982                                                const SMDS_MeshNode* n5,
983                                                const SMDS_MeshNode* n6,
984                                                const int id,
985                                                const bool force3d)
986 {
987   SMESHDS_Mesh * meshDS = GetMeshDS();
988   SMDS_MeshVolume* elem = 0;
989   if(!myCreateQuadratic) {
990     if(id)
991       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
992     else
993       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
994   }
995   else {
996     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
997     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
998     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
999
1000     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1001     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1002     const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1003
1004     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1005     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1006     const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1007
1008     if(id)
1009       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, 
1010                                      n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1011     else
1012       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1013                                n12, n23, n31, n45, n56, n64, n14, n25, n36);
1014   }
1015   if ( mySetElemOnShape && myShapeID > 0 )
1016     meshDS->SetMeshElementOnShape( elem, myShapeID );
1017
1018   return elem;
1019 }
1020
1021 //=======================================================================
1022 //function : AddVolume
1023 //purpose  : Creates quadratic or linear tetrahedron
1024 //=======================================================================
1025
1026 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1027                                                const SMDS_MeshNode* n2,
1028                                                const SMDS_MeshNode* n3,
1029                                                const SMDS_MeshNode* n4,
1030                                                const int id, 
1031                                                const bool force3d)
1032 {
1033   SMESHDS_Mesh * meshDS = GetMeshDS();
1034   SMDS_MeshVolume* elem = 0;
1035   if(!myCreateQuadratic) {
1036     if(id)
1037       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1038     else
1039       elem = meshDS->AddVolume(n1, n2, n3, n4);
1040   }
1041   else {
1042     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1043     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1044     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1045
1046     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1047     const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1048     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1049
1050     if(id)
1051       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1052     else
1053       elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1054   }
1055   if ( mySetElemOnShape && myShapeID > 0 )
1056     meshDS->SetMeshElementOnShape( elem, myShapeID );
1057
1058   return elem;
1059 }
1060
1061 //=======================================================================
1062 //function : AddVolume
1063 //purpose  : Creates quadratic or linear pyramid
1064 //=======================================================================
1065
1066 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1067                                                const SMDS_MeshNode* n2,
1068                                                const SMDS_MeshNode* n3,
1069                                                const SMDS_MeshNode* n4,
1070                                                const SMDS_MeshNode* n5,
1071                                                const int id, 
1072                                                const bool force3d)
1073 {
1074   SMDS_MeshVolume* elem = 0;
1075   if(!myCreateQuadratic) {
1076     if(id)
1077       elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1078     else
1079       elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1080   }
1081   else {
1082     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1083     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1084     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1085     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1086
1087     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1088     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1089     const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1090     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1091
1092     if(id)
1093       elem = GetMeshDS()->AddVolumeWithID ( n1,  n2,  n3,  n4,  n5,
1094                                             n12, n23, n34, n41,
1095                                             n15, n25, n35, n45,
1096                                             id);
1097     else
1098       elem = GetMeshDS()->AddVolume( n1,  n2,  n3,  n4,  n5,
1099                                      n12, n23, n34, n41,
1100                                      n15, n25, n35, n45);
1101   }
1102   if ( mySetElemOnShape && myShapeID > 0 )
1103     GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1104
1105   return elem;
1106 }
1107
1108 //=======================================================================
1109 //function : AddVolume
1110 //purpose  : Creates quadratic or linear hexahedron
1111 //=======================================================================
1112
1113 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1114                                                const SMDS_MeshNode* n2,
1115                                                const SMDS_MeshNode* n3,
1116                                                const SMDS_MeshNode* n4,
1117                                                const SMDS_MeshNode* n5,
1118                                                const SMDS_MeshNode* n6,
1119                                                const SMDS_MeshNode* n7,
1120                                                const SMDS_MeshNode* n8,
1121                                                const int id,
1122                                                const bool force3d)
1123 {
1124   SMESHDS_Mesh * meshDS = GetMeshDS();
1125   SMDS_MeshVolume* elem = 0;
1126   if(!myCreateQuadratic) {
1127     if(id)
1128       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1129     else
1130       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1131   }
1132   else {
1133     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1134     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1135     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1136     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1137
1138     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1139     const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1140     const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1141     const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1142
1143     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1144     const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1145     const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1146     const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1147
1148     if(id)
1149       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1150                                      n12, n23, n34, n41, n56, n67,
1151                                      n78, n85, n15, n26, n37, n48, id);
1152     else
1153       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1154                                n12, n23, n34, n41, n56, n67,
1155                                n78, n85, n15, n26, n37, n48);
1156   }
1157   if ( mySetElemOnShape && myShapeID > 0 )
1158     meshDS->SetMeshElementOnShape( elem, myShapeID );
1159
1160   return elem;
1161 }
1162
1163 //=======================================================================
1164 //function : LoadNodeColumns
1165 //purpose  : Load nodes bound to face into a map of node columns
1166 //=======================================================================
1167
1168 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1169                                          const TopoDS_Face& theFace,
1170                                          const TopoDS_Edge& theBaseEdge,
1171                                          SMESHDS_Mesh*      theMesh)
1172 {
1173   // get vertices of theBaseEdge
1174   TopoDS_Vertex vfb, vlb, vft; // first and last, bottom and top vertices
1175   TopoDS_Edge eFrw = TopoDS::Edge( theBaseEdge.Oriented( TopAbs_FORWARD ));
1176   TopExp::Vertices( eFrw, vfb, vlb );
1177
1178   // find the other edges of theFace and orientation of e1
1179   TopoDS_Edge e1, e2, eTop;
1180   bool rev1, CumOri = false;
1181   TopExp_Explorer exp( theFace, TopAbs_EDGE );
1182   int nbEdges = 0;
1183   for ( ; exp.More(); exp.Next() ) {
1184     if ( ++nbEdges > 4 ) {
1185       return false; // more than 4 edges in theFace
1186     }
1187     TopoDS_Edge e = TopoDS::Edge( exp.Current() );
1188     if ( theBaseEdge.IsSame( e ))
1189       continue;
1190     TopoDS_Vertex vCommon;
1191     if ( !TopExp::CommonVertex( theBaseEdge, e, vCommon ))
1192       eTop = e;
1193     else if ( vCommon.IsSame( vfb )) {
1194       e1 = e;
1195       vft = TopExp::LastVertex( e1, CumOri );
1196       rev1 = vfb.IsSame( vft );
1197       if ( rev1 )
1198         vft = TopExp::FirstVertex( e1, CumOri );
1199     }
1200     else
1201       e2 = e;
1202   }
1203   if ( nbEdges < 4 ) {
1204     return false; // less than 4 edges in theFace
1205   }
1206   if ( e2.IsNull() && vfb.IsSame( vlb ))
1207     e2 = e1;
1208
1209   // submeshes corresponding to shapes
1210   SMESHDS_SubMesh* smFace = theMesh->MeshElements( theFace );
1211   SMESHDS_SubMesh* smb = theMesh->MeshElements( theBaseEdge );
1212   SMESHDS_SubMesh* smt = theMesh->MeshElements( eTop );
1213   SMESHDS_SubMesh* sm1 = theMesh->MeshElements( e1 );
1214   SMESHDS_SubMesh* sm2 = theMesh->MeshElements( e2 );
1215   SMESHDS_SubMesh* smVfb = theMesh->MeshElements( vfb );
1216   SMESHDS_SubMesh* smVlb = theMesh->MeshElements( vlb );
1217   SMESHDS_SubMesh* smVft = theMesh->MeshElements( vft );
1218   if (!smFace || !smb || !smt || !sm1 || !sm2 || !smVfb || !smVlb || !smVft ) {
1219     RETURN_BAD_RESULT( "NULL submesh " <<smFace<<" "<<smb<<" "<<smt<<" "<<
1220                        sm1<<" "<<sm2<<" "<<smVfb<<" "<<smVlb<<" "<<smVft);
1221   }
1222   if ( smb->NbNodes() != smt->NbNodes() || sm1->NbNodes() != sm2->NbNodes() ) {
1223     RETURN_BAD_RESULT(" Diff nb of nodes on opposite edges" );
1224   }
1225   if (smVfb->NbNodes() != 1 || smVlb->NbNodes() != 1 || smVft->NbNodes() != 1) {
1226     RETURN_BAD_RESULT("Empty submesh of vertex");
1227   }
1228   // define whether mesh is quadratic
1229   bool isQuadraticMesh = false;
1230   SMDS_ElemIteratorPtr eIt = smFace->GetElements();
1231   if ( !eIt->more() ) {
1232     RETURN_BAD_RESULT("No elements on the face");
1233   }
1234   const SMDS_MeshElement* e = eIt->next();
1235   isQuadraticMesh = e->IsQuadratic();
1236   
1237   if ( sm1->NbNodes() * smb->NbNodes() != smFace->NbNodes() ) {
1238     // check quadratic case
1239     if ( isQuadraticMesh ) {
1240       // what if there are quadrangles and triangles mixed?
1241 //       int n1 = sm1->NbNodes()/2;
1242 //       int n2 = smb->NbNodes()/2;
1243 //       int n3 = sm1->NbNodes() - n1;
1244 //       int n4 = smb->NbNodes() - n2;
1245 //       int nf = sm1->NbNodes()*smb->NbNodes() - n3*n4;
1246 //       if( nf != smFace->NbNodes() ) {
1247 //         MESSAGE( "Wrong nb face nodes: " <<
1248 //                 sm1->NbNodes()<<" "<<smb->NbNodes()<<" "<<smFace->NbNodes());
1249 //         return false;
1250 //       }
1251     }
1252     else {
1253       RETURN_BAD_RESULT( "Wrong nb face nodes: " <<
1254                          sm1->NbNodes()<<" "<<smb->NbNodes()<<" "<<smFace->NbNodes());
1255     }
1256   }
1257   // IJ size
1258   int vsize = sm1->NbNodes() + 2;
1259   int hsize = smb->NbNodes() + 2;
1260   if(isQuadraticMesh) {
1261     vsize = vsize - sm1->NbNodes()/2 -1;
1262     hsize = hsize - smb->NbNodes()/2 -1;
1263   }
1264
1265   // load nodes from theBaseEdge
1266
1267   std::set<const SMDS_MeshNode*> loadedNodes;
1268   const SMDS_MeshNode* nullNode = 0;
1269
1270   std::vector<const SMDS_MeshNode*> & nVecf = theParam2ColumnMap[ 0.];
1271   nVecf.resize( vsize, nullNode );
1272   loadedNodes.insert( nVecf[ 0 ] = smVfb->GetNodes()->next() );
1273
1274   std::vector<const SMDS_MeshNode*> & nVecl = theParam2ColumnMap[ 1.];
1275   nVecl.resize( vsize, nullNode );
1276   loadedNodes.insert( nVecl[ 0 ] = smVlb->GetNodes()->next() );
1277
1278   double f, l;
1279   BRep_Tool::Range( eFrw, f, l );
1280   double range = l - f;
1281   SMDS_NodeIteratorPtr nIt = smb->GetNodes();
1282   const SMDS_MeshNode* node;
1283   while ( nIt->more() ) {
1284     node = nIt->next();
1285     if(IsMedium(node, SMDSAbs_Edge))
1286       continue;
1287     const SMDS_EdgePosition* pos =
1288       dynamic_cast<const SMDS_EdgePosition*>( node->GetPosition().get() );
1289     if ( !pos ) {
1290       return false;
1291     }
1292     double u = ( pos->GetUParameter() - f ) / range;
1293     std::vector<const SMDS_MeshNode*> & nVec = theParam2ColumnMap[ u ];
1294     nVec.resize( vsize, nullNode );
1295     loadedNodes.insert( nVec[ 0 ] = node );
1296   }
1297   if ( theParam2ColumnMap.size() != hsize ) {
1298     RETURN_BAD_RESULT( "Wrong node positions on theBaseEdge" );
1299   }
1300
1301   // load nodes from e1
1302
1303   std::map< double, const SMDS_MeshNode*> sortedNodes; // sort by param on edge
1304   nIt = sm1->GetNodes();
1305   while ( nIt->more() ) {
1306     node = nIt->next();
1307     if(IsMedium(node))
1308       continue;
1309     const SMDS_EdgePosition* pos =
1310       dynamic_cast<const SMDS_EdgePosition*>( node->GetPosition().get() );
1311     if ( !pos ) {
1312       return false;
1313     }
1314     sortedNodes.insert( std::make_pair( pos->GetUParameter(), node ));
1315   }
1316   loadedNodes.insert( nVecf[ vsize - 1 ] = smVft->GetNodes()->next() );
1317   std::map< double, const SMDS_MeshNode*>::iterator u_n = sortedNodes.begin();
1318   int row  = rev1 ? vsize - 1 : 0;
1319   int dRow = rev1 ? -1 : +1;
1320   for ( ; u_n != sortedNodes.end(); u_n++ ) {
1321     row += dRow;
1322     loadedNodes.insert( nVecf[ row ] = u_n->second );
1323   }
1324
1325   // try to load the rest nodes
1326
1327   // get all faces from theFace
1328   TIDSortedElemSet allFaces, foundFaces;
1329   eIt = smFace->GetElements();
1330   while ( eIt->more() ) {
1331     const SMDS_MeshElement* e = eIt->next();
1332     if ( e->GetType() == SMDSAbs_Face )
1333       allFaces.insert( e );
1334   }
1335   // Starting from 2 neighbour nodes on theBaseEdge, look for a face
1336   // the nodes belong to, and between the nodes of the found face,
1337   // look for a not loaded node considering this node to be the next
1338   // in a column of the starting second node. Repeat, starting
1339   // from nodes next to the previous starting nodes in their columns,
1340   // and so on while a face can be found. Then go the the next pair
1341   // of nodes on theBaseEdge.
1342   TParam2ColumnMap::iterator par_nVec_1 = theParam2ColumnMap.begin();
1343   TParam2ColumnMap::iterator par_nVec_2 = par_nVec_1;
1344   // loop on columns
1345   int col = 0;
1346   for ( par_nVec_2++; par_nVec_2 != theParam2ColumnMap.end(); par_nVec_1++, par_nVec_2++ ) {
1347     col++;
1348     row = 0;
1349     const SMDS_MeshNode* n1 = par_nVec_1->second[ row ];
1350     const SMDS_MeshNode* n2 = par_nVec_2->second[ row ];
1351     const SMDS_MeshElement* face = 0;
1352     bool lastColOnClosedFace = ( nVecf[ row ] == n2 );
1353     do {
1354       // look for a face by 2 nodes
1355       face = SMESH_MeshEditor::FindFaceInSet( n1, n2, allFaces, foundFaces );
1356       if ( face ) {
1357         int nbFaceNodes = face->NbNodes();
1358         if ( face->IsQuadratic() )
1359           nbFaceNodes /= 2;
1360         if ( nbFaceNodes>4 ) {
1361           RETURN_BAD_RESULT(" Too many nodes in a face: " << nbFaceNodes );
1362         }
1363         // look for a not loaded node of the <face>
1364         bool found = false;
1365         const SMDS_MeshNode* n3 = 0; // a node defferent from n1 and n2
1366         for ( int i = 0; i < nbFaceNodes && !found; ++i ) {
1367           node = face->GetNode( i );
1368           found = loadedNodes.insert( node ).second;
1369           if ( !found && node != n1 && node != n2 )
1370             n3 = node;
1371         }
1372         if ( lastColOnClosedFace && row + 1 < vsize ) {
1373           node = nVecf[ row + 1 ];
1374           found = ( face->GetNodeIndex( node ) >= 0 );
1375         }
1376         if ( found ) {
1377           if ( ++row > vsize - 1 ) {
1378             RETURN_BAD_RESULT( "Too many nodes in column "<< col <<": "<< row+1);
1379           }
1380           par_nVec_2->second[ row ] = node;
1381           foundFaces.insert( face );
1382           n2 = node;
1383           if ( nbFaceNodes==4 ) {
1384             n1 = par_nVec_1->second[ row ];
1385           }
1386         }
1387         else if ( nbFaceNodes==3 && n3 == par_nVec_1->second[ row + 1 ] ) {
1388           n1 = n3;
1389         }
1390         else  {
1391           RETURN_BAD_RESULT( "Not quad mesh, column "<< col );
1392         }
1393       }
1394     }
1395     while ( face && n1 && n2 );
1396
1397     if ( row < vsize - 1 ) {
1398       MESSAGE( "Too few nodes in column "<< col <<": "<< row+1);
1399       MESSAGE( "Base node 1: "<< par_nVec_1->second[0]);
1400       MESSAGE( "Base node 2: "<< par_nVec_2->second[0]);
1401       if ( n1 ) { MESSAGE( "Current node 1: "<< n1); }
1402       else      { MESSAGE( "Current node 1: NULL");  }
1403       if ( n2 ) { MESSAGE( "Current node 2: "<< n2); }
1404       else      { MESSAGE( "Current node 2: NULL");  }
1405       MESSAGE( "first base node: "<< theParam2ColumnMap.begin()->second[0]);
1406       MESSAGE( "last base node: "<< theParam2ColumnMap.rbegin()->second[0]);
1407       return false;
1408     }
1409   } // loop on columns
1410
1411   return true;
1412 }
1413
1414 //=======================================================================
1415 //function : NbAncestors
1416 //purpose  : Return number of unique ancestors of the shape
1417 //=======================================================================
1418
1419 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1420                                     const SMESH_Mesh&   mesh,
1421                                     TopAbs_ShapeEnum    ancestorType/*=TopAbs_SHAPE*/)
1422 {
1423   TopTools_MapOfShape ancestors;
1424   TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1425   for ( ; ansIt.More(); ansIt.Next() ) {
1426     if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1427       ancestors.Add( ansIt.Value() );
1428   }
1429   return ancestors.Extent();
1430 }
1431
1432 //=======================================================================
1433 //function : GetSubShapeOri
1434 //purpose  : Return orientation of sub-shape in the main shape
1435 //=======================================================================
1436
1437 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
1438                                                       const TopoDS_Shape& subShape)
1439 {
1440   TopAbs_Orientation ori = TopAbs_Orientation(-1);
1441   if ( !shape.IsNull() && !subShape.IsNull() )
1442   {
1443     TopExp_Explorer e( shape, subShape.ShapeType() );
1444     if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
1445       e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
1446     for ( ; e.More(); e.Next())
1447       if ( subShape.IsSame( e.Current() ))
1448         break;
1449     if ( e.More() )
1450       ori = e.Current().Orientation();
1451   }
1452   return ori;
1453 }
1454
1455 //=======================================================================
1456 //function : IsSubShape
1457 //purpose  : 
1458 //=======================================================================
1459
1460 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
1461                                      const TopoDS_Shape& mainShape )
1462 {
1463   if ( !shape.IsNull() && !mainShape.IsNull() )
1464   {
1465     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1466           exp.More();
1467           exp.Next() )
1468       if ( shape.IsSame( exp.Current() ))
1469         return true;
1470   }
1471   SCRUTE((shape.IsNull()));
1472   SCRUTE((mainShape.IsNull()));
1473   return false;
1474 }
1475
1476 //=======================================================================
1477 //function : IsSubShape
1478 //purpose  : 
1479 //=======================================================================
1480
1481 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
1482 {
1483   if ( shape.IsNull() || !aMesh )
1484     return false;
1485   return
1486     aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1487     // PAL16202
1488     shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape );
1489 }
1490
1491 //=======================================================================
1492 //function : IsQuadraticMesh
1493 //purpose  : Check mesh without geometry for: if all elements on this shape are quadratic,
1494 //           quadratic elements will be created.
1495 //           Used then generated 3D mesh without geometry.
1496 //=======================================================================
1497
1498 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1499 {
1500   int NbAllEdgsAndFaces=0;
1501   int NbQuadFacesAndEdgs=0;
1502   int NbFacesAndEdges=0;
1503   //All faces and edges
1504   NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
1505   
1506   //Quadratic faces and edges
1507   NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
1508
1509   //Linear faces and edges
1510   NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
1511   
1512   if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
1513     //Quadratic mesh
1514     return SMESH_MesherHelper::QUADRATIC;
1515   }
1516   else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
1517     //Linear mesh
1518     return SMESH_MesherHelper::LINEAR;
1519   }
1520   else
1521     //Mesh with both type of elements
1522     return SMESH_MesherHelper::COMP;
1523 }
1524
1525 //=======================================================================
1526 //function : GetOtherParam
1527 //purpose  : Return an alternative parameter for a node on seam
1528 //=======================================================================
1529
1530 double SMESH_MesherHelper::GetOtherParam(const double param) const
1531 {
1532   int i = myParIndex & U_periodic ? 0 : 1;
1533   return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
1534 }
1535
1536 //=======================================================================
1537 namespace { // Structures used by FixQuadraticElements()
1538 //=======================================================================
1539
1540 #define __DMP__(txt) \
1541 //cout << txt
1542 #define MSG(txt) __DMP__(txt<<endl)
1543 #define MSGBEG(txt) __DMP__(txt)
1544
1545   const double straightTol2 = 1e-33; // to detect straing links
1546
1547   struct QFace;
1548   // ---------------------------------------
1549   /*!
1550    * \brief Quadratic link knowing its faces
1551    */
1552   struct QLink: public SMESH_TLink
1553   {
1554     const SMDS_MeshNode*          _mediumNode;
1555     mutable vector<const QFace* > _faces;
1556     mutable gp_Vec                _nodeMove;
1557     mutable int                   _nbMoves;
1558
1559     QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
1560       SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
1561       _faces.reserve(4);
1562       //if ( MediumPos() != SMDS_TOP_3DSPACE )
1563         _nodeMove = MediumPnt() - MiddlePnt();
1564     }
1565     void SetContinuesFaces() const;
1566     const QFace* GetContinuesFace( const QFace* face ) const;
1567     bool OnBoundary() const;
1568     gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
1569     gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
1570
1571     SMDS_TypeOfPosition MediumPos() const
1572     { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
1573     SMDS_TypeOfPosition EndPos(bool isSecond) const
1574     { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
1575     const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
1576     { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
1577
1578     void Move(const gp_Vec& move, bool sum=false) const
1579     { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
1580     gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
1581     bool IsMoved() const { return (_nbMoves > 0 && !IsStraight()); }
1582     bool IsStraight() const { return _nodeMove.SquareMagnitude() <= straightTol2; }
1583
1584     bool operator<(const QLink& other) const {
1585       return (node1()->GetID() == other.node1()->GetID() ?
1586               node2()->GetID() < other.node2()->GetID() :
1587               node1()->GetID() < other.node1()->GetID());
1588     }
1589     struct PtrComparator {
1590       bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
1591     };
1592   };
1593   // ---------------------------------------------------------
1594   /*!
1595    * \brief Link in the chain of links; it connects two faces
1596    */
1597   struct TChainLink
1598   {
1599     const QLink*         _qlink;
1600     mutable const QFace* _qfaces[2];
1601
1602     TChainLink(const QLink* qlink=0):_qlink(qlink) {
1603       _qfaces[0] = _qfaces[1] = 0;
1604     }
1605     void SetFace(const QFace* face) { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
1606
1607     bool IsBoundary() const { return !_qfaces[1]; }
1608
1609     void RemoveFace( const QFace* face ) const
1610     { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
1611
1612     const QFace* NextFace( const QFace* f ) const
1613     { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
1614
1615     const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
1616     { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
1617
1618     bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
1619
1620     operator bool() const { return (_qlink); }
1621
1622     const QLink* operator->() const { return _qlink; }
1623
1624     gp_Vec Normal() const;
1625   };
1626   // --------------------------------------------------------------------
1627   typedef list< TChainLink > TChain;
1628   typedef set < TChainLink > TLinkSet;
1629   typedef TLinkSet::const_iterator TLinkInSet;
1630
1631   const int theFirstStep = 5;
1632
1633   enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
1634   // --------------------------------------------------------------------
1635   /*!
1636    * \brief Face shared by two volumes and bound by QLinks
1637    */
1638   struct QFace: public TIDSortedElemSet
1639   {
1640     mutable const SMDS_MeshElement* _volumes[2];
1641     mutable vector< const QLink* >  _sides;
1642     mutable bool                    _sideIsAdded[4]; // added in chain of links
1643     gp_Vec                          _normal;
1644 #ifdef _DEBUG_
1645     mutable const SMDS_MeshElement* _face;
1646 #endif
1647
1648     QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
1649
1650     void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
1651
1652     int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
1653
1654     void AddSelfToLinks() const {
1655       for ( int i = 0; i < _sides.size(); ++i )
1656         _sides[i]->_faces.push_back( this );
1657     }
1658     int LinkIndex( const QLink* side ) const {
1659       for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
1660       return -1;
1661     }
1662     bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
1663
1664     bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
1665     {
1666       int i = LinkIndex( link._qlink );
1667       if ( i < 0 ) return true;
1668       _sideIsAdded[i] = true;
1669       link.SetFace( this );
1670       // continue from opposite link
1671       return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
1672     }
1673     bool IsBoundary() const { return !_volumes[1]; }
1674
1675     bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
1676
1677     TLinkInSet GetBoundaryLink( const TLinkSet&      links,
1678                                 const TChainLink&    avoidLink,
1679                                 TLinkInSet *         notBoundaryLink = 0,
1680                                 const SMDS_MeshNode* nodeToContain = 0,
1681                                 bool *               isAdjacentUsed = 0,
1682                                 int                  nbRecursionsLeft = -1) const;
1683
1684     TLinkInSet GetLinkByNode( const TLinkSet&      links,
1685                               const TChainLink&    avoidLink,
1686                               const SMDS_MeshNode* nodeToContain) const;
1687
1688     const SMDS_MeshNode* GetNodeInFace() const {
1689       for ( int iL = 0; iL < _sides.size(); ++iL )
1690         if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
1691       return 0;
1692     }
1693
1694     gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
1695
1696     double MoveByBoundary( const TChainLink&   theLink,
1697                            const gp_Vec&       theRefVec,
1698                            const TLinkSet&     theLinks,
1699                            SMESH_MesherHelper* theFaceHelper=0,
1700                            const double        thePrevLen=0,
1701                            const int           theStep=theFirstStep,
1702                            gp_Vec*             theLinkNorm=0,
1703                            double              theSign=1.0) const;
1704   };
1705
1706   //================================================================================
1707   /*!
1708    * \brief Dump QLink and QFace
1709    */
1710   ostream& operator << (ostream& out, const QLink& l)
1711   {
1712     out <<"QLink nodes: "
1713         << l.node1()->GetID() << " - "
1714         << l._mediumNode->GetID() << " - "
1715         << l.node2()->GetID() << endl;
1716     return out;
1717   }
1718   ostream& operator << (ostream& out, const QFace& f)
1719   {
1720     out <<"QFace nodes: "/*<< &f << "  "*/;
1721     for ( TIDSortedElemSet::const_iterator n = f.begin(); n != f.end(); ++n )
1722       out << (*n)->GetID() << " ";
1723     out << " \tvolumes: "
1724         << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
1725         << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
1726     out << "  \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
1727     return out;
1728   }
1729
1730   //================================================================================
1731   /*!
1732    * \brief Construct QFace from QLinks 
1733    */
1734   //================================================================================
1735
1736   QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
1737   {
1738     _volumes[0] = _volumes[1] = 0;
1739     _sides = links;
1740     _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
1741     _normal.SetCoord(0,0,0);
1742     for ( int i = 1; i < _sides.size(); ++i ) {
1743       const QLink *l1 = _sides[i-1], *l2 = _sides[i];
1744       insert( l1->node1() ); insert( l1->node2() );
1745       // compute normal
1746       gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
1747       gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
1748       if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
1749         v1.Reverse(); 
1750       _normal += v1 ^ v2;
1751     }
1752     double normSqSize = _normal.SquareMagnitude();
1753     if ( normSqSize > numeric_limits<double>::min() )
1754       _normal /= sqrt( normSqSize );
1755     else
1756       _normal.SetCoord(1e-33,0,0);
1757
1758 #ifdef _DEBUG_
1759     _face = face;
1760 #endif
1761   }
1762   //================================================================================
1763   /*!
1764    * \brief Make up chain of links
1765    *  \param iSide - link to add first
1766    *  \param chain - chain to fill in
1767    *  \param pos   - postion of medium nodes the links should have
1768    *  \param error - out, specifies what is wrong
1769    *  \retval bool - false if valid chain can't be built; "valid" means that links
1770    *                 of the chain belongs to rectangles bounding hexahedrons
1771    */
1772   //================================================================================
1773
1774   bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
1775   {
1776     if ( iSide >= _sides.size() ) // wrong argument iSide
1777       return false;
1778     if ( _sideIsAdded[ iSide ]) // already in chain
1779       return true;
1780
1781     if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
1782       MSGBEG( *this );
1783       list< const QFace* > faces( 1, this );
1784       for (list< const QFace* >::iterator fIt = faces.begin(); fIt != faces.end(); ++fIt ) {
1785         const QFace* face = *fIt;
1786         for ( int i = 0; i < face->_sides.size(); ++i ) {
1787           if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
1788             face->_sideIsAdded[i] = true;
1789             TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
1790             chLink->SetFace( face );
1791             if ( face->_sides[i]->MediumPos() >= pos )
1792               if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
1793                 faces.push_back( contFace );
1794           }
1795         }
1796       }
1797       if ( error < ERR_TRI )
1798         error = ERR_TRI;
1799       return false;
1800     }
1801     _sideIsAdded[iSide] = true; // not to add this link to chain again
1802     const QLink* link = _sides[iSide];
1803     if ( !link)
1804       return true;
1805
1806     // add link into chain
1807     TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
1808     chLink->SetFace( this );
1809     MSGBEG( *this );
1810
1811     // propagate from quadrangle to neighbour faces
1812     if ( link->MediumPos() >= pos ) {
1813       int nbLinkFaces = link->_faces.size();
1814       if ( nbLinkFaces == 4 || nbLinkFaces < 4 && link->OnBoundary()) {
1815         // hexahedral mesh or boundary quadrangles - goto a continous face
1816         if ( const QFace* f = link->GetContinuesFace( this ))
1817           return f->GetLinkChain( *chLink, chain, pos, error );
1818       }
1819       else {
1820         TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
1821         for ( int i = 0; i < nbLinkFaces; ++i )
1822           if ( link->_faces[i] )
1823             link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
1824         if ( error < ERR_PRISM )
1825           error = ERR_PRISM;
1826         return false;
1827       }
1828     }
1829     return true;
1830   }
1831
1832   //================================================================================
1833   /*!
1834    * \brief Return a boundary link of the triangle face
1835    *  \param links - set of all links
1836    *  \param avoidLink - link not to return
1837    *  \param notBoundaryLink - out, neither the returned link nor avoidLink
1838    *  \param nodeToContain - node the returned link must contain; if provided, search
1839    *                         also performed on adjacent faces
1840    *  \param isAdjacentUsed - returns true if link is found in adjacent faces
1841    *  \param nbRecursionsLeft - to limit recursion
1842    */
1843   //================================================================================
1844
1845   TLinkInSet QFace::GetBoundaryLink( const TLinkSet&      links,
1846                                      const TChainLink&    avoidLink,
1847                                      TLinkInSet *         notBoundaryLink,
1848                                      const SMDS_MeshNode* nodeToContain,
1849                                      bool *               isAdjacentUsed,
1850                                      int                  nbRecursionsLeft) const
1851   {
1852     TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
1853
1854     typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
1855     TFaceLinkList adjacentFaces;
1856
1857     for ( int iL = 0; iL < _sides.size(); ++iL )
1858     {
1859       if ( avoidLink._qlink == _sides[iL] )
1860         continue;
1861       TLinkInSet link = links.find( _sides[iL] );
1862       if ( link == linksEnd ) continue;
1863       if ( (*link)->MediumPos() > SMDS_TOP_FACE )
1864         continue; // We work on faces here, don't go into a volume
1865
1866       // check link
1867       if ( link->IsBoundary() ) {
1868         if ( !nodeToContain ||
1869              (*link)->node1() == nodeToContain ||
1870              (*link)->node2() == nodeToContain )
1871         {
1872           boundaryLink = link;
1873           if ( !notBoundaryLink ) break;
1874         }
1875       }
1876       else if ( notBoundaryLink ) {
1877         *notBoundaryLink = link;
1878         if ( boundaryLink != linksEnd ) break;
1879       }
1880
1881       if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
1882         if ( const QFace* adj = link->NextFace( this ))
1883           if ( adj->Contains( nodeToContain ))
1884             adjacentFaces.push_back( make_pair( adj, link ));
1885     }
1886
1887     if ( isAdjacentUsed ) *isAdjacentUsed = false;
1888     if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
1889     {
1890       if ( nbRecursionsLeft < 0 )
1891         nbRecursionsLeft = nodeToContain->NbInverseElements();
1892       TFaceLinkList::iterator adj = adjacentFaces.begin();
1893       for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
1894         boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
1895                                                     isAdjacentUsed, nbRecursionsLeft-1);
1896       if ( isAdjacentUsed ) *isAdjacentUsed = true;
1897     }
1898     return boundaryLink;
1899   }
1900   //================================================================================
1901   /*!
1902    * \brief Return a link ending at the given node but not avoidLink
1903    */
1904   //================================================================================
1905
1906   TLinkInSet QFace::GetLinkByNode( const TLinkSet&      links,
1907                                    const TChainLink&    avoidLink,
1908                                    const SMDS_MeshNode* nodeToContain) const
1909   {
1910     for ( int i = 0; i < _sides.size(); ++i )
1911       if ( avoidLink._qlink != _sides[i] &&
1912            (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
1913         return links.find( _sides[ i ]);
1914     return links.end();
1915   }
1916
1917   //================================================================================
1918   /*!
1919    * \brief Return normal to the i-th side pointing outside the face
1920    */
1921   //================================================================================
1922
1923   gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
1924   {
1925     gp_Vec norm, vecOut;
1926 //     if ( uvHelper ) {
1927 //       TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
1928 //       const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
1929 //       gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
1930 //       gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
1931 //       norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
1932
1933 //       const QLink* otherLink = _sides[(i + 1) % _sides.size()];
1934 //       const SMDS_MeshNode* otherNode =
1935 //         otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
1936 //       gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
1937 //       vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
1938 //     }
1939 //     else {
1940       norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
1941       gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
1942                      XYZ( _sides[0]->node2() ) +
1943                      XYZ( _sides[1]->node1() )) / 3.;
1944       vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
1945       //}
1946     if ( norm * vecOut < 0 )
1947       norm.Reverse();
1948     double mag2 = norm.SquareMagnitude();
1949     if ( mag2 > numeric_limits<double>::min() )
1950       norm /= sqrt( mag2 );
1951     return norm;
1952   }
1953   //================================================================================
1954   /*!
1955    * \brief Move medium node of theLink according to its distance from boundary
1956    *  \param theLink - link to fix
1957    *  \param theRefVec - movement of boundary
1958    *  \param theLinks - all adjacent links of continous triangles
1959    *  \param theFaceHelper - helper is not used so far
1960    *  \param thePrevLen - distance from the boundary
1961    *  \param theStep - number of steps till movement propagation limit
1962    *  \param theLinkNorm - out normal to theLink
1963    *  \param theSign - 1 or -1 depending on movement of boundary
1964    *  \retval double - distance from boundary to propagation limit or other boundary
1965    */
1966   //================================================================================
1967
1968   double QFace::MoveByBoundary( const TChainLink&   theLink,
1969                                 const gp_Vec&       theRefVec,
1970                                 const TLinkSet&     theLinks,
1971                                 SMESH_MesherHelper* theFaceHelper,
1972                                 const double        thePrevLen,
1973                                 const int           theStep,
1974                                 gp_Vec*             theLinkNorm,
1975                                 double              theSign) const
1976   {
1977     if ( !theStep )
1978       return thePrevLen; // propagation limit reached
1979
1980     int iL; // index of theLink
1981     for ( iL = 0; iL < _sides.size(); ++iL )
1982       if ( theLink._qlink == _sides[ iL ])
1983         break;
1984
1985     MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
1986         <<" thePrevLen " << thePrevLen);
1987     MSG(string(theStep,'.')<<" "<<*theLink._qlink);
1988
1989     gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
1990     double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
1991     if ( theStep == theFirstStep )
1992       theSign = refProj < 0. ? -1. : 1.;
1993     else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
1994       return thePrevLen; // to propagate movement forward only, not in side dir or backward
1995
1996     int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
1997     TLinkInSet link1 = theLinks.find( _sides[iL1] );
1998     TLinkInSet link2 = theLinks.find( _sides[iL2] );
1999     if ( link1 == theLinks.end() || link2 == theLinks.end() )
2000       return thePrevLen;
2001     const QFace* f1 = link1->NextFace( this ); // adjacent faces
2002     const QFace* f2 = link2->NextFace( this );
2003
2004     // propagate to adjacent faces till limit step or boundary
2005     double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2006     double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2007     gp_Vec linkDir1, linkDir2;
2008     try {
2009       OCC_CATCH_SIGNALS;
2010       if ( f1 )
2011         len1 = f1->MoveByBoundary
2012           ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2013       else
2014         linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2015     } catch (...) {
2016       MSG( " --------------- EXCEPTION");
2017       return thePrevLen;
2018     }
2019     try {
2020       OCC_CATCH_SIGNALS;
2021       if ( f2 )
2022         len2 = f2->MoveByBoundary
2023           ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2024       else
2025         linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2026     } catch (...) {
2027       MSG( " --------------- EXCEPTION");
2028       return thePrevLen;
2029     }
2030
2031     double fullLen = 0;
2032     if ( theStep != theFirstStep )
2033     {
2034       // choose chain length by direction of propagation most codirected with theRefVec
2035       bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2036       fullLen = choose1 ? len1 : len2;
2037       double r = thePrevLen / fullLen;
2038
2039       gp_Vec move = linkNorm * refProj * ( 1 - r );
2040       theLink->Move( move, true );
2041
2042       MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2043           " by " << refProj * ( 1 - r ) << " following " <<
2044           (choose1 ? *link1->_qlink : *link2->_qlink));
2045
2046       if ( theLinkNorm ) *theLinkNorm = linkNorm;
2047     }
2048     return fullLen;
2049   }
2050
2051   //================================================================================
2052   /*!
2053    * \brief Find pairs of continues faces 
2054    */
2055   //================================================================================
2056
2057   void QLink::SetContinuesFaces() const
2058   {
2059     //       x0         x - QLink, [-|] - QFace, v - volume
2060     //   v0  |   v1   
2061     //       |          Between _faces of link x2 two vertical faces are continues
2062     // x1----x2-----x3  and two horizontal faces are continues. We set vertical faces
2063     //       |          to _faces[0] and _faces[1] and horizontal faces to
2064     //   v2  |   v3     _faces[2] and _faces[3] (or vise versa).
2065     //       x4
2066
2067     if ( _faces.empty() )
2068       return;
2069     int iFaceCont = -1;
2070     for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2071     {
2072       // look for a face bounding none of volumes bound by _faces[0]
2073       bool sameVol = false;
2074       int nbVol = _faces[iF]->NbVolumes();
2075       for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2076         sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2077                     _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2078       if ( !sameVol )
2079         iFaceCont = iF;
2080     }
2081     if ( iFaceCont > 0 ) // continues faces found, set one by the other
2082     {
2083       if ( iFaceCont != 1 )
2084         std::swap( _faces[1], _faces[iFaceCont] );
2085     }
2086     else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2087     {
2088       _faces.insert( ++_faces.begin(), 0 );
2089     }
2090   }
2091   //================================================================================
2092   /*!
2093    * \brief Return a face continues to the given one
2094    */
2095   //================================================================================
2096
2097   const QFace* QLink::GetContinuesFace( const QFace* face ) const
2098   {
2099     for ( int i = 0; i < _faces.size(); ++i ) {
2100       if ( _faces[i] == face ) {
2101         int iF = i < 2 ? 1-i : 5-i;
2102         return iF < _faces.size() ? _faces[iF] : 0;
2103       }
2104     }
2105     return 0;
2106   }
2107   //================================================================================
2108   /*!
2109    * \brief True if link is on mesh boundary
2110    */
2111   //================================================================================
2112
2113   bool QLink::OnBoundary() const
2114   {
2115     for ( int i = 0; i < _faces.size(); ++i )
2116       if (_faces[i] && _faces[i]->IsBoundary()) return true;
2117     return false;
2118   }
2119   //================================================================================
2120   /*!
2121    * \brief Return normal of link of the chain
2122    */
2123   //================================================================================
2124
2125   gp_Vec TChainLink::Normal() const {
2126     gp_Vec norm;
2127     if (_qfaces[0]) norm  = _qfaces[0]->_normal;
2128     if (_qfaces[1]) norm += _qfaces[1]->_normal;
2129     return norm;
2130   }
2131   //================================================================================
2132   /*!
2133    * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
2134    */
2135   //================================================================================
2136
2137   void fixPrism( TChain& allLinks )
2138   {
2139     // separate boundary links from internal ones
2140     typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
2141     QLinkSet interLinks, bndLinks1, bndLink2;
2142
2143     bool isCurved = false;
2144     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2145       if ( (*lnk)->OnBoundary() )
2146         bndLinks1.insert( lnk->_qlink );
2147       else
2148         interLinks.insert( lnk->_qlink );
2149       isCurved = isCurved || !(*lnk)->IsStraight();
2150     }
2151     if ( !isCurved )
2152       return; // no need to move
2153
2154     QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
2155
2156     while ( !interLinks.empty() && !curBndLinks->empty() )
2157     {
2158       // propagate movement from boundary links to connected internal links
2159       QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
2160       for ( ; bnd != bndEnd; ++bnd )
2161       {
2162         const QLink* bndLink = *bnd;
2163         for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
2164         {
2165           const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
2166           if ( !face ) continue;
2167           // find and move internal link opposite to bndLink within the face
2168           int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
2169           const QLink* interLink = face->_sides[ interInd ];
2170           QLinkSet::iterator pInterLink = interLinks.find( interLink );
2171           if ( pInterLink == interLinks.end() ) continue; // not internal link
2172           interLink->Move( bndLink->_nodeMove );
2173           // treated internal links become new boundary ones
2174           interLinks. erase( pInterLink );
2175           newBndLinks->insert( interLink );
2176         }
2177       }
2178       curBndLinks->clear();
2179       std::swap( curBndLinks, newBndLinks );
2180     }
2181   }
2182
2183   //================================================================================
2184   /*!
2185    * \brief Fix links of continues triangles near curved boundary
2186    */
2187   //================================================================================
2188
2189   void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2190   {
2191     if ( allLinks.empty() ) return;
2192
2193     TLinkSet linkSet( allLinks.begin(), allLinks.end());
2194     TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2195
2196     // move in 2d if we are on geom face
2197 //     TopoDS_Face face;
2198 //     TopLoc_Location loc;
2199 //     SMESH_MesherHelper faceHelper( *helper.GetMesh());
2200 //     while ( linkIt->IsBoundary()) ++linkIt;
2201 //     if ( linkIt == linksEnd ) return;
2202 //     if ( (*linkIt)->MediumPos() == SMDS_TOP_FACE ) {
2203 //       bool checkPos = true;
2204 //       TopoDS_Shape f = helper.GetSubShapeByNode( (*linkIt)->_mediumNode, helper.GetMeshDS() );
2205 //       if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE ) {
2206 //         face = TopoDS::Face( f );
2207 //         helper.GetNodeUV( face, (*linkIt)->_mediumNode, 0, &checkPos);
2208 //         if (checkPos)
2209 //           face.Nullify();
2210 //         else
2211 //           faceHelper.SetSubShape( face );
2212 //       }
2213 //     }
2214     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2215     {
2216       if ( linkIt->IsBoundary() && !(*linkIt)->IsStraight() && linkIt->_qfaces[0])
2217       {
2218 //         if ( !face.IsNull() ) {
2219 //           const SMDS_MeshNode* inFaceNode =
2220 //             faceHelper.GetNodeUVneedInFaceNode() ? linkIt->_qfaces[0]->GetNodeInFace() : 0;
2221 //           gp_XY uvm = helper.GetNodeUV( face, (*linkIt)->_mediumNode, inFaceNode );
2222 //           gp_XY uv1 = helper.GetNodeUV( face, (*linkIt)->node1(), inFaceNode);
2223 //           gp_XY uv2 = helper.GetNodeUV( face, (*linkIt)->node2(), inFaceNode);
2224 //           gp_XY uvMove = uvm - helper.GetMiddleUV( BRep_Tool::Surface(face,loc), uv1, uv2);
2225 //           gp_Vec move( uvMove.X(), uvMove.Y(), 0 );
2226 //           linkIt->_qfaces[0]->MoveByBoundary( *linkIt, move, linkSet, &faceHelper );
2227 //         }
2228 //         else {
2229           linkIt->_qfaces[0]->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2230           //}
2231       }
2232     }
2233   }
2234
2235   //================================================================================
2236   /*!
2237    * \brief Detect rectangular structure of links and build chains from them
2238    */
2239   //================================================================================
2240
2241   enum TSplitTriaResult {
2242     _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2243     _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK };
2244
2245   TSplitTriaResult splitTrianglesIntoChains( TChain &            allLinks,
2246                                              vector< TChain> &   resultChains,
2247                                              SMDS_TypeOfPosition pos )
2248   {
2249     // put links in the set and evalute number of result chains by number of boundary links
2250     TLinkSet linkSet;
2251     int nbBndLinks = 0;
2252     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2253       linkSet.insert( *lnk );
2254       nbBndLinks += lnk->IsBoundary();
2255     }
2256     resultChains.clear();
2257     resultChains.reserve( nbBndLinks / 2 );
2258
2259     TLinkInSet linkIt, linksEnd = linkSet.end();
2260
2261     // find a boundary link with corner node; corner node has position pos-2
2262     // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2263     // links in volume
2264     SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2265     const SMDS_MeshNode* corner = 0;
2266     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2267       if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2268         break;
2269     if ( !corner)
2270       return _NO_CORNERS;
2271
2272     TLinkInSet           startLink = linkIt;
2273     const SMDS_MeshNode* startCorner = corner;
2274     vector< TChain* >    rowChains;
2275     int iCol = 0;
2276
2277     while ( startLink != linksEnd) // loop on columns
2278     {
2279       // We suppose we have a rectangular structure like shown here. We have found a
2280       //               corner of the rectangle (startCorner) and a boundary link sharing  
2281       //    |/  |/  |  the startCorner (startLink). We are going to loop on rows of the   
2282       //  --o---o---o  structure making several chains at once. One chain (columnChain)   
2283       //    |\  |  /|  starts at startLink and continues upward (we look at the structure 
2284       //  \ | \ | / |  from such point that startLink is on the bottom of the structure). 
2285       //   \|  \|/  |  While going upward we also fill horizontal chains (rowChains) we   
2286       //  --o---o---o  encounter.                                                         
2287       //   /|\  |\  |
2288       //  / | \ | \ |  startCorner
2289       //    |  \|  \|,'
2290       //  --o---o---o
2291       //          `.startLink
2292
2293       if ( resultChains.size() == nbBndLinks / 2 )
2294         return _NOT_RECT;
2295       resultChains.push_back( TChain() );
2296       TChain& columnChain = resultChains.back();
2297
2298       TLinkInSet botLink = startLink; // current horizontal link to go up from
2299       corner = startCorner; // current corner the botLink ends at
2300       int iRow = 0;
2301       while ( botLink != linksEnd ) // loop on rows
2302       {
2303         // add botLink to the columnChain
2304         columnChain.push_back( *botLink );
2305
2306         const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2307         if ( !botTria )
2308         { // the column ends
2309           linkSet.erase( botLink );
2310           if ( iRow != rowChains.size() )
2311             return _FEW_ROWS; // different nb of rows in columns
2312           break;
2313         }
2314         // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2315         // link ending at <corner> (sideLink); there are two cases:
2316         // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2317         //   since midQuadLink is not at boundary while sideLink is.
2318         // 2) midQuadLink ends at <corner>
2319         bool isCase2;
2320         TLinkInSet midQuadLink = linksEnd;
2321         TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2322                                                         corner, &isCase2 );
2323         if ( isCase2 ) { // find midQuadLink among links of botTria
2324           midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2325           if ( midQuadLink->IsBoundary() )
2326             return _BAD_MIDQUAD;
2327         }
2328         if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2329           return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2330
2331         // fill chains
2332         columnChain.push_back( *midQuadLink );
2333         if ( iRow >= rowChains.size() ) {
2334           if ( iCol > 0 )
2335             return _MANY_ROWS; // different nb of rows in columns
2336           if ( resultChains.size() == nbBndLinks / 2 )
2337             return _NOT_RECT;
2338           resultChains.push_back( TChain() );
2339           rowChains.push_back( & resultChains.back() );
2340         }
2341         rowChains[iRow]->push_back( *sideLink );
2342         rowChains[iRow]->push_back( *midQuadLink );
2343
2344         const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2345         if ( !upTria)
2346           return _NO_UPTRIA;
2347         if ( iRow == 0 ) {
2348           // prepare startCorner and startLink for the next column
2349           startCorner = startLink->NextNode( startCorner );
2350           if (isCase2)
2351             startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2352           else
2353             startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2354           // check if no more columns remains
2355           if ( startLink != linksEnd ) {
2356             const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
2357             if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
2358               startLink = linksEnd; // startLink bounds upTria or botTria
2359             else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
2360               return _BAD_START;
2361           }
2362         }
2363         // find bottom link and corner for the next row
2364         corner = sideLink->NextNode( corner );
2365         // next bottom link ends at the new corner
2366         linkSet.erase( botLink );
2367         botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
2368         if ( botLink == linksEnd || botLink == (isCase2 ? midQuadLink : sideLink))
2369           return _NO_BOTLINK;
2370         linkSet.erase( midQuadLink );
2371         linkSet.erase( sideLink );
2372
2373         // make faces neighboring the found ones be boundary
2374         if ( startLink != linksEnd ) {
2375           const QFace* tria = isCase2 ? botTria : upTria;
2376           for ( int iL = 0; iL < 3; ++iL ) {
2377             linkIt = linkSet.find( tria->_sides[iL] );
2378             if ( linkIt != linksEnd )
2379               linkIt->RemoveFace( tria );
2380           }
2381         }
2382         if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
2383           botLink->RemoveFace( upTria ); // make next botTria first in vector
2384
2385         iRow++;
2386       } // loop on rows
2387
2388       iCol++;
2389     }
2390     // In the linkSet, there must remain the last links of rowChains; add them
2391     if ( linkSet.size() != rowChains.size() )
2392       return _BAD_SET_SIZE;
2393     for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
2394       // find the link (startLink) ending at startCorner
2395       corner = 0;
2396       for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
2397         if ( (*startLink)->node1() == startCorner ) {
2398           corner = (*startLink)->node2(); break;
2399         }
2400         else if ( (*startLink)->node2() == startCorner) {
2401           corner = (*startLink)->node1(); break;
2402         }
2403       }
2404       if ( startLink == linksEnd )
2405         return _BAD_CORNER;
2406       rowChains[ iRow ]->push_back( *startLink );
2407       linkSet.erase( startLink );
2408       startCorner = corner;
2409     }
2410
2411     return _OK;
2412   }
2413 }
2414
2415 //=======================================================================
2416 /*!
2417  * \brief Move medium nodes of faces and volumes to fix distorted elements
2418  * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
2419  * 
2420  * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
2421  */
2422 //=======================================================================
2423
2424 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
2425 {
2426   // apply algorithm to solids or geom faces
2427   // ----------------------------------------------
2428   if ( myShape.IsNull() ) {
2429     if ( !myMesh->HasShapeToMesh() ) return;
2430     SetSubShape( myMesh->GetShapeToMesh() );
2431
2432     TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
2433     for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
2434       faces.Add( f.Current() );
2435     }
2436     for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
2437       if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
2438         for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
2439           faces.Add( f.Current() );
2440       }
2441       else { // fix nodes in the solid and its faces
2442         SMESH_MesherHelper h(*myMesh);
2443         h.SetSubShape( s.Current() );
2444         h.FixQuadraticElements(false);
2445       }
2446     }
2447     // fix nodes on geom faces
2448     for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
2449       SMESH_MesherHelper h(*myMesh);
2450       h.SetSubShape( fIt.Key() );
2451       h.FixQuadraticElements(true);
2452     }
2453     return;
2454   }
2455
2456   // Find out type of elements and get iterator on them
2457   // ---------------------------------------------------
2458
2459   SMDS_ElemIteratorPtr elemIt;
2460   SMDSAbs_ElementType elemType = SMDSAbs_All;
2461
2462   SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
2463   if ( !submesh )
2464     return;
2465   if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
2466     elemIt = smDS->GetElements();
2467     if ( elemIt->more() ) {
2468       elemType = elemIt->next()->GetType();
2469       elemIt = smDS->GetElements();
2470     }
2471   }
2472   if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
2473     return;
2474
2475   // Fill in auxiliary data structures
2476   // ----------------------------------
2477
2478   set< QLink > links;
2479   set< QFace > faces;
2480   set< QLink >::iterator pLink;
2481   set< QFace >::iterator pFace;
2482
2483   bool isCurved = false;
2484   bool hasRectFaces = false;
2485   set<int> nbElemNodeSet;
2486
2487   if ( elemType == SMDSAbs_Volume )
2488   {
2489     SMDS_VolumeTool volTool;
2490     while ( elemIt->more() ) // loop on volumes
2491     {
2492       const SMDS_MeshElement* vol = elemIt->next();
2493       if ( !vol->IsQuadratic() || !volTool.Set( vol ))
2494         return; //continue;
2495       for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
2496       {
2497         int nbN = volTool.NbFaceNodes( iF );
2498         nbElemNodeSet.insert( nbN );
2499         const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
2500         vector< const QLink* > faceLinks( nbN/2 );
2501         for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
2502         {
2503           // store QLink
2504           QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
2505           pLink = links.insert( link ).first;
2506           faceLinks[ iN/2 ] = & *pLink;
2507           if ( !isCurved )
2508             isCurved = !link.IsStraight();
2509           if ( link.MediumPos() == SMDS_TOP_3DSPACE && !link.IsStraight() )
2510             return; // already fixed
2511         }
2512         // store QFace
2513         pFace = faces.insert( QFace( faceLinks )).first;
2514         if ( pFace->NbVolumes() == 0 )
2515           pFace->AddSelfToLinks();
2516         pFace->SetVolume( vol );
2517         hasRectFaces = hasRectFaces ||
2518           ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
2519             volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
2520 #ifdef _DEBUG_
2521         if ( nbN == 6 )
2522           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
2523         else
2524           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
2525                                                faceNodes[4],faceNodes[6] );
2526 #endif
2527       }
2528     }
2529     set< QLink >::iterator pLink = links.begin();
2530     for ( ; pLink != links.end(); ++pLink )
2531       pLink->SetContinuesFaces();
2532   }
2533   else
2534   {
2535     while ( elemIt->more() ) // loop on faces
2536     {
2537       const SMDS_MeshElement* face = elemIt->next();
2538       if ( !face->IsQuadratic() )
2539         continue;
2540       nbElemNodeSet.insert( face->NbNodes() );
2541       int nbN = face->NbNodes()/2;
2542       vector< const QLink* > faceLinks( nbN );
2543       for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
2544       {
2545         // store QLink
2546         QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
2547         pLink = links.insert( link ).first;
2548         faceLinks[ iN ] = & *pLink;
2549         if ( !isCurved )
2550           isCurved = !link.IsStraight();
2551       }
2552       // store QFace
2553       pFace = faces.insert( QFace( faceLinks )).first;
2554       pFace->AddSelfToLinks();
2555       hasRectFaces = ( hasRectFaces || nbN == 4 );
2556     }
2557   }
2558   if ( !isCurved )
2559     return; // no curved edges of faces
2560
2561   // Compute displacement of medium nodes
2562   // -------------------------------------
2563
2564   // two loops on faces: the first is to treat boundary links, the second is for internal ones
2565   TopLoc_Location loc;
2566   // not treat boundary of volumic submesh
2567   int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
2568   for ( ; isInside < 2; ++isInside ) {
2569     MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
2570     SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
2571
2572     for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
2573       if ( bool(isInside) == pFace->IsBoundary() )
2574         continue;
2575       for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from quadrangle
2576       {
2577         MSG( "CHAIN");
2578         // make chain of links connected via continues faces
2579         int error = ERR_OK;
2580         TChain rawChain;
2581         if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
2582         rawChain.reverse();
2583         if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
2584
2585         vector< TChain > chains;
2586         if ( error == ERR_OK ) { // chain contains continues rectangles
2587           chains.resize(1);
2588           chains[0].splice( chains[0].begin(), rawChain );
2589         }
2590         else if ( error == ERR_TRI ) {  // chain contains continues triangles
2591           TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
2592           if ( res != _OK ) { // not quadrangles split into triangles
2593             fixTriaNearBoundary( rawChain, *this );
2594             break;
2595           }
2596         }
2597         else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
2598           fixPrism( rawChain );
2599           break;
2600         }
2601         else {
2602           continue;
2603         }
2604         for ( int iC = 0; iC < chains.size(); ++iC )
2605         {
2606           TChain& chain = chains[iC];
2607           if ( chain.empty() ) continue;
2608           if ( chain.front()->IsStraight() && chain.back()->IsStraight() ) {
2609             MSG("3D straight");
2610             continue;
2611           }
2612           // mesure chain length and compute link position along the chain
2613           double chainLen = 0;
2614           vector< double > linkPos;
2615           MSGBEG( "Link medium nodes: ");
2616           TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
2617           for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
2618             MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
2619             double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2620             while ( len < numeric_limits<double>::min() ) { // remove degenerated link
2621               link1 = chain.erase( link1 );
2622               if ( link1 == chain.end() )
2623                 break;
2624               len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2625             }
2626             chainLen += len;
2627             linkPos.push_back( chainLen );
2628           }
2629           MSG("");
2630           if ( linkPos.size() < 2 )
2631             continue;
2632
2633           gp_Vec move0 = chain.front()->_nodeMove;
2634           gp_Vec move1 = chain.back ()->_nodeMove;
2635
2636           TopoDS_Face face;
2637           bool checkUV = true;
2638           if ( !isInside ) {
2639             // compute node displacement of end links in parametric space of face
2640             const SMDS_MeshNode* nodeOnFace = (*(++chain.begin()))->_mediumNode;
2641             TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
2642             if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
2643             {
2644               face = TopoDS::Face( f );
2645               Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
2646               for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
2647               {
2648                 TChainLink& link = is1 ? chain.back() : chain.front();
2649                 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
2650                 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
2651                 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
2652                 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
2653                 // uvMove = uvm - uv12
2654                 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
2655                 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
2656               }
2657               if ( move0.SquareMagnitude() < straightTol2 &&
2658                    move1.SquareMagnitude() < straightTol2 ) {
2659                 MSG("2D straight");
2660                 continue; // straight - no need to move nodes of internal links
2661               }
2662             }
2663           }
2664           gp_Trsf trsf;
2665           if ( isInside || face.IsNull() )
2666           {
2667             // compute node displacement of end links in their local coord systems
2668             {
2669               TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
2670               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
2671                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2672               move0.Transform(trsf);
2673             }
2674             {
2675               TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
2676               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
2677                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2678               move1.Transform(trsf);
2679             }
2680           }
2681           // compute displacement of medium nodes
2682           link2 = chain.begin();
2683           link0 = link2++;
2684           link1 = link2++;
2685           for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
2686           {
2687             double r = linkPos[i] / chainLen;
2688             // displacement in local coord system
2689             gp_Vec move = (1. - r) * move0 + r * move1;
2690             if ( isInside || face.IsNull()) {
2691               // transform to global
2692               gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
2693               gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
2694               gp_Vec x = x01.Normalized() + x12.Normalized();
2695               trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
2696               move.Transform(trsf);
2697             }
2698             else {
2699               // compute 3D displacement by 2D one
2700               Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
2701               gp_XY oldUV   = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
2702               gp_XY newUV   = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
2703               gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
2704               move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
2705 #ifdef _DEBUG_
2706               if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
2707                    move.SquareMagnitude())
2708               {
2709                 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
2710                 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
2711                 MSG( "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
2712                      "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
2713                      "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
2714                      "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
2715               }
2716 #endif
2717             }
2718             (*link1)->Move( move );
2719             MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
2720                  << chain.front()->_mediumNode->GetID() <<"-"
2721                  << chain.back ()->_mediumNode->GetID() <<
2722                  " by " << move.Magnitude());
2723           }
2724         } // loop on chains of links
2725       } // loop on 2 directions of propagation from quadrangle
2726     } // loop on faces
2727   }
2728
2729   // Move nodes
2730   // -----------
2731
2732   for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
2733     if ( pLink->IsMoved() ) {
2734       //gp_Pnt p = pLink->MediumPnt() + pLink->Move();
2735       gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
2736       GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
2737     }
2738   }
2739 }
2740
2741 //=======================================================================
2742 /*!
2743  * \brief Iterator on ancestors of the given type
2744  */
2745 //=======================================================================
2746
2747 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
2748 {
2749   TopTools_ListIteratorOfListOfShape _ancIter;
2750   TopAbs_ShapeEnum                   _type;
2751   TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
2752     : _ancIter( ancestors ), _type( type )
2753   {
2754     if ( _ancIter.More() && _ancIter.Value().ShapeType() != _type ) next();
2755   }
2756   virtual bool more()
2757   {
2758     return _ancIter.More();
2759   }
2760   virtual const TopoDS_Shape* next()
2761   {
2762     const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
2763     if ( _ancIter.More() )
2764       for ( _ancIter.Next();  _ancIter.More(); _ancIter.Next())
2765         if ( _ancIter.Value().ShapeType() == _type )
2766           break;
2767     return s;
2768   }
2769 };
2770
2771 //=======================================================================
2772 /*!
2773  * \brief Return iterator on ancestors of the given type
2774  */
2775 //=======================================================================
2776
2777 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
2778                                                    const SMESH_Mesh&   mesh,
2779                                                    TopAbs_ShapeEnum    ancestorType)
2780 {
2781   return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
2782 }