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