Salome HOME
23514: EDF 16031 - SMESH freezes
[modules/smesh.git] / src / SMESH / SMESH_MesherHelper.cxx
1 // Copyright (C) 2007-2016  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, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // File:      SMESH_MesherHelper.cxx
24 // Created:   15.02.06 15:22:41
25 // Author:    Sergey KUUL
26 //
27 #include "SMESH_MesherHelper.hxx"
28
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FaceOfNodes.hxx"
31 #include "SMDS_FacePosition.hxx" 
32 #include "SMDS_IteratorOnIterators.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMESHDS_Mesh.hxx"
35 #include "SMESH_Block.hxx"
36 #include "SMESH_HypoFilter.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MeshAlgos.hxx"
39 #include "SMESH_ProxyMesh.hxx"
40 #include "SMESH_subMesh.hxx"
41
42 #include <BRepAdaptor_Curve.hxx>
43 #include <BRepAdaptor_Surface.hxx>
44 #include <BRepTools.hxx>
45 #include <BRep_Tool.hxx>
46 #include <Geom2d_Curve.hxx>
47 #include <GeomAPI_ProjectPointOnCurve.hxx>
48 #include <GeomAPI_ProjectPointOnSurf.hxx>
49 #include <Geom_Curve.hxx>
50 #include <Geom_RectangularTrimmedSurface.hxx>
51 #include <Geom_Surface.hxx>
52 #include <ShapeAnalysis.hxx>
53 #include <TopExp.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopTools_MapIteratorOfMapOfShape.hxx>
57 #include <TopTools_MapOfShape.hxx>
58 #include <TopoDS.hxx>
59 #include <gp_Ax3.hxx>
60 #include <gp_Pnt2d.hxx>
61 #include <gp_Trsf.hxx>
62
63 #include <Standard_Failure.hxx>
64 #include <Standard_ErrorHandler.hxx>
65
66 #include <utilities.h>
67
68 #include <limits>
69
70 using namespace std;
71
72 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
73
74 namespace {
75
76   inline SMESH_TNodeXYZ XYZ(const SMDS_MeshNode* n) { return SMESH_TNodeXYZ(n); }
77
78   enum { U_periodic = 1, V_periodic = 2 };
79 }
80
81 //================================================================================
82 /*!
83  * \brief Constructor
84  */
85 //================================================================================
86
87 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
88   : myParIndex(0),
89     myMesh(&theMesh),
90     myShapeID(0),
91     myCreateQuadratic(false),
92     myCreateBiQuadratic(false),
93     myFixNodeParameters(false)
94 {
95   myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
96   mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
97 }
98
99 //=======================================================================
100 //function : ~SMESH_MesherHelper
101 //purpose  : 
102 //=======================================================================
103
104 SMESH_MesherHelper::~SMESH_MesherHelper()
105 {
106   {
107     TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
108     for ( ; i_proj != myFace2Projector.end(); ++i_proj )
109       delete i_proj->second;
110   }
111   {
112     TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
113     for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
114       delete i_proj->second;
115   }
116 }
117
118 //================================================================================
119 /*!
120  * \brief Return SMESH_Gen
121  */
122 //================================================================================
123
124 SMESH_Gen* SMESH_MesherHelper::GetGen() const
125 {
126   return GetMesh()->GetGen();
127 }
128
129 //================================================================================
130 /*!
131  * \brief Return mesh DS
132  */
133 //================================================================================
134
135 SMESHDS_Mesh* SMESH_MesherHelper::GetMeshDS() const
136 {
137   return GetMesh()->GetMeshDS();
138 }
139
140 //=======================================================================
141 //function : IsQuadraticSubMesh
142 //purpose  : Check sub-meshes of a given shape: if all elements on sub-shapes
143 //           are quadratic, quadratic elements will be created.
144 //           Fill myTLinkNodeMap
145 //=======================================================================
146
147 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
148 {
149   SMESHDS_Mesh* meshDS = GetMeshDS();
150   // we can create quadratic elements only if all elements
151   // created on sub-shapes of given shape are quadratic
152   myCreateQuadratic = true;
153   mySeamShapeIds.clear();
154   myDegenShapeIds.clear();
155   TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
156   if ( aSh.ShapeType()==TopAbs_COMPOUND )
157   {
158     TopoDS_Iterator subIt( aSh );
159     if ( subIt.More() )
160       subType = ( subIt.Value().ShapeType()==TopAbs_FACE ) ? TopAbs_EDGE : TopAbs_FACE;
161   }
162   SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
163
164   if ( !myMesh->HasShapeToMesh() )
165   {
166     if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
167     {
168       SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
169       while ( fIt->more() )
170         AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
171     }
172   }
173   else
174   {
175     TopExp_Explorer exp( aSh, subType );
176     TopTools_MapOfShape checkedSubShapes;
177     for (; exp.More() && myCreateQuadratic; exp.Next()) {
178       if ( !checkedSubShapes.Add( exp.Current() ))
179         continue; // needed if aSh is compound of solids
180       if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
181         if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
182           while(it->more()) {
183             const SMDS_MeshElement* e = it->next();
184             if ( e->GetType() != elemType || !e->IsQuadratic() ) {
185               myCreateQuadratic = false;
186               break;
187             }
188             else {
189               // fill TLinkNodeMap
190               switch ( e->NbCornerNodes() ) {
191               case 2:
192                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
193               case 3:
194                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
195                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
196                 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
197               case 4:
198                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
199                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
200                 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
201                 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
202                 break;
203               default:
204                 myCreateQuadratic = false;
205                 break;
206               }
207             }
208           }
209         }
210       }
211     }
212   }
213
214   // if ( nbOldLinks == myTLinkNodeMap.size() ) -- 0023068
215   if ( myTLinkNodeMap.empty() )
216     myCreateQuadratic = false;
217
218   if ( !myCreateQuadratic )
219     myTLinkNodeMap.clear();
220
221   SetSubShape( aSh );
222
223   return myCreateQuadratic;
224 }
225
226 //=======================================================================
227 //function : SetSubShape
228 //purpose  : Set geometry to make elements on
229 //=======================================================================
230
231 void SMESH_MesherHelper::SetSubShape(const int aShID)
232 {
233   if ( aShID == myShapeID )
234     return;
235   if ( aShID > 0 )
236     SetSubShape( GetMeshDS()->IndexToShape( aShID ));
237   else
238     SetSubShape( TopoDS_Shape() );
239 }
240
241 //=======================================================================
242 //function : SetSubShape
243 //purpose  : Set geometry to create elements on
244 //=======================================================================
245
246 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
247 {
248   if ( myShape.IsSame( aSh ))
249     return;
250
251   myShape = aSh;
252   mySeamShapeIds.clear();
253   myDegenShapeIds.clear();
254
255   if ( myShape.IsNull() ) {
256     myShapeID  = 0;
257     return;
258   }
259   SMESHDS_Mesh* meshDS = GetMeshDS();
260   myShapeID = meshDS->ShapeToIndex(aSh);
261   myParIndex = 0;
262
263   // treatment of periodic faces
264   for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
265   {
266     const TopoDS_Face& face = TopoDS::Face( eF.Current() );
267     BRepAdaptor_Surface surf( face, false );
268     if ( surf.IsUPeriodic() || surf.IsUClosed() ) {
269       myParIndex |= U_periodic;
270       myPar1[0] = surf.FirstUParameter();
271       myPar2[0] = surf.LastUParameter();
272     }
273     if ( surf.IsVPeriodic() || surf.IsVClosed() ) {
274       myParIndex |= V_periodic;
275       myPar1[1] = surf.FirstVParameter();
276       myPar2[1] = surf.LastVParameter();
277     }
278
279     gp_Pnt2d uv1, uv2;
280     for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
281     {
282       // look for a "seam" edge, a real seam or an edge on period boundary
283       TopoDS_Edge edge = TopoDS::Edge( exp.Current() );
284       const int edgeID = meshDS->ShapeToIndex( edge );
285       if ( myParIndex )
286       {
287         BRep_Tool::UVPoints( edge, face, uv1, uv2 );
288         const double du = Abs( uv1.Coord(1) - uv2.Coord(1) );
289         const double dv = Abs( uv1.Coord(2) - uv2.Coord(2) );
290
291         bool isSeam = BRep_Tool::IsClosed( edge, face );
292         if ( isSeam ) // real seam - having two pcurves on face
293         {
294           // pcurve can lie not on pediod boundary (22582, mesh_Quadratic_01/C9)
295           if ( du < dv )
296           {
297             double u1 = uv1.Coord(1);
298             edge.Reverse();
299             BRep_Tool::UVPoints( edge, face, uv1, uv2 );
300             double u2 = uv1.Coord(1);
301             myPar1[0] = Min( u1, u2 );
302             myPar2[0] = Max( u1, u2 );
303             myParIndex |= U_periodic;
304           }
305           else
306           {
307             double v1 = uv1.Coord(2);
308             edge.Reverse();
309             BRep_Tool::UVPoints( edge, face, uv1, uv2 );
310             double v2 = uv1.Coord(2);
311             myPar1[1] = Min( v1, v2 );
312             myPar2[1] = Max( v1, v2 );
313             myParIndex |= V_periodic;
314           }
315         }
316         else //if ( !isSeam )
317         {
318           // one pcurve but on period boundary (22772, mesh_Quadratic_01/D1)
319           if      (( myParIndex & U_periodic ) && du < Precision::PConfusion() )
320           {
321             isSeam = ( Abs( uv1.Coord(1) - myPar1[0] ) < Precision::PConfusion() ||
322                        Abs( uv1.Coord(1) - myPar2[0] ) < Precision::PConfusion() );
323           }
324           else if (( myParIndex & V_periodic ) && dv < Precision::PConfusion() )
325           {
326             isSeam = ( Abs( uv1.Coord(2) - myPar1[1] ) < Precision::PConfusion() ||
327                        Abs( uv1.Coord(2) - myPar2[1] ) < Precision::PConfusion() );
328           }
329           if ( isSeam ) // vertices are on period boundary, check a middle point (23032)
330           {
331             double f,l, r = 0.2345;
332             Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
333             if ( C2d.IsNull() )
334             {
335               isSeam = false;
336             }
337             else
338             {
339               uv2 = C2d->Value( f * r + l * ( 1.-r ));
340               if ( du < Precision::PConfusion() )
341                 isSeam = ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Precision::PConfusion() );
342               else
343                 isSeam = ( Abs( uv1.Coord(2) - uv2.Coord(2) ) < Precision::PConfusion() );
344             }
345           }
346         }
347         if ( isSeam )
348         {
349           // store seam shape indices, negative if shape encounters twice ('real seam')
350           mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
351           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
352             int vertexID = meshDS->ShapeToIndex( v.Current() );
353             mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
354           }
355         }
356       }
357       // look for a degenerated edge
358       if ( SMESH_Algo::isDegenerated( edge )) {
359         myDegenShapeIds.insert( edgeID );
360         for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
361           myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
362       }
363       if ( !BRep_Tool::SameParameter( edge ) ||
364            !BRep_Tool::SameRange( edge ))
365       {
366         setPosOnShapeValidity( edgeID, false );
367       }
368     }
369   }
370 }
371
372 //=======================================================================
373 /*!
374  * \brief Copy shape information from another helper. Used to improve performance
375  *        since SetSubShape() can be time consuming if there are many edges
376  */
377 //=======================================================================
378
379 void SMESH_MesherHelper::CopySubShapeInfo(const SMESH_MesherHelper& other)
380 {
381   this->myShape         = other.myShape;
382   this->myShapeID       = other.myShapeID;
383   this->myDegenShapeIds = other.myDegenShapeIds;
384   this->mySeamShapeIds  = other.mySeamShapeIds;
385   this->myPar1[0]       = other.myPar1[0];
386   this->myPar1[1]       = other.myPar1[1];
387   this->myPar2[0]       = other.myPar2[0];
388   this->myPar2[1]       = other.myPar2[1];
389   this->myParIndex      = other.myParIndex;
390   this->myFace2Surface  = other.myFace2Surface;
391 }
392
393 //=======================================================================
394 //function : ShapeToIndex
395 //purpose  : Convert a shape to its index in the SMESHDS_Mesh
396 //=======================================================================
397
398 int SMESH_MesherHelper::ShapeToIndex( const TopoDS_Shape& S ) const
399 {
400   return GetMeshDS()->ShapeToIndex( S );
401 }
402
403 //=======================================================================
404 //function : GetNodeUVneedInFaceNode
405 //purpose  : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
406 //           Return true if the face is periodic.
407 //           If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
408 //           * SetSubShape()
409 //=======================================================================
410
411 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
412 {
413   if ( F.IsNull() ) return !mySeamShapeIds.empty();
414
415   if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
416     return !mySeamShapeIds.empty();
417
418   TopLoc_Location loc;
419   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
420   if ( !aSurface.IsNull() )
421     return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
422
423   return false;
424 }
425
426 //=======================================================================
427 //function : IsMedium
428 //purpose  : 
429 //=======================================================================
430
431 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode*      node,
432                                   const SMDSAbs_ElementType typeToCheck)
433 {
434   return SMESH_MeshEditor::IsMedium( node, typeToCheck );
435 }
436
437 //=======================================================================
438 //function : GetSubShapeByNode
439 //purpose  : Return support shape of a node
440 //=======================================================================
441
442 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
443                                                    const SMESHDS_Mesh*  meshDS)
444 {
445   int shapeID = node ? node->getshapeId() : 0;
446   if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
447     return meshDS->IndexToShape( shapeID );
448   else
449     return TopoDS_Shape();
450 }
451
452
453 //=======================================================================
454 //function : AddTLinkNode
455 //purpose  : add a link in my data structure
456 //=======================================================================
457
458 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
459                                       const SMDS_MeshNode* n2,
460                                       const SMDS_MeshNode* n12)
461 {
462   // add new record to map
463   SMESH_TLink link( n1, n2 );
464   myTLinkNodeMap.insert( make_pair(link,n12));
465 }
466
467 //================================================================================
468 /*!
469  * \brief Add quadratic links of edge to own data structure
470  */
471 //================================================================================
472
473 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
474 {
475   if ( edge && edge->IsQuadratic() )
476     AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
477   else
478     return false;
479   return true;
480 }
481
482 //================================================================================
483 /*!
484  * \brief Add quadratic links of face to own data structure
485  */
486 //================================================================================
487
488 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
489 {
490   bool isQuad = true;
491   if ( !f->IsPoly() )
492     switch ( f->NbNodes() ) {
493     case 7:
494       // myMapWithCentralNode.insert
495       //   ( make_pair( TBiQuad( f->GetNode(0),f->GetNode(1),f->GetNode(2) ),
496       //                f->GetNode(6)));
497       // break; -- add medium nodes as well
498     case 6:
499       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
500       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
501       AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
502
503     case 9:
504       // myMapWithCentralNode.insert
505       //   ( make_pair( TBiQuad( f->GetNode(0),f->GetNode(1),f->GetNode(2),f->GetNode(3) ),
506       //                f->GetNode(8)));
507       // break; -- add medium nodes as well
508     case 8:
509       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
510       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
511       AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
512       AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7)); break;
513     default:;
514       isQuad = false;
515     }
516   return isQuad;
517 }
518
519 //================================================================================
520 /*!
521  * \brief Add quadratic links of volume to own data structure
522  */
523 //================================================================================
524
525 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
526 {
527   if ( volume->IsQuadratic() )
528   {
529     SMDS_VolumeTool vTool( volume );
530     const SMDS_MeshNode** nodes = vTool.GetNodes();
531     set<int> addedLinks;
532     for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
533     {
534       const int nbN = vTool.NbFaceNodes( iF );
535       const int* iNodes = vTool.GetFaceNodesIndices( iF );
536       for ( int i = 0; i < nbN; )
537       {
538         int iN1  = iNodes[i++];
539         int iN12 = iNodes[i++];
540         int iN2  = iNodes[i];
541         if ( iN1 > iN2 ) std::swap( iN1, iN2 );
542         int linkID = iN1 * vTool.NbNodes() + iN2;
543         pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
544         if ( it_isNew.second )
545           AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
546         else
547           addedLinks.erase( it_isNew.first ); // each link encounters only twice
548       }
549       if ( vTool.NbNodes() == 27 )
550       {
551         const SMDS_MeshNode* nFCenter = nodes[ vTool.GetCenterNodeIndex( iF )];
552         if ( nFCenter->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
553           myMapWithCentralNode.insert
554             ( make_pair( TBiQuad( nodes[ iNodes[0]], nodes[ iNodes[1]],
555                                   nodes[ iNodes[2]], nodes[ iNodes[3]] ),
556                          nFCenter ));
557       }
558     }
559     return true;
560   }
561   return false;
562 }
563
564 //================================================================================
565 /*!
566  * \brief Return true if position of nodes on the shape hasn't yet been checked or
567  * the positions proved to be invalid
568  */
569 //================================================================================
570
571 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
572 {
573   map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
574   return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
575 }
576
577 //================================================================================
578 /*!
579  * \brief Set validity of positions of nodes on the shape.
580  * Once set, validity is not changed
581  */
582 //================================================================================
583
584 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
585 {
586   std::map< int,bool >::iterator sh_ok = 
587     ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok)).first;
588   if ( !ok )
589     sh_ok->second = ok;
590 }
591
592 //=======================================================================
593 //function : ToFixNodeParameters
594 //purpose  : Enables fixing node parameters on EDGEs and FACEs in 
595 //           GetNodeU(...,check=true), GetNodeUV(...,check=true), CheckNodeUV() and
596 //           CheckNodeU() in case if a node lies on a shape set via SetSubShape().
597 //           Default is False
598 //=======================================================================
599
600 void SMESH_MesherHelper::ToFixNodeParameters(bool toFix)
601 {
602   myFixNodeParameters = toFix;
603 }
604
605
606 //=======================================================================
607 //function : getUVOnSeam
608 //purpose  : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
609 //=======================================================================
610
611 gp_Pnt2d SMESH_MesherHelper::getUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
612 {
613   gp_Pnt2d result = uv1;
614   for ( int i = U_periodic; i <= V_periodic ; ++i )
615   {
616     if ( myParIndex & i )
617     {
618       double p1 = uv1.Coord( i );
619       double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
620       if ( myParIndex == i ||
621            dp1 < ( myPar2[i-1] - myPar1[i-1] ) / 100. ||
622            dp2 < ( myPar2[i-1] - myPar1[i-1] ) / 100. )
623       {
624         double p2 = uv2.Coord( i );
625         double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
626         if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
627           result.SetCoord( i, p1Alt );
628       }
629     }
630   }
631   return result;
632 }
633
634 //=======================================================================
635 //function : GetNodeUV
636 //purpose  : Return node UV on face
637 //=======================================================================
638
639 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face&   F,
640                                     const SMDS_MeshNode* n,
641                                     const SMDS_MeshNode* n2,
642                                     bool*                check) const
643 {
644   gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
645
646   const SMDS_PositionPtr Pos = n->GetPosition();
647   bool uvOK = false;
648   if ( Pos->GetTypeOfPosition() == SMDS_TOP_FACE )
649   {
650     // node has position on face
651     const SMDS_FacePosition* fpos = static_cast<const SMDS_FacePosition*>( Pos );
652     uv.SetCoord( fpos->GetUParameter(), fpos->GetVParameter() );
653     if ( check )
654       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F )); // 2. from 22830
655   }
656   else if ( Pos->GetTypeOfPosition() == SMDS_TOP_EDGE )
657   {
658     // node has position on EDGE => it is needed to find
659     // corresponding EDGE from FACE, get pcurve for this
660     // EDGE and retrieve value from this pcurve
661     const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( Pos );
662     const int              edgeID = n->getshapeId();
663     const TopoDS_Edge& E = TopoDS::Edge( GetMeshDS()->IndexToShape( edgeID ));
664     double f, l, u = epos->GetUParameter();
665     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( E, F, f, l );
666     bool validU = ( !C2d.IsNull() && ( f < u ) && ( u < l ));
667     if ( validU ) uv = C2d->Value( u );
668     else          uv.SetCoord( Precision::Infinite(),0.);
669     if ( check || !validU )
670       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F ),/*force=*/ !validU );
671
672     // for a node on a seam EDGE select one of UVs on 2 pcurves
673     if ( n2 && IsSeamShape( edgeID ))
674     {
675       uv = getUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
676     }
677     else
678     { // adjust uv to period
679       TopLoc_Location loc;
680       Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
681       Standard_Boolean isUPeriodic = S->IsUPeriodic();
682       Standard_Boolean isVPeriodic = S->IsVPeriodic();
683       gp_Pnt2d newUV = uv;
684       if ( isUPeriodic || isVPeriodic ) {
685         Standard_Real UF,UL,VF,VL;
686         S->Bounds(UF,UL,VF,VL);
687         if ( isUPeriodic ) newUV.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
688         if ( isVPeriodic ) newUV.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
689
690         if ( n2 )
691         {
692           gp_Pnt2d uv2 = GetNodeUV( F, n2, 0, check );
693           if ( isUPeriodic && Abs( uv.X()-uv2.X() ) < Abs( newUV.X()-uv2.X() ))
694             newUV.SetX( uv.X() );
695           if ( isVPeriodic && Abs( uv.Y()-uv2.Y() ) < Abs( newUV.Y()-uv2.Y() ))
696             newUV.SetY( uv.Y() );
697         }
698       }
699       uv = newUV;
700     }
701   }
702   else if ( Pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
703   {
704     if ( int vertexID = n->getshapeId() ) {
705       const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
706       try {
707         uv = BRep_Tool::Parameters( V, F );
708         uvOK = true;
709       }
710       catch (Standard_Failure& exc) {
711       }
712       if ( !uvOK )
713       {
714         if ( !IsSubShape( V, F ))
715         {
716           MESSAGE("GetNodeUV() Vertex "<< vertexID <<" not in face "<< GetMeshDS()->ShapeToIndex(F));
717           // get UV of a vertex closest to the node
718           double dist = 1e100;
719           gp_Pnt pn = XYZ( n );
720           for ( TopExp_Explorer vert( F,TopAbs_VERTEX ); !uvOK && vert.More(); vert.Next() ) {
721             TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
722             gp_Pnt p = BRep_Tool::Pnt( curV );
723             double curDist = p.SquareDistance( pn );
724             if ( curDist < dist ) {
725               dist = curDist;
726               uv = BRep_Tool::Parameters( curV, F );
727               uvOK = ( dist < DBL_MIN );
728             }
729           }
730         }
731         else
732         {
733           uvOK = false;
734           TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
735           for ( ; it.More(); it.Next() ) {
736             if ( it.Value().ShapeType() == TopAbs_EDGE ) {
737               const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
738               double f,l;
739               Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
740               if ( !C2d.IsNull() ) {
741                 double u = ( V == IthVertex( 0, edge )) ?  f : l;
742                 uv = C2d->Value( u );
743                 uvOK = true;
744                 break;
745               }
746             }
747           }
748           if ( !uvOK && V.Orientation() == TopAbs_INTERNAL )
749           {
750             Handle(ShapeAnalysis_Surface) projector = GetSurface( F );
751             if ( n2 ) uv = GetNodeUV( F, n2 );
752             if ( Precision::IsInfinite( uv.X() ))
753               uv = projector->NextValueOfUV( uv, BRep_Tool::Pnt( V ), BRep_Tool::Tolerance( F ));
754             else
755               uv = projector->ValueOfUV( BRep_Tool::Pnt( V ), BRep_Tool::Tolerance( F ));
756             uvOK = ( projector->Gap() < getFaceMaxTol( F ));
757           }
758         }
759       }
760       if ( n2 && IsSeamShape( vertexID ))
761       {
762         bool isSeam = ( myShape.IsSame( F ));
763         if ( !isSeam ) {
764           SMESH_MesherHelper h( *myMesh );
765           h.SetSubShape( F );
766           isSeam = IsSeamShape( vertexID );
767         }
768
769         if ( isSeam )
770           uv = getUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
771       }
772     }
773   }
774   else
775   {
776     uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F ));
777   }
778
779   if ( check && !uvOK )
780     *check = uvOK;
781
782   return uv.XY();
783 }
784
785 //=======================================================================
786 //function : CheckNodeUV
787 //purpose  : Check and fix node UV on a face
788 //=======================================================================
789
790 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face&   F,
791                                      const SMDS_MeshNode* n,
792                                      gp_XY&               uv,
793                                      const double         tol,
794                                      const bool           force,
795                                      double               distXYZ[4]) const
796 {
797   int  shapeID = n->getshapeId();
798   bool infinit;
799   if (( infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ))) ||
800       ( force ) ||
801       ( uv.X() == 0. && uv.Y() == 0. ) ||
802       ( toCheckPosOnShape( shapeID )))
803   {
804     // check that uv is correct
805     TopLoc_Location loc;
806     Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
807     gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
808     double dist = 0;
809     if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
810     if ( infinit ||
811          (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
812     {
813       setPosOnShapeValidity( shapeID, false );
814       if ( !infinit && distXYZ ) {
815         surfPnt.Transform( loc );
816         distXYZ[0] = dist;
817         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
818       }
819       // uv incorrect, project the node to surface
820       GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
821       projector.Perform( nodePnt );
822       if ( !projector.IsDone() || projector.NbPoints() < 1 )
823       {
824         MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
825         return false;
826       }
827       Standard_Real U,V;
828       projector.LowerDistanceParameters(U,V);
829       uv.SetCoord( U,V );
830       surfPnt = surface->Value( U, V );
831       dist = nodePnt.Distance( surfPnt );
832       if ( distXYZ ) {
833         surfPnt.Transform( loc );
834         distXYZ[0] = dist;
835         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
836       }
837       if ( dist > tol )
838       {
839         MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
840         return false;
841       }
842       // store the fixed UV on the face
843       if ( myShape.IsSame(F) && shapeID == myShapeID && myFixNodeParameters )
844         const_cast<SMDS_MeshNode*>(n)->SetPosition
845           ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
846     }
847     else if ( myShape.IsSame(F) && uv.Modulus() > numeric_limits<double>::min() )
848     {
849       setPosOnShapeValidity( shapeID, true );
850     }
851   }
852   return true;
853 }
854
855 //=======================================================================
856 //function : GetProjector
857 //purpose  : Return projector intitialized by given face without location, which is returned
858 //=======================================================================
859
860 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
861                                                              TopLoc_Location&   loc,
862                                                              double             tol ) const
863 {
864   Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
865   int faceID = GetMeshDS()->ShapeToIndex( F );
866   TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
867   TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
868   if ( i_proj == i2proj.end() )
869   {
870     if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
871     double U1, U2, V1, V2;
872     surface->Bounds(U1, U2, V1, V2);
873     GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
874     proj->Init( surface, U1, U2, V1, V2, tol );
875     i_proj = i2proj.insert( make_pair( faceID, proj )).first;
876   }
877   return *( i_proj->second );
878 }
879
880 //=======================================================================
881 //function : GetSurface
882 //purpose  : Return a cached ShapeAnalysis_Surface of a FACE
883 //=======================================================================
884
885 Handle(ShapeAnalysis_Surface) SMESH_MesherHelper::GetSurface(const TopoDS_Face& F ) const
886 {
887   Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
888   int faceID = GetMeshDS()->ShapeToIndex( F );
889   TID2Surface::iterator i_surf = myFace2Surface.find( faceID );
890   if ( i_surf == myFace2Surface.end() && faceID )
891   {
892     Handle(ShapeAnalysis_Surface) surf( new ShapeAnalysis_Surface( surface ));
893     i_surf = myFace2Surface.insert( make_pair( faceID, surf )).first;
894   }
895   return i_surf->second;
896 }
897
898 namespace
899 {
900   gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
901   gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
902   gp_XY_FunPtr(Subtracted); 
903 }
904
905 //=======================================================================
906 //function : ApplyIn2D
907 //purpose  : Perform given operation on two 2d points in parameric space of given surface.
908 //           It takes into account period of the surface. Use gp_XY_FunPtr macro
909 //           to easily define pointer to function of gp_XY class.
910 //=======================================================================
911
912 gp_XY SMESH_MesherHelper::ApplyIn2D(Handle(Geom_Surface) surface,
913                                     const gp_XY&         uv1,
914                                     const gp_XY&         uv2,
915                                     xyFunPtr             fun,
916                                     const bool           resultInPeriod)
917 {
918   if ( surface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
919     surface = Handle(Geom_RectangularTrimmedSurface)::DownCast( surface )->BasisSurface();
920   Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
921   Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
922   if ( !isUPeriodic && !isVPeriodic )
923     return fun(uv1,uv2);
924
925   // move uv2 not far than half-period from uv1
926   double u2 = 
927     uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
928   double v2 = 
929     uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
930
931   // execute operation
932   gp_XY res = fun( uv1, gp_XY(u2,v2) );
933
934   // move result within period
935   if ( resultInPeriod )
936   {
937     Standard_Real UF,UL,VF,VL;
938     surface->Bounds(UF,UL,VF,VL);
939     if ( isUPeriodic )
940       res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
941     if ( isVPeriodic )
942       res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
943   }
944
945   return res;
946 }
947
948 //=======================================================================
949 //function : AdjustByPeriod
950 //purpose  : Move node positions on a FACE within surface period
951 //=======================================================================
952
953 void SMESH_MesherHelper::AdjustByPeriod( const TopoDS_Face& face, gp_XY uv[], const int nbUV )
954 {
955   SMESH_MesherHelper h( *myMesh ), *ph = face.IsSame( myShape ) ? this : &h;
956   ph->SetSubShape( face );
957
958   for ( int iCoo = U_periodic; iCoo <= V_periodic; ++iCoo )
959     if ( ph->GetPeriodicIndex() & iCoo )
960     {
961       const double period = ( ph->myPar2[iCoo-1] - ph->myPar1[iCoo-1] );
962       const double xRef = uv[0].Coord( iCoo );
963       for ( int i = 1; i < nbUV; ++i )
964       {
965         double x = uv[i].Coord( iCoo );
966         double dx = ShapeAnalysis::AdjustByPeriod( x, xRef, period );
967         uv[i].SetCoord( iCoo, x + dx );
968       }
969     }
970 }
971
972 //=======================================================================
973 //function : GetMiddleUV
974 //purpose  : Return middle UV taking in account surface period
975 //=======================================================================
976
977 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
978                                       const gp_XY&                p1,
979                                       const gp_XY&                p2)
980 {
981   // NOTE:
982   // the proper place of getting basic surface seems to be in ApplyIn2D()
983   // but we put it here to decrease a risk of regressions just before releasing a version
984   // Handle(Geom_Surface) surf = surface;
985   // while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
986   //   surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
987
988   return ApplyIn2D( surface, p1, p2, & AverageUV );
989 }
990
991 //=======================================================================
992 //function : GetCenterUV
993 //purpose  : Return UV for the central node of a biquadratic triangle
994 //=======================================================================
995
996 gp_XY SMESH_MesherHelper::GetCenterUV(const gp_XY& uv1,
997                                       const gp_XY& uv2, 
998                                       const gp_XY& uv3, 
999                                       const gp_XY& uv12,
1000                                       const gp_XY& uv23,
1001                                       const gp_XY& uv31,
1002                                       bool *       isBadTria/*=0*/)
1003 {
1004   bool badTria;
1005   gp_XY uvAvg = ( uv12 + uv23 + uv31 ) / 3.;
1006
1007   if      (( badTria = (( uvAvg - uv1 ) * ( uvAvg - uv23 ) > 0 )))
1008     uvAvg = ( uv1 + uv23 ) / 2.;
1009   else if (( badTria = (( uvAvg - uv2 ) * ( uvAvg - uv31 ) > 0 )))
1010     uvAvg = ( uv2 + uv31 ) / 2.;
1011   else if (( badTria = (( uvAvg - uv3 ) * ( uvAvg - uv12 ) > 0 )))
1012     uvAvg = ( uv3 + uv12 ) / 2.;
1013
1014   if ( isBadTria )
1015     *isBadTria = badTria;
1016   return uvAvg;
1017 }
1018
1019 //=======================================================================
1020 //function : GetNodeU
1021 //purpose  : Return node U on edge
1022 //=======================================================================
1023
1024 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge&   E,
1025                                     const SMDS_MeshNode* n,
1026                                     const SMDS_MeshNode* inEdgeNode,
1027                                     bool*                check) const
1028 {
1029   double param = Precision::Infinite();
1030
1031   const SMDS_PositionPtr pos = n->GetPosition();
1032   if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
1033   {
1034     const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
1035     param =  epos->GetUParameter();
1036   }
1037   else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1038   {
1039     if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
1040     {
1041       Standard_Real f,l;
1042       BRep_Tool::Range( E, f,l );
1043       double uInEdge = GetNodeU( E, inEdgeNode );
1044       param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
1045     }
1046     else
1047     {
1048       SMESHDS_Mesh * meshDS = GetMeshDS();
1049       int vertexID = n->getshapeId();
1050       const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
1051       param =  BRep_Tool::Parameter( V, E );
1052     }
1053   }
1054   if ( check )
1055   {
1056     double tol = BRep_Tool::Tolerance( E );
1057     double f,l;  BRep_Tool::Range( E, f,l );
1058     bool force = ( param < f-tol || param > l+tol );
1059     if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
1060       force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
1061
1062     *check = CheckNodeU( E, n, param, 2*tol, force );
1063   }
1064   return param;
1065 }
1066
1067 //=======================================================================
1068 //function : CheckNodeU
1069 //purpose  : Check and fix node U on an edge
1070 //           Return false if U is bad and could not be fixed
1071 //=======================================================================
1072
1073 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge&   E,
1074                                     const SMDS_MeshNode* n,
1075                                     double&              u,
1076                                     const double         tol,
1077                                     const bool           force,
1078                                     double               distXYZ[4]) const
1079 {
1080   int  shapeID = n->getshapeId();
1081   bool infinit;
1082   if (( infinit = Precision::IsInfinite( u )) ||
1083       ( force ) ||
1084       ( u == 0. ) ||
1085       ( toCheckPosOnShape( shapeID )))
1086   {
1087     TopLoc_Location loc; double f,l;
1088     Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
1089     if ( curve.IsNull() ) // degenerated edge
1090     {
1091       if ( u+tol < f || u-tol > l )
1092       {
1093         double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
1094         u =  f*r + l*(1-r);
1095       }
1096     }
1097     else
1098     {
1099       gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
1100       if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
1101       gp_Pnt curvPnt;
1102       double dist = 2*tol;
1103       if ( !infinit )
1104       {
1105         curvPnt = curve->Value( u );
1106         dist    = nodePnt.Distance( curvPnt );
1107         if ( distXYZ ) {
1108           curvPnt.Transform( loc );
1109           distXYZ[0] = dist;
1110           distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
1111         }
1112       }
1113       if ( dist > tol )
1114       {
1115         setPosOnShapeValidity( shapeID, false );
1116         // u incorrect, project the node to the curve
1117         int edgeID = GetMeshDS()->ShapeToIndex( E );
1118         TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
1119         TID2ProjectorOnCurve::iterator i_proj =
1120           i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
1121         if ( !i_proj->second  )
1122         {
1123           i_proj->second = new GeomAPI_ProjectPointOnCurve();
1124           i_proj->second->Init( curve, f, l );
1125         }
1126         GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
1127         projector->Perform( nodePnt );
1128         if ( projector->NbPoints() < 1 )
1129         {
1130           MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
1131           return false;
1132         }
1133         Standard_Real U = projector->LowerDistanceParameter();
1134         u = double( U );
1135         curvPnt = curve->Value( u );
1136         dist = nodePnt.Distance( curvPnt );
1137         if ( distXYZ ) {
1138           curvPnt.Transform( loc );
1139           distXYZ[0] = dist;
1140           distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
1141         }
1142         if ( dist > tol )
1143         {
1144           MESSAGE( "CheckNodeU(), invalid projection; distance " << dist << "; tol " << tol );
1145           return false;
1146         }
1147         // store the fixed U on the edge
1148         if ( myShape.IsSame(E) && shapeID == myShapeID && myFixNodeParameters )
1149           const_cast<SMDS_MeshNode*>(n)->SetPosition
1150             ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
1151       }
1152       else if ( fabs( u ) > numeric_limits<double>::min() )
1153       {
1154         setPosOnShapeValidity( shapeID, true );
1155       }
1156       if (( u < f-tol || u > l+tol ) && force )
1157       {
1158         MESSAGE("u < f-tol || u > l+tol  ; u " << u << " f " << f << " l " << l);
1159         // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
1160         try
1161         {
1162           // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
1163           double period = curve->Period();
1164           u = ( u < f ) ? u + period : u - period;
1165         }
1166         catch (Standard_Failure& exc)
1167         {
1168           return false;
1169         }
1170       }
1171     }
1172   }
1173   return true;
1174 }
1175
1176 //=======================================================================
1177 //function : GetMediumPos
1178 //purpose  : Return index and type of the shape  (EDGE or FACE only) to
1179 //           set a medium node on
1180 //param    : useCurSubShape - if true, returns the shape set via SetSubShape()
1181 //           if any
1182 //param    : expectedSupport - shape type corresponding to element being created,
1183 //                             e.g TopAbs_EDGE if SMDSAbs_Edge is created
1184 //                             basing on \a n1 and \a n2
1185 // Calling GetMediumPos() with useCurSubShape=true is OK only for the
1186 // case where the lower dim mesh is already constructed and converted to quadratic,
1187 // else, nodes on EDGEs are assigned to FACE, for example.
1188 //=======================================================================
1189
1190 std::pair<int, TopAbs_ShapeEnum>
1191 SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
1192                                  const SMDS_MeshNode* n2,
1193                                  const bool           useCurSubShape,
1194                                  TopAbs_ShapeEnum     expectedSupport)
1195 {
1196   if ( useCurSubShape && !myShape.IsNull() )
1197     return std::make_pair( myShapeID, myShape.ShapeType() );
1198
1199   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1200   int              shapeID = -1;
1201   TopoDS_Shape     shape;
1202
1203   if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
1204   {
1205     shapeType = myShape.ShapeType();
1206     shapeID   = myShapeID;
1207   }
1208   else if ( n1->getshapeId() == n2->getshapeId() )
1209   {
1210     shapeID = n2->getshapeId();
1211     shape = GetSubShapeByNode( n1, GetMeshDS() );
1212   }
1213   else // 2 different shapes
1214   {
1215     const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
1216     const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
1217
1218     if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
1219     {
1220       // in SOLID
1221     }
1222     else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
1223     {
1224       // in FACE or SOLID
1225       if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE ) // not 2 FACEs
1226       {
1227         if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
1228         TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
1229         TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
1230         if ( IsSubShape( S, F ))
1231         {
1232           shapeType = TopAbs_FACE;
1233           shapeID   = n1->getshapeId();
1234         }
1235       }
1236     }
1237     else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
1238     {
1239       TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
1240       TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
1241       shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
1242     }
1243     else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
1244     {
1245       TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
1246       TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
1247       shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
1248       if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
1249     }
1250     else // on VERTEX and EDGE
1251     {
1252       if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
1253       TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
1254       TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
1255       if ( IsSubShape( V, E ))
1256         shape = E;
1257       else
1258         shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
1259     }
1260   }
1261
1262   if ( !shape.IsNull() )
1263   {
1264     if ( shapeID < 1 )
1265       shapeID = GetMeshDS()->ShapeToIndex( shape );
1266     shapeType = shape.ShapeType(); // EDGE or FACE
1267
1268     if ( expectedSupport < shapeType &&
1269          expectedSupport != TopAbs_SHAPE &&
1270          !myShape.IsNull() &&
1271          myShape.ShapeType() == expectedSupport )
1272     {
1273       // e.g. a side of triangle connects nodes on the same EDGE but does not
1274       // lie on this EDGE (an arc with a coarse mesh)
1275       // =>  shapeType == TopAbs_EDGE, expectedSupport == TopAbs_FACE;
1276       // hope that myShape is a right shape, return it if the found shape
1277       // has converted elements of corresponding dim (segments in our example)
1278       int nbConvertedElems = 0;
1279       SMDSAbs_ElementType type = ( shapeType == TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
1280       for ( int iN = 0; iN < 2; ++iN )
1281       {
1282         const SMDS_MeshNode* n = iN ? n2 : n1;
1283         SMDS_ElemIteratorPtr it = n->GetInverseElementIterator( type );
1284         while ( it->more() )
1285         {
1286           const SMDS_MeshElement* elem = it->next();
1287           if ( elem->getshapeId() == shapeID &&
1288                elem->IsQuadratic() )
1289           {
1290             ++nbConvertedElems;
1291             break;
1292           }
1293         }
1294       }
1295       if ( nbConvertedElems == 2 )
1296       {
1297         shapeType = myShape.ShapeType();
1298         shapeID   = myShapeID;
1299       }
1300     }
1301   }
1302   return make_pair( shapeID, shapeType );
1303 }
1304
1305 //=======================================================================
1306 //function : GetCentralNode
1307 //purpose  : Return existing or create a new central node for a quardilateral
1308 //           quadratic face given its 8 nodes.
1309 //@param   : force3d - true means node creation in between the given nodes,
1310 //           else node position is found on a geometrical face if any.
1311 //=======================================================================
1312
1313 const SMDS_MeshNode* SMESH_MesherHelper::GetCentralNode(const SMDS_MeshNode* n1,
1314                                                         const SMDS_MeshNode* n2,
1315                                                         const SMDS_MeshNode* n3,
1316                                                         const SMDS_MeshNode* n4,
1317                                                         const SMDS_MeshNode* n12,
1318                                                         const SMDS_MeshNode* n23,
1319                                                         const SMDS_MeshNode* n34,
1320                                                         const SMDS_MeshNode* n41,
1321                                                         bool                 force3d)
1322 {
1323   SMDS_MeshNode *centralNode = 0; // central node to return
1324
1325   // Find an existing central node
1326
1327   TBiQuad keyOfMap(n1,n2,n3,n4);
1328   std::map<TBiQuad, const SMDS_MeshNode* >::iterator itMapCentralNode;
1329   itMapCentralNode = myMapWithCentralNode.find( keyOfMap );
1330   if ( itMapCentralNode != myMapWithCentralNode.end() ) 
1331   {
1332     return (*itMapCentralNode).second;
1333   }
1334
1335   // Get type of shape for the new central node
1336
1337   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1338   int              solidID = -1;
1339   int              faceID = -1;
1340   TopoDS_Shape     shape;
1341   TopTools_ListIteratorOfListOfShape it;
1342
1343   std::map< int, int > faceId2nbNodes;
1344   std::map< int, int > ::iterator itMapWithIdFace;
1345   
1346   SMESHDS_Mesh* meshDS = GetMeshDS();
1347   
1348   // check if a face lies on a FACE, i.e. its all corner nodes lie either on the FACE or
1349   // on sub-shapes of the FACE
1350   if ( GetMesh()->HasShapeToMesh() )
1351   {
1352     const SMDS_MeshNode* nodes[] = { n1, n2, n3, n4 };
1353     for(int i = 0; i < 4; i++)
1354     {
1355       shape = GetSubShapeByNode( nodes[i], meshDS );
1356       if ( shape.IsNull() ) break;
1357       if ( shape.ShapeType() == TopAbs_SOLID )
1358       {
1359         solidID   = nodes[i]->getshapeId();
1360         shapeType = TopAbs_SOLID;
1361         break;
1362       }
1363       if ( shape.ShapeType() == TopAbs_FACE )
1364       {
1365         faceID          = nodes[i]->getshapeId();
1366         itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1367         itMapWithIdFace->second++;
1368       }
1369       else
1370       {
1371         PShapeIteratorPtr it = GetAncestors( shape, *GetMesh(), TopAbs_FACE );
1372         while ( const TopoDS_Shape* face = it->next() )
1373         {
1374           faceID = meshDS->ShapeToIndex( *face );
1375           itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 )).first;
1376           itMapWithIdFace->second++;
1377         }
1378       }
1379     }
1380   }
1381   if ( solidID < 1 && !faceId2nbNodes.empty() ) // SOLID not found
1382   {
1383     // find ID of the FACE the four corner nodes belong to
1384     itMapWithIdFace = faceId2nbNodes.find( myShapeID ); // IPAL52698
1385     if ( itMapWithIdFace != faceId2nbNodes.end() &&
1386          itMapWithIdFace->second == 4 )
1387     {
1388       shapeType = TopAbs_FACE;
1389       faceID = myShapeID;
1390     }
1391     else
1392     {
1393       itMapWithIdFace = faceId2nbNodes.begin();
1394       for ( ; itMapWithIdFace != faceId2nbNodes.end(); ++itMapWithIdFace)
1395       {
1396         if ( itMapWithIdFace->second == 4 )
1397         {
1398           shapeType = TopAbs_FACE;
1399           faceID = (*itMapWithIdFace).first;
1400           break;
1401         }
1402       }
1403     }
1404   }
1405
1406   TopoDS_Face F;
1407   if ( shapeType == TopAbs_FACE )
1408   {
1409     F = TopoDS::Face( meshDS->IndexToShape( faceID ));
1410   }
1411
1412   // Create a node
1413
1414   gp_XY  uvAvg;
1415   gp_Pnt P;
1416   bool toCheck = true;
1417   if ( !F.IsNull() && !force3d )
1418   {
1419     Handle(ShapeAnalysis_Surface) surface = GetSurface( F );
1420     if ( HasDegeneratedEdges() || surface->HasSingularities( 1e-7 ))
1421     {
1422       gp_Pnt center = calcTFI (0.5, 0.5, // IPAL0052863
1423                                SMESH_TNodeXYZ(n1),  SMESH_TNodeXYZ(n2),
1424                                SMESH_TNodeXYZ(n3),  SMESH_TNodeXYZ(n4),
1425                                SMESH_TNodeXYZ(n12), SMESH_TNodeXYZ(n23),
1426                                SMESH_TNodeXYZ(n34), SMESH_TNodeXYZ(n41));
1427       gp_Pnt2d uv12 = GetNodeUV( F, n12, n3, &toCheck );
1428       uvAvg = surface->NextValueOfUV( uv12, center, BRep_Tool::Tolerance( F )).XY();
1429     }
1430     else
1431     {
1432       gp_XY uv[8] = {
1433         GetNodeUV( F,n1,  n3, &toCheck ),
1434         GetNodeUV( F,n2,  n4, &toCheck ),
1435         GetNodeUV( F,n3,  n1, &toCheck ),
1436         GetNodeUV( F,n4,  n2, &toCheck ),
1437         GetNodeUV( F,n12, n3 ),
1438         GetNodeUV( F,n23, n4 ),
1439         GetNodeUV( F,n34, n2 ),
1440         GetNodeUV( F,n41, n2 )
1441       };
1442       AdjustByPeriod( F, uv, 8 ); // put uv[] within a period (IPAL52698)
1443
1444       uvAvg = calcTFI (0.5, 0.5, uv[0],uv[1],uv[2],uv[3], uv[4],uv[5],uv[6],uv[7] );
1445     }
1446     P = surface->Value( uvAvg );
1447     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1448     // if ( mySetElemOnShape ) node is not elem!
1449     meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1450   }
1451   else // ( force3d || F.IsNull() )
1452   {
1453     P = calcTFI (0.5, 0.5,
1454                  SMESH_TNodeXYZ(n1),  SMESH_TNodeXYZ(n2),
1455                  SMESH_TNodeXYZ(n3),  SMESH_TNodeXYZ(n4),
1456                  SMESH_TNodeXYZ(n12), SMESH_TNodeXYZ(n23),
1457                  SMESH_TNodeXYZ(n34), SMESH_TNodeXYZ(n41));
1458     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1459
1460     if ( !F.IsNull() ) // force3d
1461     {
1462       uvAvg = (GetNodeUV(F,n1,n3,&toCheck) +
1463                GetNodeUV(F,n2,n4,&toCheck) +
1464                GetNodeUV(F,n3,n1,&toCheck) +
1465                GetNodeUV(F,n4,n2,&toCheck)) / 4;
1466       //CheckNodeUV( F, centralNode, uvAvg, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1467       meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1468     }
1469     else if ( solidID > 0 )
1470     {
1471       meshDS->SetNodeInVolume( centralNode, solidID );
1472     }
1473     else if ( myShapeID > 0 && mySetElemOnShape )
1474     {
1475       meshDS->SetMeshElementOnShape( centralNode, myShapeID );
1476     }
1477   }
1478   myMapWithCentralNode.insert( std::make_pair( keyOfMap, centralNode ) );
1479   return centralNode;
1480 }
1481
1482 //=======================================================================
1483 //function : GetCentralNode
1484 //purpose  : Return existing or create a new central node for a
1485 //           quadratic triangle given its 6 nodes.
1486 //@param   : force3d - true means node creation in between the given nodes,
1487 //           else node position is found on a geometrical face if any.
1488 //=======================================================================
1489
1490 const SMDS_MeshNode* SMESH_MesherHelper::GetCentralNode(const SMDS_MeshNode* n1,
1491                                                         const SMDS_MeshNode* n2,
1492                                                         const SMDS_MeshNode* n3,
1493                                                         const SMDS_MeshNode* n12,
1494                                                         const SMDS_MeshNode* n23,
1495                                                         const SMDS_MeshNode* n31,
1496                                                         bool                 force3d)
1497 {
1498   SMDS_MeshNode *centralNode = 0; // central node to return
1499
1500   // Find an existing central node
1501
1502   TBiQuad keyOfMap(n1,n2,n3);
1503   std::map<TBiQuad, const SMDS_MeshNode* >::iterator itMapCentralNode;
1504   itMapCentralNode = myMapWithCentralNode.find( keyOfMap );
1505   if ( itMapCentralNode != myMapWithCentralNode.end() ) 
1506   {
1507     return (*itMapCentralNode).second;
1508   }
1509
1510   // Get type of shape for the new central node
1511
1512   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1513   int              solidID = -1;
1514   int              faceID = -1;
1515   TopoDS_Shape     shape;
1516   TopTools_ListIteratorOfListOfShape it;
1517
1518   std::map< int, int > faceId2nbNodes;
1519   std::map< int, int > ::iterator itMapWithIdFace;
1520   
1521   SMESHDS_Mesh* meshDS = GetMeshDS();
1522   
1523   // check if a face lies on a FACE, i.e. its all corner nodes lie either on the FACE or
1524   // on sub-shapes of the FACE
1525   if ( GetMesh()->HasShapeToMesh() )
1526   {
1527     const SMDS_MeshNode* nodes[] = { n1, n2, n3 };
1528     for(int i = 0; i < 3; i++)
1529     {
1530       shape = GetSubShapeByNode( nodes[i], meshDS );
1531       if ( shape.IsNull() ) break;
1532       if ( shape.ShapeType() == TopAbs_SOLID )
1533       {
1534         solidID   = nodes[i]->getshapeId();
1535         shapeType = TopAbs_SOLID;
1536         break;
1537       }
1538       if ( shape.ShapeType() == TopAbs_FACE )
1539       {
1540         faceID          = nodes[i]->getshapeId();
1541         itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1542         itMapWithIdFace->second++;
1543       }
1544       else
1545       {
1546         PShapeIteratorPtr it = GetAncestors(shape, *GetMesh(), TopAbs_FACE );
1547         while ( const TopoDS_Shape* face = it->next() )
1548         {
1549           faceID = meshDS->ShapeToIndex( *face );
1550           itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1551           itMapWithIdFace->second++;
1552         }
1553       }
1554     }
1555   }
1556   if ( solidID < 1 && !faceId2nbNodes.empty() ) // SOLID not found
1557   {
1558     // find ID of the FACE the four corner nodes belong to
1559     itMapWithIdFace = faceId2nbNodes.find( myShapeID ); // IPAL52698
1560     if ( itMapWithIdFace != faceId2nbNodes.end() &&
1561          itMapWithIdFace->second == 4 )
1562     {
1563       shapeType = TopAbs_FACE;
1564       faceID = myShapeID;
1565     }
1566     else
1567     {
1568       itMapWithIdFace = faceId2nbNodes.begin();
1569       for ( ; itMapWithIdFace != faceId2nbNodes.end(); ++itMapWithIdFace)
1570       {
1571         if ( itMapWithIdFace->second == 3 )
1572         {
1573           shapeType = TopAbs_FACE;
1574           faceID = (*itMapWithIdFace).first;
1575           break;
1576         }
1577       }
1578     }
1579   }
1580
1581   TopoDS_Face F;
1582   gp_XY       uvAvg;
1583
1584   if ( shapeType == TopAbs_FACE )
1585   {
1586     F = TopoDS::Face( meshDS->IndexToShape( faceID ));
1587     bool checkOK = true, badTria = false;
1588     gp_XY uv[6] = {
1589       GetNodeUV( F, n1, n23, &checkOK ),
1590       GetNodeUV( F, n2, n31, &checkOK ),
1591       GetNodeUV( F, n3, n12, &checkOK ),
1592       GetNodeUV( F, n12, n3, &checkOK ),
1593       GetNodeUV( F, n23, n1, &checkOK ),
1594       GetNodeUV( F, n31, n2, &checkOK )
1595     };
1596     AdjustByPeriod( F, uv, 6 ); // put uv[] within a period (IPAL52698)
1597
1598     uvAvg = GetCenterUV( uv[0],uv[1],uv[2], uv[3],uv[4],uv[5], &badTria );
1599
1600     if ( badTria || !checkOK )
1601       force3d = true;
1602   }
1603
1604   // Create a central node
1605
1606   gp_Pnt P;
1607   if ( !F.IsNull() && !force3d )
1608   {
1609     TopLoc_Location        loc;
1610     Handle( Geom_Surface ) S = BRep_Tool::Surface( F, loc );
1611     P = S->Value( uvAvg.X(), uvAvg.Y() ).Transformed( loc );
1612     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1613     // if ( mySetElemOnShape ) node is not elem!
1614     meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1615   }
1616   else // ( force3d || F.IsNull() )
1617   {
1618     P = ( SMESH_TNodeXYZ( n12 ) +
1619           SMESH_TNodeXYZ( n23 ) +
1620           SMESH_TNodeXYZ( n31 ) ) / 3;
1621     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1622
1623     if ( !F.IsNull() ) // force3d
1624     {
1625       meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1626     }
1627     else if ( solidID > 0 )
1628     {
1629       meshDS->SetNodeInVolume( centralNode, solidID );
1630     }
1631     else if ( myShapeID > 0 && mySetElemOnShape )
1632     {
1633       meshDS->SetMeshElementOnShape( centralNode, myShapeID );
1634     }
1635   }
1636   myMapWithCentralNode.insert( std::make_pair( keyOfMap, centralNode ) );
1637   return centralNode;
1638 }
1639
1640 //=======================================================================
1641 //function : GetMediumNode
1642 //purpose  : Return existing or create a new medium node between given ones
1643 //=======================================================================
1644
1645 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
1646                                                        const SMDS_MeshNode* n2,
1647                                                        bool                 force3d,
1648                                                        TopAbs_ShapeEnum     expectedSupport)
1649 {
1650   // Find existing node
1651
1652   SMESH_TLink link(n1,n2);
1653   ItTLinkNode itLN = myTLinkNodeMap.find( link );
1654   if ( itLN != myTLinkNodeMap.end() ) {
1655     return (*itLN).second;
1656   }
1657
1658   // Create medium node
1659
1660   SMDS_MeshNode* n12;
1661   SMESHDS_Mesh* meshDS = GetMeshDS();
1662
1663   if ( IsSeamShape( n1->getshapeId() ))
1664     // to get a correct UV of a node on seam, the second node must have checked UV
1665     std::swap( n1, n2 );
1666
1667   // get type of shape for the new medium node
1668   int faceID = -1, edgeID = -1;
1669   TopoDS_Edge E; double u [2] = {0.,0.};
1670   TopoDS_Face F; gp_XY  uv[2];
1671   bool uvOK[2] = { true, true };
1672   const bool useCurSubShape = ( !myShape.IsNull() && myShape.ShapeType() == TopAbs_EDGE );
1673
1674   pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2, useCurSubShape, expectedSupport );
1675
1676   // get positions of the given nodes on shapes
1677   if ( pos.second == TopAbs_FACE )
1678   {
1679     F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1680     uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1681     if (( !force3d ) &&
1682         ( HasDegeneratedEdges() || GetSurface( F )->HasSingularities( 1e-7 )))
1683     {
1684       // IPAL52850 (degen VERTEX not at singularity)
1685       // project middle point to a surface
1686       SMESH_TNodeXYZ p1( n1 ), p2( n2 );
1687       gp_Pnt pMid = 0.5 * ( p1 + p2 );
1688       Handle(ShapeAnalysis_Surface) projector = GetSurface( F );
1689       gp_Pnt2d uvMid;
1690       if ( uvOK[0] )
1691         uvMid = projector->NextValueOfUV( uv[0], pMid, BRep_Tool::Tolerance( F ));
1692       else
1693         uvMid = projector->ValueOfUV( pMid, getFaceMaxTol( F ));
1694       if ( projector->Gap() * projector->Gap() < ( p1 - p2 ).SquareModulus() / 4 )
1695       {
1696         gp_Pnt pProj = projector->Value( uvMid );
1697         n12  = meshDS->AddNode( pProj.X(), pProj.Y(), pProj.Z() );
1698         meshDS->SetNodeOnFace( n12, faceID, uvMid.X(), uvMid.Y() );
1699         myTLinkNodeMap.insert( make_pair ( link, n12 ));
1700         return n12;
1701       }
1702     }
1703     uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1704   }
1705   else if ( pos.second == TopAbs_EDGE )
1706   {
1707     const SMDS_PositionPtr Pos1 = n1->GetPosition();
1708     const SMDS_PositionPtr Pos2 = n2->GetPosition();
1709     if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1710          Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1711          n1->getshapeId() != n2->getshapeId() )
1712     {
1713       // issue 0021006
1714       return getMediumNodeOnComposedWire(n1,n2,force3d);
1715     }
1716     E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1717     try {
1718       u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1719       u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1720     }
1721     catch ( Standard_Failure& f )
1722     {
1723       // issue 22502 / a node is on VERTEX not belonging to E
1724       // issue 22568 / both nodes are on non-connected VERTEXes
1725       return getMediumNodeOnComposedWire(n1,n2,force3d);
1726     }
1727   }
1728
1729   if ( !force3d & uvOK[0] && uvOK[1] )
1730   {
1731     // we try to create medium node using UV parameters of
1732     // nodes, else - medium between corresponding 3d points
1733     if( ! F.IsNull() )
1734     {
1735       //if ( uvOK[0] && uvOK[1] )
1736       {
1737         if ( IsDegenShape( n1->getshapeId() )) {
1738           if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1739           else                           uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1740         }
1741         else if ( IsDegenShape( n2->getshapeId() )) {
1742           if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1743           else                           uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1744         }
1745         TopLoc_Location loc;
1746         Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1747         gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1748         gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1749         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1750         // if ( mySetElemOnShape ) node is not elem!
1751         meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1752         myTLinkNodeMap.insert(make_pair(link,n12));
1753         return n12;
1754       }
1755     }
1756     else if ( !E.IsNull() )
1757     {
1758       double f,l;
1759       Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1760       if(!C.IsNull())
1761       {
1762         Standard_Boolean isPeriodic = C->IsPeriodic();
1763         double U;
1764         if(isPeriodic) {
1765           Standard_Real Period = C->Period();
1766           Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1767           Standard_Real pmid = (u[0]+p)/2.;
1768           U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1769         }
1770         else
1771           U = (u[0]+u[1])/2.;
1772
1773         gp_Pnt P = C->Value( U );
1774         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1775         //if ( mySetElemOnShape ) node is not elem!
1776         meshDS->SetNodeOnEdge(n12, edgeID, U);
1777         myTLinkNodeMap.insert(make_pair(link,n12));
1778         return n12;
1779       }
1780     }
1781   }
1782
1783   // 3d variant
1784   double x = ( n1->X() + n2->X() )/2.;
1785   double y = ( n1->Y() + n2->Y() )/2.;
1786   double z = ( n1->Z() + n2->Z() )/2.;
1787   n12 = meshDS->AddNode(x,y,z);
1788
1789   //if ( mySetElemOnShape ) node is not elem!
1790   {
1791     if ( !F.IsNull() )
1792     {
1793       gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1794       CheckNodeUV( F, n12, UV, 2 * BRep_Tool::Tolerance( F ), /*force=*/true);
1795       meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1796     }
1797     else if ( !E.IsNull() )
1798     {
1799       double U = ( u[0] + u[1] ) / 2.;
1800       CheckNodeU( E, n12, U, 2 * BRep_Tool::Tolerance( E ), /*force=*/true);
1801       meshDS->SetNodeOnEdge(n12, edgeID, U);
1802     }
1803     else if ( myShapeID > 0 && mySetElemOnShape )
1804     {
1805       meshDS->SetMeshElementOnShape(n12, myShapeID);
1806     }
1807   }
1808
1809   myTLinkNodeMap.insert( make_pair( link, n12 ));
1810   return n12;
1811 }
1812
1813 //================================================================================
1814 /*!
1815  * \brief Makes a medium node if nodes reside different edges
1816  */
1817 //================================================================================
1818
1819 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1820                                                                      const SMDS_MeshNode* n2,
1821                                                                      bool                 force3d)
1822 {
1823   SMESH_TNodeXYZ p1( n1 ), p2( n2 );
1824   gp_Pnt      middle = 0.5 * p1 + 0.5 * p2;
1825   SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1826
1827   // To find position on edge and 3D position for n12,
1828   // project <middle> to 2 edges and select projection most close to <middle>
1829
1830   TopoDS_Edge bestEdge;
1831   double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4], f,l;
1832
1833   // get shapes under the nodes
1834   TopoDS_Shape shape[2];
1835   int nbShapes = 0;
1836   for ( int is2nd = 0; is2nd < 2; ++is2nd )
1837   {
1838     const SMDS_MeshNode* n = is2nd ? n2 : n1;
1839     TopoDS_Shape S = GetSubShapeByNode( n, GetMeshDS() );
1840     if ( !S.IsNull() )
1841       shape[ nbShapes++ ] = S;
1842   }
1843   // get EDGEs
1844   vector< TopoDS_Shape > edges;
1845   for ( int iS = 0; iS < nbShapes; ++iS )
1846   {
1847     switch ( shape[iS].ShapeType() ) {
1848     case TopAbs_EDGE:
1849     {
1850       edges.push_back( shape[iS] );
1851       break;
1852     }
1853     case TopAbs_VERTEX:
1854     {
1855       TopoDS_Shape edge;
1856       if ( nbShapes == 2 && iS==0 && shape[1-iS].ShapeType() == TopAbs_VERTEX )
1857         edge = GetCommonAncestor( shape[iS], shape[1-iS], *myMesh, TopAbs_EDGE );
1858
1859       if ( edge.IsNull() )
1860       {
1861         PShapeIteratorPtr eIt = GetAncestors( shape[iS], *myMesh, TopAbs_EDGE );
1862         while( const TopoDS_Shape* e = eIt->next() )
1863           edges.push_back( *e );
1864       }
1865       break;
1866     }
1867     case TopAbs_FACE:
1868     {
1869       if ( nbShapes == 1 || shape[1-iS].ShapeType() < TopAbs_EDGE )
1870         for ( TopExp_Explorer e( shape[iS], TopAbs_EDGE ); e.More(); e.Next() )
1871           edges.push_back( e.Current() );
1872       break;
1873     }
1874     default:
1875       continue;
1876     }
1877   }
1878   // project to get U of projection and distance from middle to projection
1879   for ( size_t iE = 0; iE < edges.size(); ++iE )
1880   {
1881     const TopoDS_Edge& edge = TopoDS::Edge( edges[ iE ]);
1882     distXYZ[0] = distMiddleProj;
1883     double testU = 0;
1884     CheckNodeU( edge, n12, testU, 2 * BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1885     if ( distXYZ[0] < distMiddleProj )
1886     {
1887       distMiddleProj = distXYZ[0];
1888       u = testU;
1889       bestEdge = edge;
1890     }
1891   }
1892   // {
1893   //   // both projections failed; set n12 on the edge of n1 with U of a common vertex
1894   //   TopoDS_Vertex vCommon;
1895   //   if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1896   //     u = BRep_Tool::Parameter( vCommon, edges[0] );
1897   //   else
1898   //   {
1899   //     double f,l, u0 = GetNodeU( edges[0], n1 );
1900   //     BRep_Tool::Range( edges[0],f,l );
1901   //     u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1902   //   }
1903   //   iOkEdge = 0;
1904   //   distMiddleProj = 0;
1905   // }
1906
1907   if ( !bestEdge.IsNull() )
1908   {
1909     // move n12 to position of a successful projection
1910     //double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1911     if ( !force3d /*&& distMiddleProj > 2*tol*/ )
1912     {
1913       TopLoc_Location loc;
1914       Handle(Geom_Curve) curve = BRep_Tool::Curve( bestEdge,loc,f,l );
1915       gp_Pnt p = curve->Value( u ).Transformed( loc );
1916       GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1917     }
1918     //if ( mySetElemOnShape ) node is not elem!
1919     {
1920       int edgeID = GetMeshDS()->ShapeToIndex( bestEdge );
1921       if ( edgeID != n12->getshapeId() )
1922         GetMeshDS()->UnSetNodeOnShape( n12 );
1923       GetMeshDS()->SetNodeOnEdge(n12, edgeID, u);
1924     }
1925   }
1926   myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1927
1928   return n12;
1929 }
1930
1931 //=======================================================================
1932 //function : AddNode
1933 //purpose  : Creates a node
1934 //=======================================================================
1935
1936 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID,
1937                                            double u, double v)
1938 {
1939   SMESHDS_Mesh * meshDS = GetMeshDS();
1940   SMDS_MeshNode* node = 0;
1941   if ( ID )
1942     node = meshDS->AddNodeWithID( x, y, z, ID );
1943   else
1944     node = meshDS->AddNode( x, y, z );
1945   if ( mySetElemOnShape && myShapeID > 0 ) { // node is not elem ?
1946     switch ( myShape.ShapeType() ) {
1947     case TopAbs_SOLID:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1948     case TopAbs_SHELL:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1949     case TopAbs_FACE:   meshDS->SetNodeOnFace(   node, myShapeID, u, v); break;
1950     case TopAbs_EDGE:   meshDS->SetNodeOnEdge(   node, myShapeID, u);    break;
1951     case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID);       break;
1952     default: ;
1953     }
1954   }
1955   return node;
1956 }
1957
1958 //=======================================================================
1959 //function : AddEdge
1960 //purpose  : Creates quadratic or linear edge
1961 //=======================================================================
1962
1963 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1964                                            const SMDS_MeshNode* n2,
1965                                            const int            id,
1966                                            const bool           force3d)
1967 {
1968   SMESHDS_Mesh * meshDS = GetMeshDS();
1969   
1970   SMDS_MeshEdge* edge = 0;
1971   if (myCreateQuadratic) {
1972     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1973     if(id)
1974       edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1975     else
1976       edge = meshDS->AddEdge(n1, n2, n12);
1977   }
1978   else {
1979     if(id)
1980       edge = meshDS->AddEdgeWithID(n1, n2, id);
1981     else
1982       edge = meshDS->AddEdge(n1, n2);
1983   }
1984
1985   if ( mySetElemOnShape && myShapeID > 0 )
1986     meshDS->SetMeshElementOnShape( edge, myShapeID );
1987
1988   return edge;
1989 }
1990
1991 //=======================================================================
1992 //function : AddFace
1993 //purpose  : Creates quadratic or linear triangle
1994 //=======================================================================
1995
1996 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1997                                            const SMDS_MeshNode* n2,
1998                                            const SMDS_MeshNode* n3,
1999                                            const int id,
2000                                            const bool force3d)
2001 {
2002   SMESHDS_Mesh * meshDS = GetMeshDS();
2003   SMDS_MeshFace* elem = 0;
2004
2005   if( n1==n2 || n2==n3 || n3==n1 )
2006     return elem;
2007
2008   if(!myCreateQuadratic) {
2009     if(id)
2010       elem = meshDS->AddFaceWithID(n1, n2, n3, id);
2011     else
2012       elem = meshDS->AddFace(n1, n2, n3);
2013   }
2014   else {
2015     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
2016     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_FACE );
2017     const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_FACE );
2018     if(myCreateBiQuadratic)
2019     {
2020      const SMDS_MeshNode* nCenter = GetCentralNode(n1, n2, n3, n12, n23, n31, force3d);
2021      if(id)
2022        elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, nCenter, id);
2023      else
2024        elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31, nCenter);
2025     }
2026     else
2027     {
2028       if(id)
2029         elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
2030       else
2031         elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
2032     }
2033   }
2034   if ( mySetElemOnShape && myShapeID > 0 )
2035     meshDS->SetMeshElementOnShape( elem, myShapeID );
2036
2037   return elem;
2038 }
2039
2040 //=======================================================================
2041 //function : AddFace
2042 //purpose  : Creates bi-quadratic, quadratic or linear quadrangle
2043 //=======================================================================
2044
2045 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
2046                                            const SMDS_MeshNode* n2,
2047                                            const SMDS_MeshNode* n3,
2048                                            const SMDS_MeshNode* n4,
2049                                            const int            id,
2050                                            const bool           force3d)
2051 {
2052   SMESHDS_Mesh * meshDS = GetMeshDS();
2053   SMDS_MeshFace* elem = 0;
2054
2055   if( n1==n2 ) {
2056     return AddFace(n1,n3,n4,id,force3d);
2057   }
2058   if( n1==n3 ) {
2059     return AddFace(n1,n2,n4,id,force3d);
2060   }
2061   if( n1==n4 ) {
2062     return AddFace(n1,n2,n3,id,force3d);
2063   }
2064   if( n2==n3 ) {
2065     return AddFace(n1,n2,n4,id,force3d);
2066   }
2067   if( n2==n4 ) {
2068     return AddFace(n1,n2,n3,id,force3d);
2069   }
2070   if( n3==n4 ) {
2071     return AddFace(n1,n2,n3,id,force3d);
2072   }
2073
2074   if(!myCreateQuadratic) {
2075     if(id)
2076       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
2077     else
2078       elem = meshDS->AddFace(n1, n2, n3, n4);
2079   }
2080   else {
2081     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
2082     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_FACE );
2083     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_FACE );
2084     const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_FACE );
2085     if(myCreateBiQuadratic)
2086     {
2087      const SMDS_MeshNode* nCenter = GetCentralNode(n1, n2, n3, n4, n12, n23, n34, n41, force3d);
2088      if(id)
2089        elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, nCenter, id);
2090      else
2091        elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41, nCenter);
2092     }
2093     else
2094     {
2095       if(id)
2096         elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
2097       else
2098         elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
2099     }
2100   }
2101   if ( mySetElemOnShape && myShapeID > 0 )
2102     meshDS->SetMeshElementOnShape( elem, myShapeID );
2103
2104   return elem;
2105 }
2106
2107 //=======================================================================
2108 //function : AddPolygonalFace
2109 //purpose  : Creates polygon, with additional nodes in quadratic mesh
2110 //=======================================================================
2111
2112 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
2113                                                      const int                           id,
2114                                                      const bool                          force3d)
2115 {
2116   SMESHDS_Mesh * meshDS = GetMeshDS();
2117   SMDS_MeshFace* elem = 0;
2118
2119   if(!myCreateQuadratic)
2120   {
2121     if(id)
2122       elem = meshDS->AddPolygonalFaceWithID(nodes, id);
2123     else
2124       elem = meshDS->AddPolygonalFace(nodes);
2125   }
2126   else
2127   {
2128     vector<const SMDS_MeshNode*> newNodes( nodes.size() * 2 );
2129     newNodes = nodes;
2130     for ( size_t i = 0; i < nodes.size(); ++i )
2131     {
2132       const SMDS_MeshNode* n1 = nodes[i];
2133       const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
2134       const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
2135       newNodes.push_back( n12 );
2136     }
2137     if(id)
2138       elem = meshDS->AddQuadPolygonalFaceWithID(newNodes, id);
2139     else
2140       elem = meshDS->AddQuadPolygonalFace(newNodes);
2141   }
2142   if ( mySetElemOnShape && myShapeID > 0 )
2143     meshDS->SetMeshElementOnShape( elem, myShapeID );
2144
2145   return elem;
2146 }
2147
2148 //=======================================================================
2149 //function : AddVolume
2150 //purpose  : Creates quadratic or linear prism
2151 //=======================================================================
2152
2153 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2154                                                const SMDS_MeshNode* n2,
2155                                                const SMDS_MeshNode* n3,
2156                                                const SMDS_MeshNode* n4,
2157                                                const SMDS_MeshNode* n5,
2158                                                const SMDS_MeshNode* n6,
2159                                                const int id,
2160                                                const bool force3d)
2161 {
2162   SMESHDS_Mesh * meshDS = GetMeshDS();
2163   SMDS_MeshVolume* elem = 0;
2164   if(!myCreateQuadratic) {
2165     if(id)
2166       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
2167     else
2168       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
2169   }
2170   else {
2171     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2172     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2173     const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_SOLID );
2174
2175     const SMDS_MeshNode* n45 = GetMediumNode( n4, n5, force3d, TopAbs_SOLID );
2176     const SMDS_MeshNode* n56 = GetMediumNode( n5, n6, force3d, TopAbs_SOLID );
2177     const SMDS_MeshNode* n64 = GetMediumNode( n6, n4, force3d, TopAbs_SOLID );
2178
2179     const SMDS_MeshNode* n14 = GetMediumNode( n1, n4, force3d, TopAbs_SOLID );
2180     const SMDS_MeshNode* n25 = GetMediumNode( n2, n5, force3d, TopAbs_SOLID );
2181     const SMDS_MeshNode* n36 = GetMediumNode( n3, n6, force3d, TopAbs_SOLID );
2182     if ( myCreateBiQuadratic )
2183     {
2184       const SMDS_MeshNode* n1245 = GetCentralNode( n1,n2,n4,n5,n12,n25,n45,n14,force3d );
2185       const SMDS_MeshNode* n1346 = GetCentralNode( n1,n3,n4,n6,n31,n36,n64,n14,force3d );
2186       const SMDS_MeshNode* n2356 = GetCentralNode( n2,n3,n6,n5,n23,n36,n56,n25,force3d );
2187
2188       if(id)
2189         elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
2190                                        n12, n23, n31, n45, n56, n64, n14, n25, n36,
2191                                        n1245, n2356, n1346, id);
2192       else
2193         elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
2194                                  n12, n23, n31, n45, n56, n64, n14, n25, n36,
2195                                  n1245, n2356, n1346);
2196     }
2197     else
2198       {
2199         if(id)
2200           elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
2201                                          n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
2202         else
2203           elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
2204                                    n12, n23, n31, n45, n56, n64, n14, n25, n36);
2205       }
2206   }
2207   if ( mySetElemOnShape && myShapeID > 0 )
2208     meshDS->SetMeshElementOnShape( elem, myShapeID );
2209
2210   return elem;
2211 }
2212
2213 //=======================================================================
2214 //function : AddVolume
2215 //purpose  : Creates quadratic or linear tetrahedron
2216 //=======================================================================
2217
2218 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2219                                                const SMDS_MeshNode* n2,
2220                                                const SMDS_MeshNode* n3,
2221                                                const SMDS_MeshNode* n4,
2222                                                const int id,
2223                                                const bool force3d)
2224 {
2225   SMESHDS_Mesh * meshDS = GetMeshDS();
2226   SMDS_MeshVolume* elem = 0;
2227   if(!myCreateQuadratic) {
2228     if(id)
2229       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
2230     else
2231       elem = meshDS->AddVolume(n1, n2, n3, n4);
2232   }
2233   else {
2234     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2235     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2236     const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_SOLID );
2237
2238     const SMDS_MeshNode* n14 = GetMediumNode( n1, n4, force3d, TopAbs_SOLID );
2239     const SMDS_MeshNode* n24 = GetMediumNode( n2, n4, force3d, TopAbs_SOLID );
2240     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2241
2242     if(id)
2243       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
2244     else
2245       elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
2246   }
2247   if ( mySetElemOnShape && myShapeID > 0 )
2248     meshDS->SetMeshElementOnShape( elem, myShapeID );
2249
2250   return elem;
2251 }
2252
2253 //=======================================================================
2254 //function : AddVolume
2255 //purpose  : Creates quadratic or linear pyramid
2256 //=======================================================================
2257
2258 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2259                                                const SMDS_MeshNode* n2,
2260                                                const SMDS_MeshNode* n3,
2261                                                const SMDS_MeshNode* n4,
2262                                                const SMDS_MeshNode* n5,
2263                                                const int id,
2264                                                const bool force3d)
2265 {
2266   SMDS_MeshVolume* elem = 0;
2267   if(!myCreateQuadratic) {
2268     if(id)
2269       elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
2270     else
2271       elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
2272   }
2273   else {
2274     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2275     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2276     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2277     const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_SOLID );
2278
2279     const SMDS_MeshNode* n15 = GetMediumNode( n1, n5, force3d, TopAbs_SOLID );
2280     const SMDS_MeshNode* n25 = GetMediumNode( n2, n5, force3d, TopAbs_SOLID );
2281     const SMDS_MeshNode* n35 = GetMediumNode( n3, n5, force3d, TopAbs_SOLID );
2282     const SMDS_MeshNode* n45 = GetMediumNode( n4, n5, force3d, TopAbs_SOLID );
2283
2284     if(id)
2285       elem = GetMeshDS()->AddVolumeWithID ( n1,  n2,  n3,  n4,  n5,
2286                                             n12, n23, n34, n41,
2287                                             n15, n25, n35, n45,
2288                                             id);
2289     else
2290       elem = GetMeshDS()->AddVolume( n1,  n2,  n3,  n4,  n5,
2291                                      n12, n23, n34, n41,
2292                                      n15, n25, n35, n45);
2293   }
2294   if ( mySetElemOnShape && myShapeID > 0 )
2295     GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
2296
2297   return elem;
2298 }
2299
2300 //=======================================================================
2301 //function : AddVolume
2302 //purpose  : Creates tri-quadratic, quadratic or linear hexahedron
2303 //=======================================================================
2304
2305 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2306                                                const SMDS_MeshNode* n2,
2307                                                const SMDS_MeshNode* n3,
2308                                                const SMDS_MeshNode* n4,
2309                                                const SMDS_MeshNode* n5,
2310                                                const SMDS_MeshNode* n6,
2311                                                const SMDS_MeshNode* n7,
2312                                                const SMDS_MeshNode* n8,
2313                                                const int id,
2314                                                const bool force3d)
2315 {
2316   SMESHDS_Mesh * meshDS = GetMeshDS();
2317   SMDS_MeshVolume* elem = 0;
2318   if(!myCreateQuadratic) {
2319     if(id)
2320       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
2321     else
2322       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
2323   }
2324   else {
2325     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2326     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2327     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2328     const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_SOLID );
2329
2330     const SMDS_MeshNode* n56 = GetMediumNode( n5, n6, force3d, TopAbs_SOLID );
2331     const SMDS_MeshNode* n67 = GetMediumNode( n6, n7, force3d, TopAbs_SOLID );
2332     const SMDS_MeshNode* n78 = GetMediumNode( n7, n8, force3d, TopAbs_SOLID );
2333     const SMDS_MeshNode* n85 = GetMediumNode( n8, n5, force3d, TopAbs_SOLID );
2334
2335     const SMDS_MeshNode* n15 = GetMediumNode( n1, n5, force3d, TopAbs_SOLID );
2336     const SMDS_MeshNode* n26 = GetMediumNode( n2, n6, force3d, TopAbs_SOLID );
2337     const SMDS_MeshNode* n37 = GetMediumNode( n3, n7, force3d, TopAbs_SOLID );
2338     const SMDS_MeshNode* n48 = GetMediumNode( n4, n8, force3d, TopAbs_SOLID );
2339     if ( myCreateBiQuadratic )
2340     {
2341       const SMDS_MeshNode* n1234 = GetCentralNode( n1,n2,n3,n4,n12,n23,n34,n41,force3d );
2342       const SMDS_MeshNode* n1256 = GetCentralNode( n1,n2,n5,n6,n12,n26,n56,n15,force3d );
2343       const SMDS_MeshNode* n2367 = GetCentralNode( n2,n3,n6,n7,n23,n37,n67,n26,force3d );
2344       const SMDS_MeshNode* n3478 = GetCentralNode( n3,n4,n7,n8,n34,n48,n78,n37,force3d );
2345       const SMDS_MeshNode* n1458 = GetCentralNode( n1,n4,n5,n8,n41,n48,n15,n85,force3d );
2346       const SMDS_MeshNode* n5678 = GetCentralNode( n5,n6,n7,n8,n56,n67,n78,n85,force3d );
2347
2348       vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
2349
2350       pointsOnShapes[ SMESH_Block::ID_V000 ] = SMESH_TNodeXYZ( n4 );
2351       pointsOnShapes[ SMESH_Block::ID_V100 ] = SMESH_TNodeXYZ( n8 );
2352       pointsOnShapes[ SMESH_Block::ID_V010 ] = SMESH_TNodeXYZ( n3 );
2353       pointsOnShapes[ SMESH_Block::ID_V110 ] = SMESH_TNodeXYZ( n7 );
2354       pointsOnShapes[ SMESH_Block::ID_V001 ] = SMESH_TNodeXYZ( n1 );
2355       pointsOnShapes[ SMESH_Block::ID_V101 ] = SMESH_TNodeXYZ( n5 );
2356       pointsOnShapes[ SMESH_Block::ID_V011 ] = SMESH_TNodeXYZ( n2 );
2357       pointsOnShapes[ SMESH_Block::ID_V111 ] = SMESH_TNodeXYZ( n6 );
2358
2359       pointsOnShapes[ SMESH_Block::ID_Ex00 ] = SMESH_TNodeXYZ( n48 );
2360       pointsOnShapes[ SMESH_Block::ID_Ex10 ] = SMESH_TNodeXYZ( n37 );
2361       pointsOnShapes[ SMESH_Block::ID_E0y0 ] = SMESH_TNodeXYZ( n15 );
2362       pointsOnShapes[ SMESH_Block::ID_E1y0 ] = SMESH_TNodeXYZ( n26 );
2363       pointsOnShapes[ SMESH_Block::ID_Ex01 ] = SMESH_TNodeXYZ( n34 );
2364       pointsOnShapes[ SMESH_Block::ID_Ex11 ] = SMESH_TNodeXYZ( n78 );
2365       pointsOnShapes[ SMESH_Block::ID_E0y1 ] = SMESH_TNodeXYZ( n12 );
2366       pointsOnShapes[ SMESH_Block::ID_E1y1 ] = SMESH_TNodeXYZ( n56 );
2367       pointsOnShapes[ SMESH_Block::ID_E00z ] = SMESH_TNodeXYZ( n41 );
2368       pointsOnShapes[ SMESH_Block::ID_E10z ] = SMESH_TNodeXYZ( n85 );
2369       pointsOnShapes[ SMESH_Block::ID_E01z ] = SMESH_TNodeXYZ( n23 );
2370       pointsOnShapes[ SMESH_Block::ID_E11z ] = SMESH_TNodeXYZ( n67 );
2371
2372       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = SMESH_TNodeXYZ( n3478 );
2373       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = SMESH_TNodeXYZ( n1256 );
2374       pointsOnShapes[ SMESH_Block::ID_Fx0z ] = SMESH_TNodeXYZ( n1458 );
2375       pointsOnShapes[ SMESH_Block::ID_Fx1z ] = SMESH_TNodeXYZ( n2367 );
2376       pointsOnShapes[ SMESH_Block::ID_F0yz ] = SMESH_TNodeXYZ( n1234 );
2377       pointsOnShapes[ SMESH_Block::ID_F1yz ] = SMESH_TNodeXYZ( n5678 );
2378
2379       gp_XYZ centerCube(0.5, 0.5, 0.5);
2380       gp_XYZ nCenterElem;
2381       SMESH_Block::ShellPoint( centerCube, pointsOnShapes, nCenterElem );
2382       const SMDS_MeshNode* nCenter =
2383         meshDS->AddNode( nCenterElem.X(), nCenterElem.Y(), nCenterElem.Z() );
2384       meshDS->SetNodeInVolume( nCenter, myShapeID );
2385
2386       if(id)
2387         elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
2388                                        n12, n23, n34, n41, n56, n67,
2389                                        n78, n85, n15, n26, n37, n48,
2390                                        n1234, n1256, n2367, n3478, n1458, n5678, nCenter, id);
2391       else
2392         elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
2393                                  n12, n23, n34, n41, n56, n67,
2394                                  n78, n85, n15, n26, n37, n48,
2395                                  n1234, n1256, n2367, n3478, n1458, n5678, nCenter);
2396     }
2397     else
2398     {
2399       if(id)
2400         elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
2401                                        n12, n23, n34, n41, n56, n67,
2402                                        n78, n85, n15, n26, n37, n48, id);
2403       else
2404         elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
2405                                  n12, n23, n34, n41, n56, n67,
2406                                  n78, n85, n15, n26, n37, n48);
2407     }
2408   }
2409   if ( mySetElemOnShape && myShapeID > 0 )
2410     meshDS->SetMeshElementOnShape( elem, myShapeID );
2411
2412   return elem;
2413 }
2414
2415 //=======================================================================
2416 //function : AddVolume
2417 //purpose  : Creates LINEAR!!!!!!!!! octahedron
2418 //=======================================================================
2419
2420 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2421                                                const SMDS_MeshNode* n2,
2422                                                const SMDS_MeshNode* n3,
2423                                                const SMDS_MeshNode* n4,
2424                                                const SMDS_MeshNode* n5,
2425                                                const SMDS_MeshNode* n6,
2426                                                const SMDS_MeshNode* n7,
2427                                                const SMDS_MeshNode* n8,
2428                                                const SMDS_MeshNode* n9,
2429                                                const SMDS_MeshNode* n10,
2430                                                const SMDS_MeshNode* n11,
2431                                                const SMDS_MeshNode* n12,
2432                                                const int id, 
2433                                                bool force3d)
2434 {
2435   SMESHDS_Mesh * meshDS = GetMeshDS();
2436   SMDS_MeshVolume* elem = 0;
2437   if(id)
2438     elem = meshDS->AddVolumeWithID(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,id);
2439   else
2440     elem = meshDS->AddVolume(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12);
2441   if ( mySetElemOnShape && myShapeID > 0 )
2442     meshDS->SetMeshElementOnShape( elem, myShapeID );
2443   return elem;
2444 }
2445
2446 //=======================================================================
2447 //function : AddPolyhedralVolume
2448 //purpose  : Creates polyhedron. In quadratic mesh, adds medium nodes
2449 //=======================================================================
2450
2451 SMDS_MeshVolume*
2452 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
2453                                          const std::vector<int>&                  quantities,
2454                                          const int                                id,
2455                                          const bool                               force3d)
2456 {
2457   SMESHDS_Mesh * meshDS = GetMeshDS();
2458   SMDS_MeshVolume* elem = 0;
2459   if(!myCreateQuadratic)
2460   {
2461     if(id)
2462       elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
2463     else
2464       elem = meshDS->AddPolyhedralVolume(nodes, quantities);
2465   }
2466   else
2467   {
2468     vector<const SMDS_MeshNode*> newNodes;
2469     vector<int> newQuantities;
2470     for ( size_t iFace = 0, iN = 0; iFace < quantities.size(); ++iFace )
2471     {
2472       int nbNodesInFace = quantities[iFace];
2473       newQuantities.push_back(0);
2474       for ( int i = 0; i < nbNodesInFace; ++i )
2475       {
2476         const SMDS_MeshNode* n1 = nodes[ iN + i ];
2477         newNodes.push_back( n1 );
2478         newQuantities.back()++;
2479
2480         const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
2481         // if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
2482         //      n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
2483         {
2484           const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2485           newNodes.push_back( n12 );
2486           newQuantities.back()++;
2487         }
2488       }
2489       iN += nbNodesInFace;
2490     }
2491     if(id)
2492       elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
2493     else
2494       elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
2495   }
2496   if ( mySetElemOnShape && myShapeID > 0 )
2497     meshDS->SetMeshElementOnShape( elem, myShapeID );
2498
2499   return elem;
2500 }
2501
2502 namespace
2503 {
2504   //================================================================================
2505   /*!
2506    * \brief Check if a node belongs to any face of sub-mesh
2507    */
2508   //================================================================================
2509
2510   bool isNodeInSubMesh( const SMDS_MeshNode* n, const SMESHDS_SubMesh* sm )
2511   {
2512     SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
2513     while ( fIt->more() )
2514       if ( sm->Contains( fIt->next() ))
2515         return true;
2516     return false;
2517   }
2518 }
2519
2520 //=======================================================================
2521 //function : IsSameElemGeometry
2522 //purpose  : Returns true if all elements of a sub-mesh are of same shape
2523 //=======================================================================
2524
2525 bool SMESH_MesherHelper::IsSameElemGeometry(const SMESHDS_SubMesh* smDS,
2526                                             SMDSAbs_GeometryType   shape,
2527                                             const bool             nullSubMeshRes)
2528 {
2529   if ( !smDS ) return nullSubMeshRes;
2530
2531   SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
2532   while ( elemIt->more() ) {
2533     const SMDS_MeshElement* e = elemIt->next();
2534     if ( e->GetGeomType() != shape )
2535       return false;
2536   }
2537   return true;
2538 }
2539
2540 //=======================================================================
2541 //function : LoadNodeColumns
2542 //purpose  : Load nodes bound to face into a map of node columns
2543 //=======================================================================
2544
2545 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
2546                                          const TopoDS_Face& theFace,
2547                                          const TopoDS_Edge& theBaseEdge,
2548                                          SMESHDS_Mesh*      theMesh,
2549                                          SMESH_ProxyMesh*   theProxyMesh)
2550 {
2551   return LoadNodeColumns(theParam2ColumnMap,
2552                          theFace,
2553                          std::list<TopoDS_Edge>(1,theBaseEdge),
2554                          theMesh,
2555                          theProxyMesh);
2556 }
2557
2558 //=======================================================================
2559 //function : LoadNodeColumns
2560 //purpose  : Load nodes bound to face into a map of node columns
2561 //=======================================================================
2562
2563 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap &            theParam2ColumnMap,
2564                                          const TopoDS_Face&            theFace,
2565                                          const std::list<TopoDS_Edge>& theBaseSide,
2566                                          SMESHDS_Mesh*                 theMesh,
2567                                          SMESH_ProxyMesh*              theProxyMesh)
2568 {
2569   // get a right sub-mesh of theFace
2570
2571   const SMESHDS_SubMesh* faceSubMesh = 0;
2572   if ( theProxyMesh )
2573   {
2574     faceSubMesh = theProxyMesh->GetSubMesh( theFace );
2575     if ( !faceSubMesh ||
2576          faceSubMesh->NbElements() == 0 ||
2577          theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
2578     {
2579       // can use a proxy sub-mesh with not temporary elements only
2580       faceSubMesh = 0;
2581       theProxyMesh = 0;
2582     }
2583   }
2584   if ( !faceSubMesh )
2585     faceSubMesh = theMesh->MeshElements( theFace );
2586   if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
2587     return false;
2588
2589   if ( theParam2ColumnMap.empty() )
2590   {
2591     // get data of edges for normalization of params
2592     vector< double > length;
2593     double fullLen = 0;
2594     list<TopoDS_Edge>::const_iterator edge;
2595     {
2596       for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
2597       {
2598         double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
2599         fullLen += len;
2600         length.push_back( len );
2601       }
2602     }
2603
2604     // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
2605     const SMDS_MeshNode* prevEndNodes[2] = { 0, 0 };
2606     edge = theBaseSide.begin();
2607     for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
2608     {
2609       map< double, const SMDS_MeshNode*> sortedBaseNN;
2610       SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN );
2611
2612       map< double, const SMDS_MeshNode*>::iterator u_n;
2613       // pb with mesh_Projection_2D_00/A1 fixed by adding expectedSupport arg to GetMediumPos()
2614       // so the following solution is commented (hope forever :)
2615       //
2616       // SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN,
2617       // // SMDSAbs_Edge here is needed to be coherent with
2618       // // StdMeshers_FaceSide used by Quadrangle to get nodes
2619       // // on EDGE; else pb in mesh_Projection_2D_00/A1 where a
2620       // // medium node on EDGE is medium in a triangle but not
2621       // // in a segment
2622       // SMDSAbs_Edge );
2623       // if ( faceSubMesh->GetElements()->next()->IsQuadratic() )
2624       //   // filter off nodes medium in faces on theFace (same pb with mesh_Projection_2D_00/A1)
2625       //   for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end() ;     )
2626       //   {
2627       //     const SMDS_MeshNode* node = u_n->second;
2628       //     SMDS_ElemIteratorPtr faceIt = node->GetInverseElementIterator( SMDSAbs_Face );
2629       //     if ( faceIt->more() && node ) {
2630       //       const SMDS_MeshElement* face = faceIt->next();
2631       //       if ( faceSubMesh->Contains( face ) && face->IsMediumNode( node ))
2632       //         node = 0;
2633       //     }
2634       //     if ( !node )
2635       //       sortedBaseNN.erase( u_n++ );
2636       //     else
2637       //       ++u_n;
2638       //   }
2639       if ( sortedBaseNN.empty() ) continue;
2640
2641       u_n = sortedBaseNN.begin();
2642       if ( theProxyMesh ) // from sortedBaseNN remove nodes not shared by faces of faceSubMesh
2643       {
2644         const SMDS_MeshNode* n1 = (++sortedBaseNN.begin())->second;
2645         const SMDS_MeshNode* n2 = (++sortedBaseNN.rbegin())->second;
2646         bool allNodesAreProxy = ( n1 != theProxyMesh->GetProxyNode( n1 ) &&
2647                                   n2 != theProxyMesh->GetProxyNode( n2 ));
2648         if ( allNodesAreProxy )
2649           for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
2650             u_n->second = theProxyMesh->GetProxyNode( u_n->second );
2651
2652         if ( u_n = sortedBaseNN.begin(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
2653         {
2654           while ( ++u_n != sortedBaseNN.end() && !isNodeInSubMesh( u_n->second, faceSubMesh ));
2655           sortedBaseNN.erase( sortedBaseNN.begin(), u_n );
2656         }
2657         if ( !sortedBaseNN.empty() )
2658           if ( u_n = --sortedBaseNN.end(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
2659           {
2660             while ( u_n != sortedBaseNN.begin() && !isNodeInSubMesh( (--u_n)->second, faceSubMesh ));
2661             sortedBaseNN.erase( ++u_n, sortedBaseNN.end() );
2662           }
2663         if ( sortedBaseNN.empty() ) continue;
2664       }
2665
2666       double f, l;
2667       BRep_Tool::Range( *edge, f, l );
2668       if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
2669       const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
2670       const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
2671       for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
2672       {
2673         if ( u_n->second == prevEndNodes[0] ||
2674              u_n->second == prevEndNodes[1] )
2675           continue;
2676         double par = prevPar + coeff * ( u_n->first - f );
2677         TParam2ColumnMap::iterator u2nn =
2678           theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
2679         u2nn->second.push_back( u_n->second );
2680       }
2681       prevEndNodes[0] = sortedBaseNN.begin()->second;
2682       prevEndNodes[1] = sortedBaseNN.rbegin()->second;
2683     }
2684     if ( theParam2ColumnMap.size() < 2 )
2685       return false;
2686   }
2687
2688   // nb rows of nodes
2689   size_t prevNbRows   = theParam2ColumnMap.begin()->second.size(); // current, at least 1 here
2690   size_t expectNbRows = faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 ); // to be added
2691
2692   // fill theParam2ColumnMap column by column by passing from nodes on
2693   // theBaseEdge up via mesh faces on theFace
2694
2695   TParam2ColumnMap::iterator par_nVec_1, par_nVec_2;
2696   par_nVec_2 = theParam2ColumnMap.begin();
2697   par_nVec_1 = par_nVec_2++;
2698   TIDSortedElemSet emptySet, avoidSet;
2699   for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
2700   {
2701     vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
2702     vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
2703     nCol1.resize( prevNbRows + expectNbRows );
2704     nCol2.resize( prevNbRows + expectNbRows );
2705
2706     int i1, i2; size_t foundNbRows = 0;
2707     const SMDS_MeshNode *n1 = nCol1[ prevNbRows-1 ];
2708     const SMDS_MeshNode *n2 = nCol2[ prevNbRows-1 ];
2709     // find face sharing node n1 and n2 and belonging to faceSubMesh
2710     while ( const SMDS_MeshElement* face =
2711             SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
2712     {
2713       if ( faceSubMesh->Contains( face ))
2714       {
2715         int nbNodes = face->NbCornerNodes();
2716         if ( nbNodes != 4 )
2717           return false;
2718         if ( foundNbRows + 1 > expectNbRows )
2719           return false;
2720         n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
2721         n2 = face->GetNode( (i1+2) % 4 );
2722         nCol1[ prevNbRows + foundNbRows] = n1;
2723         nCol2[ prevNbRows + foundNbRows] = n2;
2724         ++foundNbRows;
2725       }
2726       avoidSet.insert( face );
2727     }
2728     if ((size_t) foundNbRows != expectNbRows )
2729       return false;
2730     avoidSet.clear();
2731   }
2732   return ( theParam2ColumnMap.size() > 1 &&
2733            theParam2ColumnMap.begin()->second.size() == prevNbRows + expectNbRows );
2734 }
2735
2736 namespace
2737 {
2738   //================================================================================
2739   /*!
2740    * \brief Return true if a node is at a corner of a 2D structured mesh of FACE
2741    */
2742   //================================================================================
2743
2744   bool isCornerOfStructure( const SMDS_MeshNode*   n,
2745                             const SMESHDS_SubMesh* faceSM,
2746                             SMESH_MesherHelper&    faceAnalyser )
2747   {
2748     int nbFacesInSM = 0;
2749     if ( n ) {
2750       SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
2751       while ( fIt->more() )
2752         nbFacesInSM += faceSM->Contains( fIt->next() );
2753     }
2754     if ( nbFacesInSM == 1 )
2755       return true;
2756
2757     if ( nbFacesInSM == 2 && n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
2758     {
2759       return faceAnalyser.IsRealSeam( n->getshapeId() );
2760     }
2761     return false;
2762   }
2763 }
2764
2765 //=======================================================================
2766 //function : IsStructured
2767 //purpose  : Return true if 2D mesh on FACE is a structured rectangle
2768 //=======================================================================
2769
2770 bool SMESH_MesherHelper::IsStructured( SMESH_subMesh* faceSM )
2771 {
2772   SMESHDS_SubMesh* fSM = faceSM->GetSubMeshDS();
2773   if ( !fSM || fSM->NbElements() == 0 )
2774     return false;
2775
2776   list< TopoDS_Edge > edges;
2777   list< int > nbEdgesInWires;
2778   int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( faceSM->GetSubShape() ),
2779                                               edges, nbEdgesInWires );
2780   if ( nbWires != 1 /*|| nbEdgesInWires.front() != 4*/ ) // allow composite sides
2781     return false;
2782
2783   // algo: find corners of a structure and then analyze nb of faces and
2784   // length of structure sides
2785
2786   SMESHDS_Mesh* meshDS = faceSM->GetFather()->GetMeshDS();
2787   SMESH_MesherHelper faceAnalyser( *faceSM->GetFather() );
2788   faceAnalyser.SetSubShape( faceSM->GetSubShape() );
2789
2790   // rotate edges to get the first node being at corner
2791   // (in principle it's not necessary because so far none SALOME algo can make
2792   //  such a structured mesh that all corner nodes are not on VERTEXes)
2793   bool isCorner     = false;
2794   int nbRemainEdges = nbEdgesInWires.front();
2795   do {
2796     TopoDS_Vertex V = IthVertex( 0, edges.front() );
2797     isCorner = isCornerOfStructure( SMESH_Algo::VertexNode( V, meshDS ),
2798                                     fSM, faceAnalyser);
2799     if ( !isCorner ) {
2800       edges.splice( edges.end(), edges, edges.begin() );
2801       --nbRemainEdges;
2802     }
2803   }
2804   while ( !isCorner && nbRemainEdges > 0 );
2805
2806   if ( !isCorner )
2807     return false;
2808
2809   // get all nodes from EDGEs
2810   list< const SMDS_MeshNode* > nodes;
2811   list< TopoDS_Edge >::iterator edge = edges.begin();
2812   for ( ; edge != edges.end(); ++edge )
2813   {
2814     map< double, const SMDS_MeshNode* > u2Nodes;
2815     if ( !SMESH_Algo::GetSortedNodesOnEdge( meshDS, *edge,
2816                                             /*skipMedium=*/true, u2Nodes ))
2817       return false;
2818
2819     list< const SMDS_MeshNode* > edgeNodes;
2820     map< double, const SMDS_MeshNode* >::iterator u2n = u2Nodes.begin();
2821     for ( ; u2n != u2Nodes.end(); ++u2n )
2822       edgeNodes.push_back( u2n->second );
2823     if ( edge->Orientation() == TopAbs_REVERSED )
2824       edgeNodes.reverse();
2825
2826     if ( !nodes.empty() && nodes.back() == edgeNodes.front() )
2827       edgeNodes.pop_front();
2828     nodes.splice( nodes.end(), edgeNodes, edgeNodes.begin(), edgeNodes.end() );
2829   }
2830
2831   // get length of structured sides
2832   vector<int> nbEdgesInSide;
2833   int nbEdges = 0;
2834   list< const SMDS_MeshNode* >::iterator n = ++nodes.begin();
2835   for ( ; n != nodes.end(); ++n )
2836   {
2837     ++nbEdges;
2838     if ( isCornerOfStructure( *n, fSM, faceAnalyser )) {
2839       nbEdgesInSide.push_back( nbEdges );
2840       nbEdges = 0;
2841     }
2842   }
2843
2844   // checks
2845   if ( nbEdgesInSide.size() != 4 )
2846     return false;
2847   if ( nbEdgesInSide[0] != nbEdgesInSide[2] )
2848     return false;
2849   if ( nbEdgesInSide[1] != nbEdgesInSide[3] )
2850     return false;
2851   if ( nbEdgesInSide[0] * nbEdgesInSide[1] != fSM->NbElements() )
2852     return false;
2853
2854   return true;
2855 }
2856
2857 //=======================================================================
2858 //function : IsDistorted2D
2859 //purpose  : Return true if 2D mesh on FACE is ditorted
2860 //=======================================================================
2861
2862 bool SMESH_MesherHelper::IsDistorted2D( SMESH_subMesh*      faceSM,
2863                                         bool                checkUV,
2864                                         SMESH_MesherHelper* faceHelper)
2865 {
2866   if ( !faceSM || faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2867     return false;
2868
2869   bool haveBadFaces = false;
2870
2871   SMESH_MesherHelper helper( *faceSM->GetFather() );
2872   if ( faceHelper )
2873     helper.CopySubShapeInfo( *faceHelper );
2874   helper.SetSubShape( faceSM->GetSubShape() );
2875
2876   const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
2877   SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( F );
2878   if ( !smDS || smDS->NbElements() == 0 ) return false;
2879
2880   bool subIdsValid = true; // shape ID of nodes is OK
2881   if ( helper.HasSeam() )
2882   {
2883     // check if nodes are bound to seam edges
2884     SMESH_subMeshIteratorPtr smIt = faceSM->getDependsOnIterator(/*includeSelf=*/false);
2885     while ( smIt->more() && subIdsValid )
2886     {
2887       SMESH_subMesh* sm = smIt->next();
2888       if ( helper.IsSeamShape( sm->GetId() ) && sm->IsEmpty() )
2889         subIdsValid = false;
2890     }
2891   }
2892   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2893   double prevArea = 0;
2894   vector< const SMDS_MeshNode* > nodes;
2895   vector< gp_XY >                uv;
2896   bool* toCheckUV = checkUV ? & checkUV : 0;
2897   while ( faceIt->more() && !haveBadFaces )
2898   {
2899     const SMDS_MeshElement* face = faceIt->next();
2900
2901     // get nodes
2902     nodes.resize( face->NbCornerNodes() );
2903     SMDS_MeshElement::iterator n = face->begin_nodes();
2904     for ( size_t i = 0; i < nodes.size(); ++n, ++i )
2905       nodes[ i ] = *n;
2906
2907     // avoid elems on degenarate shapes as UV on them can be wrong
2908     if ( helper.HasDegeneratedEdges() )
2909     {
2910       bool isOnDegen = false;
2911       for ( size_t i = 0; ( i < nodes.size() && !isOnDegen ); ++i )
2912         isOnDegen = helper.IsDegenShape( nodes[ i ]->getshapeId() );
2913       if ( isOnDegen )
2914         continue;
2915     }
2916     // prepare for getting UVs
2917     const SMDS_MeshNode* inFaceNode = 0;
2918     if ( helper.HasSeam() ) {
2919       for ( size_t i = 0; ( i < nodes.size() && !inFaceNode ); ++i )
2920         if ( !helper.IsSeamShape( nodes[ i ]->getshapeId() ))
2921         {
2922           inFaceNode = nodes[ i ];
2923           if ( !subIdsValid )
2924           {
2925             gp_XY uv = helper.GetNodeUV( F, inFaceNode );
2926             if ( helper.IsOnSeam( uv ))
2927               inFaceNode = NULL;
2928           }
2929         }
2930       if ( !inFaceNode )
2931         continue;
2932     }
2933     // get UVs
2934     uv.resize( nodes.size() );
2935     for ( size_t i = 0; i < nodes.size(); ++i )
2936       uv[ i ] = helper.GetNodeUV( F, nodes[ i ], inFaceNode, toCheckUV );
2937
2938     if ( !subIdsValid ) // fix uv on seam
2939     {
2940       gp_XY uvInFace = helper.GetNodeUV( F, inFaceNode );
2941       for ( size_t i = 0; i < uv.size(); ++i )
2942         if ( helper.IsOnSeam( uv[i] ))
2943           uv[i] = helper.getUVOnSeam( uv[i], uvInFace ).XY();
2944     }
2945
2946     // compare orientation of triangles
2947     double faceArea = 0;
2948     for ( int iT = 0, nbT = nodes.size()-2; iT < nbT; ++iT )
2949     {
2950       gp_XY v1 = uv[ iT+1 ] - uv[ 0 ];
2951       gp_XY v2 = uv[ iT+2 ] - uv[ 0 ];
2952       faceArea += v2 ^ v1;
2953     }
2954     haveBadFaces = ( faceArea * prevArea < 0 );
2955     prevArea = faceArea;
2956   }
2957
2958   return haveBadFaces;
2959 }
2960
2961 //================================================================================
2962 /*!
2963  * \brief Find out elements orientation on a geometrical face
2964  * \param theFace - The face correctly oriented in the shape being meshed
2965  * \retval bool - true if the face normal and the normal of first element
2966  *                in the correspoding submesh point in different directions
2967  */
2968 //================================================================================
2969
2970 bool SMESH_MesherHelper::IsReversedSubMesh (const TopoDS_Face& theFace)
2971 {
2972   if ( theFace.IsNull() )
2973     return false;
2974
2975   // find out orientation of a meshed face
2976   int faceID = GetMeshDS()->ShapeToIndex( theFace );
2977   TopoDS_Shape aMeshedFace = GetMeshDS()->IndexToShape( faceID );
2978   bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
2979
2980   const SMESHDS_SubMesh * aSubMeshDSFace = GetMeshDS()->MeshElements( faceID );
2981   if ( !aSubMeshDSFace )
2982     return isReversed;
2983
2984   // find an element on a bounday of theFace
2985   SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
2986   const SMDS_MeshNode* nn[2];
2987   while ( iteratorElem->more() ) // loop on elements on theFace
2988   {
2989     const SMDS_MeshElement* elem = iteratorElem->next();
2990     if ( ! elem ) continue;
2991
2992     // look for 2 nodes on EDGE
2993     int nbNodes = elem->NbCornerNodes();
2994     nn[0] = elem->GetNode( nbNodes-1 );
2995     for ( int iN = 0; iN < nbNodes; ++iN )
2996     {
2997       nn[1] = elem->GetNode( iN );
2998       if ( nn[0]->GetPosition()->GetDim() < 2 &&
2999            nn[1]->GetPosition()->GetDim() < 2 )
3000       {
3001         TopoDS_Shape s0 = GetSubShapeByNode( nn[0], GetMeshDS() );
3002         TopoDS_Shape s1 = GetSubShapeByNode( nn[1], GetMeshDS() );
3003         TopoDS_Shape  E = GetCommonAncestor( s0, s1, *myMesh, TopAbs_EDGE );
3004         if ( !E.IsNull() && !s0.IsSame( s1 ) && E.Orientation() != TopAbs_INTERNAL )
3005         {
3006           // is E seam edge?
3007           int nb = 0;
3008           for ( TopExp_Explorer exp( theFace, TopAbs_EDGE ); exp.More(); exp.Next() )
3009             if ( E.IsSame( exp.Current() )) {
3010               ++nb;
3011               E = exp.Current(); // to know orientation
3012             }
3013           if ( nb == 1 )
3014           {
3015             bool ok = true;
3016             double u0 = GetNodeU( TopoDS::Edge( E ), nn[0], nn[1], &ok );
3017             double u1 = GetNodeU( TopoDS::Edge( E ), nn[1], nn[0], &ok );
3018             if ( ok )
3019             {
3020               // check that the 2 nodes are connected with a segment (IPAL53055)
3021               ok = false;
3022               const SMDS_MeshElement* seg;
3023               if ( SMESHDS_SubMesh* sm = GetMeshDS()->MeshElements( E ))
3024                 if (( sm->NbElements() > 0 ) &&
3025                     ( seg = GetMeshDS()->FindEdge( nn[0], nn[1] )))
3026                   ok = sm->Contains( seg );
3027             }
3028             if ( ok )
3029             {
3030               isReversed = ( u0 > u1 );
3031               if ( E.Orientation() == TopAbs_REVERSED )
3032                 isReversed = !isReversed;
3033               return isReversed;
3034             }
3035           }
3036         }
3037       }
3038       nn[0] = nn[1];
3039     }
3040   }
3041
3042   // find an element with a good normal
3043   gp_Vec Ne;
3044   bool normalOK = false;
3045   gp_XY uv;
3046   iteratorElem = aSubMeshDSFace->GetElements();
3047   while ( !normalOK && iteratorElem->more() ) // loop on elements on theFace
3048   {
3049     const SMDS_MeshElement* elem = iteratorElem->next();
3050     if ( ! SMESH_MeshAlgos::FaceNormal( elem, const_cast<gp_XYZ&>( Ne.XYZ() ), /*normalized=*/0 ))
3051       continue;
3052     normalOK = true;
3053
3054     // get UV of a node inside theFACE
3055     SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
3056     const SMDS_MeshNode* nInFace = 0;
3057     int iPosDim = SMDS_TOP_VERTEX;
3058     while ( nodesIt->more() ) // loop on nodes
3059     {
3060       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodesIt->next() );
3061       if ( n->GetPosition()->GetTypeOfPosition() >= iPosDim )
3062       {
3063         nInFace = n;
3064         iPosDim = n->GetPosition()->GetTypeOfPosition();
3065       }
3066     }
3067     uv = GetNodeUV( theFace, nInFace, 0, &normalOK );
3068   }
3069   if ( !normalOK )
3070     return isReversed;
3071
3072   // face normal at node position
3073   TopLoc_Location loc;
3074   Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
3075   // if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 )
3076   // some surfaces not detected as GeomAbs_C1 are nevertheless correct for meshing
3077   if ( surf.IsNull() || surf->Continuity() < GeomAbs_C0 )
3078     return isReversed;
3079
3080   gp_Vec d1u, d1v; gp_Pnt p;
3081   surf->D1( uv.X(), uv.Y(), p, d1u, d1v );
3082   gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
3083
3084   if ( theFace.Orientation() == TopAbs_REVERSED )
3085     Nf.Reverse();
3086
3087   return Ne * Nf < 0.;
3088 }
3089
3090 //=======================================================================
3091 //function : Count
3092 //purpose  : Count nb of sub-shapes
3093 //=======================================================================
3094
3095 int SMESH_MesherHelper::Count(const TopoDS_Shape&    shape,
3096                               const TopAbs_ShapeEnum type,
3097                               const bool             ignoreSame)
3098 {
3099   if ( ignoreSame ) {
3100     TopTools_IndexedMapOfShape map;
3101     TopExp::MapShapes( shape, type, map );
3102     return map.Extent();
3103   }
3104   else {
3105     int nb = 0;
3106     for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
3107       ++nb;
3108     return nb;
3109   }
3110 }
3111
3112 //=======================================================================
3113 //function : NbAncestors
3114 //purpose  : Return number of unique ancestors of the shape
3115 //=======================================================================
3116
3117 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
3118                                     const SMESH_Mesh&   mesh,
3119                                     TopAbs_ShapeEnum    ancestorType/*=TopAbs_SHAPE*/)
3120 {
3121   TopTools_MapOfShape ancestors;
3122   TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
3123   for ( ; ansIt.More(); ansIt.Next() ) {
3124     if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
3125       ancestors.Add( ansIt.Value() );
3126   }
3127   return ancestors.Extent();
3128 }
3129
3130 //=======================================================================
3131 //function : GetSubShapeOri
3132 //purpose  : Return orientation of sub-shape in the main shape
3133 //=======================================================================
3134
3135 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
3136                                                       const TopoDS_Shape& subShape)
3137 {
3138   TopAbs_Orientation ori = TopAbs_Orientation(-1);
3139   if ( !shape.IsNull() && !subShape.IsNull() )
3140   {
3141     TopExp_Explorer e( shape, subShape.ShapeType() );
3142     if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
3143       e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
3144     for ( ; e.More(); e.Next())
3145       if ( subShape.IsSame( e.Current() ))
3146         break;
3147     if ( e.More() )
3148       ori = e.Current().Orientation();
3149   }
3150   return ori;
3151 }
3152
3153 //=======================================================================
3154 //function : IsSubShape
3155 //purpose  :
3156 //=======================================================================
3157
3158 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
3159                                      const TopoDS_Shape& mainShape )
3160 {
3161   if ( !shape.IsNull() && !mainShape.IsNull() )
3162   {
3163     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
3164           exp.More();
3165           exp.Next() )
3166       if ( shape.IsSame( exp.Current() ))
3167         return true;
3168   }
3169   return false;
3170 }
3171
3172 //=======================================================================
3173 //function : IsSubShape
3174 //purpose  : 
3175 //=======================================================================
3176
3177 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
3178 {
3179   if ( shape.IsNull() || !aMesh )
3180     return false;
3181   return
3182     aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
3183     // PAL16202
3184     (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
3185 }
3186
3187 //=======================================================================
3188 //function : IsBlock
3189 //purpose  : 
3190 //=======================================================================
3191
3192 bool SMESH_MesherHelper::IsBlock( const TopoDS_Shape& shape )
3193 {
3194   if ( shape.IsNull() )
3195     return false;
3196
3197   TopoDS_Shell shell;
3198   TopExp_Explorer exp( shape, TopAbs_SHELL );
3199   if ( !exp.More() ) return false;
3200   shell = TopoDS::Shell( exp.Current() );
3201   if ( exp.Next(), exp.More() ) return false;
3202
3203   TopoDS_Vertex v;
3204   TopTools_IndexedMapOfOrientedShape map;
3205   return SMESH_Block::FindBlockShapes( shell, v, v, map );
3206 }
3207
3208
3209 //================================================================================
3210 /*!
3211  * \brief Return maximal tolerance of shape
3212  */
3213 //================================================================================
3214
3215 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
3216 {
3217   double tol = Precision::Confusion();
3218   TopExp_Explorer exp;
3219   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
3220     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
3221   for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3222     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
3223   for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
3224     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
3225
3226   return tol;
3227 }
3228
3229 //================================================================================
3230 /*!
3231  * \brief Return MaxTolerance( face ), probably cached
3232  */
3233 //================================================================================
3234
3235 double SMESH_MesherHelper::getFaceMaxTol( const TopoDS_Shape& face ) const
3236 {
3237   int faceID = GetMeshDS()->ShapeToIndex( face );
3238
3239   SMESH_MesherHelper* me = const_cast< SMESH_MesherHelper* >( this );
3240   double & tol = me->myFaceMaxTol.insert( make_pair( faceID, -1. )).first->second;
3241   if ( tol < 0 )
3242     tol = MaxTolerance( face );
3243
3244   return tol;
3245 }
3246
3247 //================================================================================
3248 /*!
3249  * \brief Return an angle between two EDGEs sharing a common VERTEX with reference
3250  *        of the FACE normal
3251  *  \return double - the angle (between -Pi and Pi), negative if the angle is concave,
3252  *                   1e100 in case of failure
3253  *  \warning Care about order of the EDGEs and their orientation to be as they are
3254  *          within the FACE! Don't pass degenerated EDGEs neither!
3255  */
3256 //================================================================================
3257
3258 double SMESH_MesherHelper::GetAngle( const TopoDS_Edge &   theE1,
3259                                      const TopoDS_Edge &   theE2,
3260                                      const TopoDS_Face &   theFace,
3261                                      const TopoDS_Vertex & theCommonV,
3262                                      gp_Vec*               theFaceNormal)
3263 {
3264   double angle = 1e100;
3265   try
3266   {
3267     double f,l;
3268     Handle(Geom_Curve)     c1 = BRep_Tool::Curve( theE1, f,l );
3269     Handle(Geom_Curve)     c2 = BRep_Tool::Curve( theE2, f,l );
3270     Handle(Geom2d_Curve) c2d1 = BRep_Tool::CurveOnSurface( theE1, theFace, f,l );
3271     Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace );
3272     double                 p1 = BRep_Tool::Parameter( theCommonV, theE1 );
3273     double                 p2 = BRep_Tool::Parameter( theCommonV, theE2 );
3274     if ( c1.IsNull() || c2.IsNull() )
3275       return angle;
3276     gp_XY uv = c2d1->Value( p1 ).XY();
3277     gp_Vec du, dv; gp_Pnt p;
3278     surf->D1( uv.X(), uv.Y(), p, du, dv );
3279     gp_Vec vec1, vec2, vecRef = du ^ dv;
3280     int  nbLoops = 0;
3281     double p1tmp = p1;
3282     while ( vecRef.SquareMagnitude() < 1e-25 )
3283     {
3284       double dp = ( l - f ) / 1000.;
3285       p1tmp += dp * (( Abs( p1 - f ) > Abs( p1 - l )) ? -1. : +1.);
3286       uv = c2d1->Value( p1tmp ).XY();
3287       surf->D1( uv.X(), uv.Y(), p, du, dv );
3288       vecRef = du ^ dv;
3289       if ( ++nbLoops > 10 )
3290       {
3291 #ifdef _DEBUG_
3292         cout << "SMESH_MesherHelper::GetAngle(): Captured in a sigularity" << endl;
3293 #endif
3294         return angle;
3295       }
3296     }
3297     if ( theFace.Orientation() == TopAbs_REVERSED )
3298       vecRef.Reverse();
3299     if ( theFaceNormal ) *theFaceNormal = vecRef;
3300
3301     c1->D1( p1, p, vec1 );
3302     c2->D1( p2, p, vec2 );
3303     // TopoDS_Face F = theFace;
3304     // if ( F.Orientation() == TopAbs_INTERNAL )
3305     //   F.Orientation( TopAbs_FORWARD );
3306     if ( theE1.Orientation() /*GetSubShapeOri( F, theE1 )*/ == TopAbs_REVERSED )
3307       vec1.Reverse();
3308     if ( theE2.Orientation() /*GetSubShapeOri( F, theE2 )*/ == TopAbs_REVERSED )
3309       vec2.Reverse();
3310     angle = vec1.AngleWithRef( vec2, vecRef );
3311
3312     if ( Abs ( angle ) >= 0.99 * M_PI )
3313     {
3314       BRep_Tool::Range( theE1, f, l );
3315       p1 += 1e-7 * ( p1-f < l-p1 ? +1. : -1. );
3316       c1->D1( p1, p, vec1 );
3317       if ( theE1.Orientation() == TopAbs_REVERSED )
3318         vec1.Reverse();
3319       BRep_Tool::Range( theE2, f, l );
3320       p2 += 1e-7 * ( p2-f < l-p2 ? +1. : -1. );
3321       c2->D1( p2, p, vec2 );
3322       if ( theE2.Orientation() == TopAbs_REVERSED )
3323         vec2.Reverse();
3324       angle = vec1.AngleWithRef( vec2, vecRef );
3325     }
3326   }
3327   catch (...)
3328   {
3329   }
3330   return angle;
3331 }
3332
3333 //================================================================================
3334 /*!
3335  * \brief Check if the first and last vertices of an edge are the same
3336  * \param anEdge - the edge to check
3337  * \retval bool - true if same
3338  */
3339 //================================================================================
3340
3341 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
3342 {
3343   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
3344     return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
3345   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
3346 }
3347
3348 //================================================================================
3349 /*!
3350  * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
3351  *  in the case of INTERNAL edge
3352  */
3353 //================================================================================
3354
3355 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool  is2nd,
3356                                              TopoDS_Edge anEdge,
3357                                              const bool  CumOri )
3358 {
3359   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
3360     anEdge.Orientation( TopAbs_FORWARD );
3361
3362   const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
3363   TopoDS_Iterator vIt( anEdge, CumOri );
3364   while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
3365     vIt.Next();
3366
3367   return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
3368 }
3369
3370 //================================================================================
3371 /*!
3372  * \brief Return type of shape contained in a group 
3373  *  \param group - a shape of type TopAbs_COMPOUND
3374  *  \param avoidCompound - not to return TopAbs_COMPOUND
3375  */
3376 //================================================================================
3377
3378 TopAbs_ShapeEnum SMESH_MesherHelper::GetGroupType(const TopoDS_Shape& group,
3379                                                   const bool          avoidCompound)
3380 {
3381   if ( !group.IsNull() )
3382   {
3383     if ( group.ShapeType() != TopAbs_COMPOUND )
3384       return group.ShapeType();
3385
3386     // iterate on a compound
3387     TopoDS_Iterator it( group );
3388     if ( it.More() )
3389       return avoidCompound ? GetGroupType( it.Value() ) : it.Value().ShapeType();
3390   }
3391   return TopAbs_SHAPE;
3392 }
3393
3394 //================================================================================
3395 /*!
3396  * \brief Returns a shape, to which a hypothesis used to mesh a given shape is assigned
3397  *  \param [in] hyp - the hypothesis
3398  *  \param [in] shape - the shape, for meshing which the \a hyp is used
3399  *  \param [in] mesh - the mesh
3400  *  \return TopoDS_Shape - the shape the \a hyp is assigned to
3401  */
3402 //================================================================================
3403
3404 TopoDS_Shape SMESH_MesherHelper::GetShapeOfHypothesis( const SMESHDS_Hypothesis * hyp,
3405                                                        const TopoDS_Shape&        shape,
3406                                                        SMESH_Mesh*                mesh)
3407 {
3408   const SMESH_Hypothesis* h = static_cast<const SMESH_Hypothesis*>( hyp );
3409   SMESH_HypoFilter hypFilter( SMESH_HypoFilter::Is( h ));
3410
3411   TopoDS_Shape shapeOfHyp;
3412   mesh->GetHypothesis( shape, hypFilter, /*checkAncestors=*/true, &shapeOfHyp );
3413   return shapeOfHyp;
3414 }
3415
3416 //=======================================================================
3417 //function : IsQuadraticMesh
3418 //purpose  : Check mesh without geometry for: if all elements on this shape are quadratic,
3419 //           quadratic elements will be created.
3420 //           Used then generated 3D mesh without geometry.
3421 //=======================================================================
3422
3423 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
3424 {
3425   int NbAllEdgsAndFaces=0;
3426   int NbQuadFacesAndEdgs=0;
3427   int NbFacesAndEdges=0;
3428   //All faces and edges
3429   NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
3430   if ( NbAllEdgsAndFaces == 0 )
3431     return SMESH_MesherHelper::LINEAR;
3432   
3433   //Quadratic faces and edges
3434   NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
3435
3436   //Linear faces and edges
3437   NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
3438   
3439   if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
3440     //Quadratic mesh
3441     return SMESH_MesherHelper::QUADRATIC;
3442   }
3443   else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
3444     //Linear mesh
3445     return SMESH_MesherHelper::LINEAR;
3446   }
3447   else
3448     //Mesh with both type of elements
3449     return SMESH_MesherHelper::COMP;
3450 }
3451
3452 //=======================================================================
3453 //function : GetOtherParam
3454 //purpose  : Return an alternative parameter for a node on seam
3455 //=======================================================================
3456
3457 double SMESH_MesherHelper::GetOtherParam(const double param) const
3458 {
3459   int i = myParIndex & U_periodic ? 0 : 1;
3460   return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
3461 }
3462
3463 //=======================================================================
3464 //function : IsOnSeam
3465 //purpose  : Check if UV is on seam. Return 0 if not, 1 for U seam, 2 for V seam
3466 //=======================================================================
3467
3468 int SMESH_MesherHelper::IsOnSeam(const gp_XY& uv) const
3469 {
3470   for ( int i = U_periodic; i <= V_periodic ; ++i )
3471     if ( myParIndex & i )
3472     {
3473       double p   = uv.Coord( i );
3474       double tol = ( myPar2[i-1] - myPar1[i-1] ) / 100.;
3475       if ( Abs( p - myPar1[i-1] ) < tol ||
3476            Abs( p - myPar2[i-1] ) < tol )
3477         return i;
3478     }
3479   return 0;
3480 }
3481
3482 namespace {
3483
3484   //=======================================================================
3485   /*!
3486    * \brief Iterator on ancestors of the given type
3487    */
3488   //=======================================================================
3489
3490   struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
3491   {
3492     TopTools_ListIteratorOfListOfShape _ancIter;
3493     TopAbs_ShapeEnum                   _type;
3494     TopTools_MapOfShape                _encountered;
3495     TopTools_IndexedMapOfShape         _allowed;
3496     TAncestorsIterator( const TopTools_ListOfShape& ancestors,
3497                         TopAbs_ShapeEnum            type,
3498                         const TopoDS_Shape*         container/* = 0*/)
3499       : _ancIter( ancestors ), _type( type )
3500     {
3501       if ( container && !container->IsNull() )
3502         TopExp::MapShapes( *container, type, _allowed);
3503       if ( _ancIter.More() ) {
3504         if ( !isCurrentAllowed() ) next();
3505         else _encountered.Add( _ancIter.Value() );
3506       }
3507     }
3508     virtual bool more()
3509     {
3510       return _ancIter.More();
3511     }
3512     virtual const TopoDS_Shape* next()
3513     {
3514       const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
3515       if ( _ancIter.More() )
3516         for ( _ancIter.Next();  _ancIter.More(); _ancIter.Next())
3517           if ( isCurrentAllowed() && _encountered.Add( _ancIter.Value() ))
3518             break;
3519       return s;
3520     }
3521     bool isCurrentAllowed()
3522     {
3523       return (( _ancIter.Value().ShapeType() == _type ) &&
3524               ( _allowed.IsEmpty() || _allowed.Contains( _ancIter.Value() )));
3525     }
3526   };
3527
3528 } // namespace
3529
3530 //=======================================================================
3531 /*!
3532  * \brief Return iterator on ancestors of the given type, included into a container shape
3533  */
3534 //=======================================================================
3535
3536 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
3537                                                    const SMESH_Mesh&   mesh,
3538                                                    TopAbs_ShapeEnum    ancestorType,
3539                                                    const TopoDS_Shape* container)
3540 {
3541   return PShapeIteratorPtr
3542     ( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType, container));
3543 }
3544
3545 //=======================================================================
3546 //function : GetCommonAncestor
3547 //purpose  : Find a common ancestors of two shapes of the given type
3548 //=======================================================================
3549
3550 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
3551                                                    const TopoDS_Shape& shape2,
3552                                                    const SMESH_Mesh&   mesh,
3553                                                    TopAbs_ShapeEnum    ancestorType)
3554 {
3555   TopoDS_Shape commonAnc;
3556   if ( !shape1.IsNull() && !shape2.IsNull() )
3557   {
3558     if ( shape1.ShapeType() == ancestorType && IsSubShape( shape2, shape1 ))
3559       return shape1;
3560     if ( shape2.ShapeType() == ancestorType && IsSubShape( shape1, shape2 ))
3561       return shape2;
3562
3563     PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
3564     while ( const TopoDS_Shape* anc = ancIt->next() )
3565       if ( IsSubShape( shape2, *anc ))
3566       {
3567         commonAnc = *anc;
3568         break;
3569       }
3570   }
3571   return commonAnc;
3572 }
3573
3574 //#include <Perf_Meter.hxx>
3575
3576 //=======================================================================
3577 namespace { // Structures used by FixQuadraticElements()
3578 //=======================================================================
3579
3580 #define __DMP__(txt) \
3581   // cout << txt
3582 #define MSG(txt) __DMP__(txt<<endl)
3583 #define MSGBEG(txt) __DMP__(txt)
3584
3585   //const double straightTol2 = 1e-33; // to detect straing links
3586   bool isStraightLink(double linkLen2, double middleNodeMove2)
3587   {
3588     // straight if <node move> < 1/15 * <link length>
3589     return middleNodeMove2 < 1/15./15. * linkLen2;
3590   }
3591
3592   struct QFace;
3593   // ---------------------------------------
3594   /*!
3595    * \brief Quadratic link knowing its faces
3596    */
3597   struct QLink: public SMESH_TLink
3598   {
3599     const SMDS_MeshNode*          _mediumNode;
3600     mutable vector<const QFace* > _faces;
3601     mutable gp_Vec                _nodeMove;
3602     mutable int                   _nbMoves;
3603     mutable bool                  _is2dFixed; // is moved along surface or in 3D
3604
3605     QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
3606       SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
3607       _faces.reserve(4);
3608       _nodeMove = MediumPnt() - MiddlePnt();
3609       _is2dFixed = ( MediumPos() != SMDS_TOP_FACE );
3610     }
3611     void SetContinuesFaces() const;
3612     const QFace* GetContinuesFace( const QFace* face ) const;
3613     bool   OnBoundary() const;
3614     gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
3615     gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
3616
3617     SMDS_TypeOfPosition  MediumPos() const
3618     { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
3619     SMDS_TypeOfPosition  EndPos(bool isSecond) const
3620     { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
3621     const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
3622     { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
3623
3624     void Move(const gp_Vec& move, bool sum=false, bool is2dFixed=false) const
3625     { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; _is2dFixed |= is2dFixed; }
3626     gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
3627     bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
3628     bool IsFixedOnSurface() const { return _is2dFixed; }
3629     bool IsStraight() const
3630     { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
3631                              _nodeMove.SquareMagnitude());
3632     }
3633     bool operator<(const QLink& other) const {
3634       return (node1()->GetID() == other.node1()->GetID() ?
3635               node2()->GetID() < other.node2()->GetID() :
3636               node1()->GetID() < other.node1()->GetID());
3637     }
3638 //     struct PtrComparator {
3639 //       bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
3640 //     };
3641   };
3642   // ---------------------------------------------------------
3643   /*!
3644    * \brief Link in the chain of links; it connects two faces
3645    */
3646   struct TChainLink
3647   {
3648     const QLink*         _qlink;
3649     mutable const QFace* _qfaces[2];
3650
3651     TChainLink(const QLink* qlink=0):_qlink(qlink) {
3652       _qfaces[0] = _qfaces[1] = 0;
3653     }
3654     void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
3655
3656     bool IsBoundary() const { return !_qfaces[1]; }
3657
3658     void RemoveFace( const QFace* face ) const
3659     { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
3660
3661     const QFace* NextFace( const QFace* f ) const
3662     { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
3663
3664     const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
3665     { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
3666
3667     bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
3668
3669     operator bool() const { return (_qlink); }
3670
3671     const QLink* operator->() const { return _qlink; }
3672
3673     gp_Vec Normal() const;
3674
3675     bool IsStraight() const;
3676   };
3677   // --------------------------------------------------------------------
3678   typedef list< TChainLink > TChain;
3679   typedef set < TChainLink > TLinkSet;
3680   typedef TLinkSet::const_iterator TLinkInSet;
3681
3682   const int theFirstStep = 5;
3683
3684   enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
3685   // --------------------------------------------------------------------
3686   /*!
3687    * \brief Quadratic face shared by two volumes and bound by QLinks
3688    */
3689   struct QFace: public TIDSortedNodeSet
3690   {
3691     mutable const SMDS_MeshElement* _volumes[2];
3692     mutable vector< const QLink* >  _sides;
3693     mutable bool                    _sideIsAdded[4]; // added in chain of links
3694     gp_Vec                          _normal;
3695 #ifdef _DEBUG_
3696     mutable const SMDS_MeshElement* _face;
3697 #endif
3698
3699     QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
3700
3701     void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
3702
3703     int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
3704
3705     void AddSelfToLinks() const {
3706       for ( size_t i = 0; i < _sides.size(); ++i )
3707         _sides[i]->_faces.push_back( this );
3708     }
3709     int LinkIndex( const QLink* side ) const {
3710       for (size_t i = 0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
3711       return -1;
3712     }
3713     bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
3714
3715     bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
3716     {
3717       int i = LinkIndex( link._qlink );
3718       if ( i < 0 ) return true;
3719       _sideIsAdded[i] = true;
3720       link.SetFace( this );
3721       // continue from opposite link
3722       return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
3723     }
3724     bool IsBoundary() const { return !_volumes[1]; }
3725
3726     bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
3727
3728     bool IsSpoiled(const QLink* bentLink ) const;
3729
3730     TLinkInSet GetBoundaryLink( const TLinkSet&      links,
3731                                 const TChainLink&    avoidLink,
3732                                 TLinkInSet *         notBoundaryLink = 0,
3733                                 const SMDS_MeshNode* nodeToContain = 0,
3734                                 bool *               isAdjacentUsed = 0,
3735                                 int                  nbRecursionsLeft = -1) const;
3736
3737     TLinkInSet GetLinkByNode( const TLinkSet&      links,
3738                               const TChainLink&    avoidLink,
3739                               const SMDS_MeshNode* nodeToContain) const;
3740
3741     const SMDS_MeshNode* GetNodeInFace() const {
3742       for ( size_t iL = 0; iL < _sides.size(); ++iL )
3743         if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
3744       return 0;
3745     }
3746
3747     gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
3748
3749     double MoveByBoundary( const TChainLink&   theLink,
3750                            const gp_Vec&       theRefVec,
3751                            const TLinkSet&     theLinks,
3752                            SMESH_MesherHelper* theFaceHelper=0,
3753                            const double        thePrevLen=0,
3754                            const int           theStep=theFirstStep,
3755                            gp_Vec*             theLinkNorm=0,
3756                            double              theSign=1.0) const;
3757   };
3758
3759   //================================================================================
3760   /*!
3761    * \brief Dump QLink and QFace
3762    */
3763   ostream& operator << (ostream& out, const QLink& l)
3764   {
3765     out <<"QLink nodes: "
3766         << l.node1()->GetID() << " - "
3767         << l._mediumNode->GetID() << " - "
3768         << l.node2()->GetID() << endl;
3769     return out;
3770   }
3771   ostream& operator << (ostream& out, const QFace& f)
3772   {
3773     out <<"QFace nodes: "/*<< &f << "  "*/;
3774     for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
3775       out << (*n)->GetID() << " ";
3776     out << " \tvolumes: "
3777         << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
3778         << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
3779     out << "  \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
3780     return out;
3781   }
3782
3783   //================================================================================
3784   /*!
3785    * \brief Construct QFace from QLinks 
3786    */
3787   //================================================================================
3788
3789   QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
3790   {
3791     _volumes[0] = _volumes[1] = 0;
3792     _sides = links;
3793     _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
3794     _normal.SetCoord(0,0,0);
3795     for ( size_t i = 1; i < _sides.size(); ++i ) {
3796       const QLink *l1 = _sides[i-1], *l2 = _sides[i];
3797       insert( l1->node1() ); insert( l1->node2() );
3798       // compute normal
3799       gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
3800       gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
3801       if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
3802         v1.Reverse(); 
3803       _normal += v1 ^ v2;
3804     }
3805     double normSqSize = _normal.SquareMagnitude();
3806     if ( normSqSize > numeric_limits<double>::min() )
3807       _normal /= sqrt( normSqSize );
3808     else
3809       _normal.SetCoord(1e-33,0,0);
3810
3811 #ifdef _DEBUG_
3812     _face = face;
3813 #endif
3814   }
3815   //================================================================================
3816   /*!
3817    * \brief Make up a chain of links
3818    *  \param iSide - link to add first
3819    *  \param chain - chain to fill in
3820    *  \param pos   - position of medium nodes the links should have
3821    *  \param error - out, specifies what is wrong
3822    *  \retval bool - false if valid chain can't be built; "valid" means that links
3823    *                 of the chain belongs to rectangles bounding hexahedrons
3824    */
3825   //================================================================================
3826
3827   bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
3828   {
3829     if ( iSide >= (int)_sides.size() ) // wrong argument iSide
3830       return false;
3831     if ( _sideIsAdded[ iSide ]) // already in chain
3832       return true;
3833
3834     if ( _sides.size() != 4 ) { // triangle - visit all my continuous faces
3835       MSGBEG( *this );
3836       TLinkSet links;
3837       list< const QFace* > faces( 1, this );
3838       while ( !faces.empty() ) {
3839         const QFace* face = faces.front();
3840         for ( size_t i = 0; i < face->_sides.size(); ++i ) {
3841           if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
3842             face->_sideIsAdded[i] = true;
3843             // find a face side in the chain
3844             TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
3845 //             TChain::iterator chLink = chain.begin();
3846 //             for ( ; chLink != chain.end(); ++chLink )
3847 //               if ( chLink->_qlink == face->_sides[i] )
3848 //                 break;
3849 //             if ( chLink == chain.end() )
3850 //               chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
3851             // add a face to a chained link and put a continues face in the queue
3852             chLink->SetFace( face );
3853             if ( face->_sides[i]->MediumPos() == pos )
3854               if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
3855                 if ( contFace->_sides.size() == 3 )
3856                   faces.push_back( contFace );
3857           }
3858         }
3859         faces.pop_front();
3860       }
3861       if ( error < ERR_TRI )
3862         error = ERR_TRI;
3863       chain.insert( chain.end(), links.begin(),links.end() );
3864       return false;
3865     }
3866     _sideIsAdded[iSide] = true; // not to add this link to chain again
3867     const QLink* link = _sides[iSide];
3868     if ( !link)
3869       return true;
3870
3871     // add link into chain
3872     TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
3873     chLink->SetFace( this );
3874     MSGBEG( *this );
3875
3876     // propagate from a quadrangle to neighbour faces
3877     if ( link->MediumPos() >= pos ) {
3878       int nbLinkFaces = link->_faces.size();
3879       if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
3880         // hexahedral mesh or boundary quadrangles - goto a continuous face
3881         if ( const QFace* f = link->GetContinuesFace( this ))
3882           if ( f->_sides.size() == 4 )
3883             return f->GetLinkChain( *chLink, chain, pos, error );
3884       }
3885       else {
3886         TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
3887         for ( int i = 0; i < nbLinkFaces; ++i )
3888           if ( link->_faces[i] )
3889             link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
3890         if ( error < ERR_PRISM )
3891           error = ERR_PRISM;
3892         return false;
3893       }
3894     }
3895     return true;
3896   }
3897
3898   //================================================================================
3899   /*!
3900    * \brief Return a boundary link of the triangle face
3901    *  \param links - set of all links
3902    *  \param avoidLink - link not to return
3903    *  \param notBoundaryLink - out, neither the returned link nor avoidLink
3904    *  \param nodeToContain - node the returned link must contain; if provided, search
3905    *                         also performed on adjacent faces
3906    *  \param isAdjacentUsed - returns true if link is found in adjacent faces
3907    *  \param nbRecursionsLeft - to limit recursion
3908    */
3909   //================================================================================
3910
3911   TLinkInSet QFace::GetBoundaryLink( const TLinkSet&      links,
3912                                      const TChainLink&    avoidLink,
3913                                      TLinkInSet *         notBoundaryLink,
3914                                      const SMDS_MeshNode* nodeToContain,
3915                                      bool *               isAdjacentUsed,
3916                                      int                  nbRecursionsLeft) const
3917   {
3918     TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
3919
3920     typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
3921     TFaceLinkList adjacentFaces;
3922
3923     for ( size_t iL = 0; iL < _sides.size(); ++iL )
3924     {
3925       if ( avoidLink._qlink == _sides[iL] )
3926         continue;
3927       TLinkInSet link = links.find( _sides[iL] );
3928       if ( link == linksEnd ) continue;
3929       if ( (*link)->MediumPos() > SMDS_TOP_FACE )
3930         continue; // We work on faces here, don't go inside a solid
3931
3932       // check link
3933       if ( link->IsBoundary() ) {
3934         if ( !nodeToContain ||
3935              (*link)->node1() == nodeToContain ||
3936              (*link)->node2() == nodeToContain )
3937         {
3938           boundaryLink = link;
3939           if ( !notBoundaryLink ) break;
3940         }
3941       }
3942       else if ( notBoundaryLink ) {
3943         *notBoundaryLink = link;
3944         if ( boundaryLink != linksEnd ) break;
3945       }
3946
3947       if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
3948         if ( const QFace* adj = link->NextFace( this ))
3949           if ( adj->Contains( nodeToContain ))
3950             adjacentFaces.push_back( make_pair( adj, link ));
3951     }
3952
3953     if ( isAdjacentUsed ) *isAdjacentUsed = false;
3954     if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
3955     {
3956       if ( nbRecursionsLeft < 0 )
3957         nbRecursionsLeft = nodeToContain->NbInverseElements();
3958       TFaceLinkList::iterator adj = adjacentFaces.begin();
3959       for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
3960         boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
3961                                                     isAdjacentUsed, nbRecursionsLeft-1);
3962       if ( isAdjacentUsed ) *isAdjacentUsed = true;
3963     }
3964     return boundaryLink;
3965   }
3966   //================================================================================
3967   /*!
3968    * \brief Return a link ending at the given node but not avoidLink
3969    */
3970   //================================================================================
3971
3972   TLinkInSet QFace::GetLinkByNode( const TLinkSet&      links,
3973                                    const TChainLink&    avoidLink,
3974                                    const SMDS_MeshNode* nodeToContain) const
3975   {
3976     for ( size_t i = 0; i < _sides.size(); ++i )
3977       if ( avoidLink._qlink != _sides[i] &&
3978            (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
3979         return links.find( _sides[i] );
3980     return links.end();
3981   }
3982
3983   //================================================================================
3984   /*!
3985    * \brief Return normal to the i-th side pointing outside the face
3986    */
3987   //================================================================================
3988
3989   gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
3990   {
3991     gp_Vec   norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
3992     gp_XYZ    pIn = ( _sides[ (i+1)%3 ]->MiddlePnt() +
3993                       _sides[ (i+2)%3 ]->MiddlePnt() ) / 2.;
3994     gp_Vec vecOut = ( _sides[i]->MiddlePnt() - pIn );
3995
3996     if ( norm * vecOut < 0 )
3997       norm.Reverse();
3998     double mag2 = norm.SquareMagnitude();
3999     if ( mag2 > numeric_limits<double>::min() )
4000       norm /= sqrt( mag2 );
4001     return norm;
4002   }
4003   //================================================================================
4004   /*!
4005    * \brief Move medium node of theLink according to its distance from boundary
4006    *  \param theLink - link to fix
4007    *  \param theRefVec - movement of boundary
4008    *  \param theLinks - all adjacent links of continuous triangles
4009    *  \param theFaceHelper - helper is not used so far
4010    *  \param thePrevLen - distance from the boundary
4011    *  \param theStep - number of steps till movement propagation limit
4012    *  \param theLinkNorm - out normal to theLink
4013    *  \param theSign - 1 or -1 depending on movement of boundary
4014    *  \retval double - distance from boundary to propagation limit or other boundary
4015    */
4016   //================================================================================
4017
4018   double QFace::MoveByBoundary( const TChainLink&   theLink,
4019                                 const gp_Vec&       theRefVec,
4020                                 const TLinkSet&     theLinks,
4021                                 SMESH_MesherHelper* theFaceHelper,
4022                                 const double        thePrevLen,
4023                                 const int           theStep,
4024                                 gp_Vec*             theLinkNorm,
4025                                 double              theSign) const
4026   {
4027     if ( !theStep )
4028       return thePrevLen; // propagation limit reached
4029
4030     size_t iL; // index of theLink
4031     for ( iL = 0; iL < _sides.size(); ++iL )
4032       if ( theLink._qlink == _sides[ iL ])
4033         break;
4034
4035     MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
4036         <<" thePrevLen " << thePrevLen);
4037     MSG(string(theStep,'.')<<" "<<*theLink._qlink);
4038
4039     gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
4040     double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
4041     if ( theStep == theFirstStep )
4042       theSign = refProj < 0. ? -1. : 1.;
4043     else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
4044       return thePrevLen; // to propagate movement forward only, not in side dir or backward
4045
4046     int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
4047     TLinkInSet link1 = theLinks.find( _sides[iL1] );
4048     TLinkInSet link2 = theLinks.find( _sides[iL2] );
4049
4050     const QFace *f1 = 0, *f2 = 0;  // adjacent faces
4051     bool isBndLink1 = true, isBndLink2 = true;
4052     if ( link1 != theLinks.end() && link2 != theLinks.end() )
4053     {
4054       f1 = link1->NextFace( this );
4055       f2 = link2->NextFace( this );
4056
4057       isBndLink1 = ( theLink->MediumPos() > (*link1)->MediumPos() );
4058       isBndLink2 = ( theLink->MediumPos() > (*link2)->MediumPos() );
4059       if ( theStep == theFirstStep ) // (issue 22541) quad-dominant mesh
4060       {
4061         if ( !isBndLink1 && !f1 )
4062           f1 = (*link1)->GetContinuesFace( this ); // get a quadrangle face
4063         if ( !isBndLink2 && !f2 )
4064           f2 = (*link2)->GetContinuesFace( this );
4065       }
4066     }
4067     else if ( _sides.size() < 4 )
4068       return thePrevLen;      
4069
4070     // propagate to adjacent faces till limit step or boundary
4071     double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
4072     double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
4073     gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
4074     gp_Vec linkDir2(0,0,0);
4075     try {
4076       OCC_CATCH_SIGNALS;
4077       if ( f1 && !isBndLink1 )
4078         len1 = f1->MoveByBoundary
4079           ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
4080       else
4081         linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
4082     } catch (...) {
4083       MSG( " --------------- EXCEPTION");
4084       return thePrevLen;
4085     }
4086     try {
4087       OCC_CATCH_SIGNALS;
4088       if ( f2 && !isBndLink2 )
4089         len2 = f2->MoveByBoundary
4090           ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
4091       else
4092         linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
4093     } catch (...) {
4094       MSG( " --------------- EXCEPTION");
4095       return thePrevLen;
4096     }
4097
4098     double fullLen = 0;
4099     if ( theStep != theFirstStep )
4100     {
4101       // choose chain length by direction of propagation most codirected with theRefVec
4102       bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
4103       fullLen = choose1 ? len1 : len2;
4104       double r = thePrevLen / fullLen;
4105
4106       gp_Vec move = linkNorm * refProj * ( 1 - r );
4107       theLink->Move( move, /*sum=*/true );
4108
4109       MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
4110           " by " << refProj * ( 1 - r ) << " following " <<
4111           (choose1 ? *link1->_qlink : *link2->_qlink)); // warning: link1 can be invalid
4112
4113       if ( theLinkNorm ) *theLinkNorm = linkNorm;
4114     }
4115     return fullLen;
4116   }
4117
4118   //================================================================================
4119   /*!
4120    * \brief Checks if the face is distorted due to bentLink
4121    */
4122   //================================================================================
4123
4124   bool QFace::IsSpoiled(const QLink* bentLink ) const
4125   {
4126     // code is valid for convex faces only
4127     gp_XYZ gc(0,0,0);
4128     for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
4129       gc += XYZ( *n ) / size();
4130     for (unsigned i = 0; i < _sides.size(); ++i )
4131     {
4132       if ( _sides[i] == bentLink ) continue;
4133       gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
4134       gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
4135       if ( linkNorm * vecOut < 0 )
4136         linkNorm.Reverse();
4137       double mag2 = linkNorm.SquareMagnitude();
4138       if ( mag2 > numeric_limits<double>::min() )
4139         linkNorm /= sqrt( mag2 );
4140       gp_Vec vecBent    ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
4141       gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
4142       if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
4143         return true;
4144     }
4145     return false;
4146     
4147   }
4148
4149   //================================================================================
4150   /*!
4151    * \brief Find pairs of continues faces 
4152    */
4153   //================================================================================
4154
4155   void QLink::SetContinuesFaces() const
4156   {
4157     //       x0         x - QLink, [-|] - QFace, v - volume
4158     //   v0  |   v1   
4159     //       |          Between _faces of link x2 two vertical faces are continues
4160     // x1----x2-----x3  and two horizontal faces are continues. We set vertical faces
4161     //       |          to _faces[0] and _faces[1] and horizontal faces to
4162     //   v2  |   v3     _faces[2] and _faces[3] (or vise versa).
4163     //       x4
4164
4165     if ( _faces.empty() )
4166       return;
4167     int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
4168     if ( _faces[0]->IsBoundary() )
4169       iBoundary[ nbBoundary++ ] = 0;
4170     for ( size_t iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
4171     {
4172       // look for a face bounding none of volumes bound by _faces[0]
4173       bool sameVol = false;
4174       int nbVol = _faces[iF]->NbVolumes();
4175       for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
4176         sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
4177                     _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
4178       if ( !sameVol )
4179         iFaceCont = iF;
4180       if ( _faces[iF]->IsBoundary() )
4181         iBoundary[ nbBoundary++ ] = iF;
4182     }
4183     // Set continues faces: arrange _faces to have
4184     // _faces[0] continues to _faces[1]
4185     // _faces[2] continues to _faces[3]
4186     if ( nbBoundary == 2 ) // bnd faces are continues
4187     {
4188       if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
4189       {
4190         int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
4191         std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
4192       }
4193     }
4194     else if ( iFaceCont > 0 ) // continues faces found
4195     {
4196       if ( iFaceCont != 1 )
4197         std::swap( _faces[1], _faces[iFaceCont] );
4198     }
4199     else if ( _faces.size() > 1 ) // not found, set NULL by the first face
4200     {
4201       _faces.insert( ++_faces.begin(), (QFace*) 0 );
4202     }
4203   }
4204   //================================================================================
4205   /*!
4206    * \brief Return a face continues to the given one
4207    */
4208   //================================================================================
4209
4210   const QFace* QLink::GetContinuesFace( const QFace* face ) const
4211   {
4212     if ( _faces.size() <= 4 )
4213       for ( size_t i = 0; i < _faces.size(); ++i ) {
4214         if ( _faces[i] == face ) {
4215           int iF = i < 2 ? 1-i : 5-i;
4216           return iF < (int)_faces.size() ? _faces[iF] : 0;
4217         }
4218       }
4219     return 0;
4220   }
4221   //================================================================================
4222   /*!
4223    * \brief True if link is on mesh boundary
4224    */
4225   //================================================================================
4226
4227   bool QLink::OnBoundary() const
4228   {
4229     for ( size_t i = 0; i < _faces.size(); ++i )
4230       if (_faces[i] && _faces[i]->IsBoundary()) return true;
4231     return false;
4232   }
4233   //================================================================================
4234   /*!
4235    * \brief Return normal of link of the chain
4236    */
4237   //================================================================================
4238
4239   gp_Vec TChainLink::Normal() const {
4240     gp_Vec norm;
4241     if (_qfaces[0]) norm  = _qfaces[0]->_normal;
4242     if (_qfaces[1]) norm += _qfaces[1]->_normal;
4243     return norm;
4244   }
4245   //================================================================================
4246   /*!
4247    * \brief Test link curvature taking into account size of faces
4248    */
4249   //================================================================================
4250
4251   bool TChainLink::IsStraight() const
4252   {
4253     bool isStraight = _qlink->IsStraight();
4254     if ( isStraight && _qfaces[0] && !_qfaces[1] )
4255     {
4256       int i = _qfaces[0]->LinkIndex( _qlink );
4257       int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
4258       gp_XYZ mid1 = _qlink->MiddlePnt();
4259       gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
4260       double faceSize2 = (mid1-mid2).SquareModulus();
4261       isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
4262     }
4263     return isStraight;
4264   }
4265   
4266   //================================================================================
4267   /*!
4268    * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
4269    */
4270   //================================================================================
4271
4272   void fixPrism( TChain& allLinks )
4273   {
4274     // separate boundary links from internal ones
4275     typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
4276     QLinkSet interLinks, bndLinks1, bndLink2;
4277
4278     bool isCurved = false;
4279     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
4280       if ( (*lnk)->OnBoundary() )
4281         bndLinks1.insert( lnk->_qlink );
4282       else
4283         interLinks.insert( lnk->_qlink );
4284       isCurved = isCurved || !lnk->IsStraight();
4285     }
4286     if ( !isCurved )
4287       return; // no need to move
4288
4289     QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
4290
4291     while ( !interLinks.empty() && !curBndLinks->empty() )
4292     {
4293       // propagate movement from boundary links to connected internal links
4294       QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
4295       for ( ; bnd != bndEnd; ++bnd )
4296       {
4297         const QLink* bndLink = *bnd;
4298         for ( size_t i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
4299         {
4300           const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
4301           if ( !face ) continue;
4302           // find and move internal link opposite to bndLink within the face
4303           int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
4304           const QLink* interLink = face->_sides[ interInd ];
4305           QLinkSet::iterator pInterLink = interLinks.find( interLink );
4306           if ( pInterLink == interLinks.end() ) continue; // not internal link
4307           interLink->Move( bndLink->_nodeMove );
4308           // treated internal links become new boundary ones
4309           interLinks.erase( pInterLink );
4310           newBndLinks->insert( interLink );
4311         }
4312       }
4313       curBndLinks->clear();
4314       std::swap( curBndLinks, newBndLinks );
4315     }
4316   }
4317
4318   //================================================================================
4319   /*!
4320    * \brief Fix links of continues triangles near curved boundary
4321    */
4322   //================================================================================
4323
4324   void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
4325   {
4326     if ( allLinks.empty() ) return;
4327
4328     TLinkSet linkSet( allLinks.begin(), allLinks.end());
4329     TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
4330
4331     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
4332     {
4333       if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
4334       {
4335         // move iff a boundary link is bent towards inside of a face (issue 0021084)
4336         const QFace* face = linkIt->_qfaces[0];
4337         gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
4338                        face->_sides[1]->MiddlePnt() +
4339                        face->_sides[2]->MiddlePnt() ) / 3.;
4340         gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
4341         bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
4342         //if ( face->IsSpoiled( linkIt->_qlink ))
4343         if ( linkBentInside )
4344           face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
4345       }
4346     }
4347   }
4348
4349   //================================================================================
4350   /*!
4351    * \brief Detect rectangular structure of links and build chains from them
4352    */
4353   //================================================================================
4354
4355   enum TSplitTriaResult {
4356     _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
4357     _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
4358
4359   TSplitTriaResult splitTrianglesIntoChains( TChain &            allLinks,
4360                                              vector< TChain> &   resultChains,
4361                                              SMDS_TypeOfPosition pos )
4362   {
4363     // put links in the set and evalute number of result chains by number of boundary links
4364     TLinkSet linkSet;
4365     size_t nbBndLinks = 0;
4366     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
4367       linkSet.insert( *lnk );
4368       nbBndLinks += lnk->IsBoundary();
4369     }
4370     resultChains.clear();
4371     resultChains.reserve( nbBndLinks / 2 );
4372
4373     TLinkInSet linkIt, linksEnd = linkSet.end();
4374
4375     // find a boundary link with corner node; corner node has position pos-2
4376     // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
4377     // links in volume
4378     SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
4379     const SMDS_MeshNode* corner = 0;
4380     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
4381       if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
4382         break;
4383     if ( !corner)
4384       return _NO_CORNERS;
4385
4386     TLinkInSet           startLink = linkIt;
4387     const SMDS_MeshNode* startCorner = corner;
4388     vector< TChain* >    rowChains;
4389     int iCol = 0;
4390
4391     while ( startLink != linksEnd) // loop on columns
4392     {
4393       // We suppose we have a rectangular structure like shown here. We have found a
4394       //               corner of the rectangle (startCorner) and a boundary link sharing  
4395       //    |/  |/  |  the startCorner (startLink). We are going to loop on rows of the   
4396       //  --o---o---o  structure making several chains at once. One chain (columnChain)   
4397       //    |\  |  /|  starts at startLink and continues upward (we look at the structure 
4398       //  \ | \ | / |  from such point that startLink is on the bottom of the structure). 
4399       //   \|  \|/  |  While going upward we also fill horizontal chains (rowChains) we   
4400       //  --o---o---o  encounter.                                                         
4401       //   /|\  |\  |
4402       //  / | \ | \ |  startCorner
4403       //    |  \|  \|,'
4404       //  --o---o---o
4405       //          `.startLink
4406
4407       if ( resultChains.size() == nbBndLinks / 2 )
4408         return _NOT_RECT;
4409       resultChains.push_back( TChain() );
4410       TChain& columnChain = resultChains.back();
4411
4412       TLinkInSet botLink = startLink; // current horizontal link to go up from
4413       corner = startCorner; // current corner the botLink ends at
4414       size_t iRow = 0;
4415       while ( botLink != linksEnd ) // loop on rows
4416       {
4417         // add botLink to the columnChain
4418         columnChain.push_back( *botLink );
4419
4420         const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
4421         if ( !botTria )
4422         { // the column ends
4423           if ( botLink == startLink )
4424             return _TWISTED_CHAIN; // issue 0020951
4425           linkSet.erase( botLink );
4426           if ( iRow != rowChains.size() )
4427             return _FEW_ROWS; // different nb of rows in columns
4428           break;
4429         }
4430         // find the link dividing the quadrangle (midQuadLink) and vertical boundary
4431         // link ending at <corner> (sideLink); there are two cases:
4432         // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
4433         //   since midQuadLink is not at boundary while sideLink is.
4434         // 2) midQuadLink ends at <corner>
4435         bool isCase2;
4436         TLinkInSet midQuadLink = linksEnd;
4437         TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
4438                                                         corner, &isCase2 );
4439         if ( isCase2 ) { // find midQuadLink among links of botTria
4440           midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
4441           if ( midQuadLink->IsBoundary() )
4442             return _BAD_MIDQUAD;
4443         }
4444         if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
4445           return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
4446
4447         // fill chains
4448         columnChain.push_back( *midQuadLink );
4449         if ( iRow >= rowChains.size() ) {
4450           if ( iCol > 0 )
4451             return _MANY_ROWS; // different nb of rows in columns
4452           if ( resultChains.size() == nbBndLinks / 2 )
4453             return _NOT_RECT;
4454           resultChains.push_back( TChain() );
4455           rowChains.push_back( & resultChains.back() );
4456         }
4457         rowChains[iRow]->push_back( *sideLink );
4458         rowChains[iRow]->push_back( *midQuadLink );
4459
4460         const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
4461         if ( !upTria)
4462           return _NO_UPTRIA;
4463         if ( iRow == 0 ) {
4464           // prepare startCorner and startLink for the next column
4465           startCorner = startLink->NextNode( startCorner );
4466           if (isCase2)
4467             startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
4468           else
4469             startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
4470           // check if no more columns remains
4471           if ( startLink != linksEnd ) {
4472             const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
4473             if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
4474               startLink = linksEnd; // startLink bounds upTria or botTria
4475             else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
4476               return _BAD_START;
4477           }
4478         }
4479         // find bottom link and corner for the next row
4480         corner = sideLink->NextNode( corner );
4481         // next bottom link ends at the new corner
4482         linkSet.erase( botLink );
4483         botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
4484         if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
4485           return _NO_BOTLINK;
4486         if ( midQuadLink == startLink || sideLink == startLink )
4487           return _TWISTED_CHAIN; // issue 0020951
4488         linkSet.erase( midQuadLink );
4489         linkSet.erase( sideLink );
4490
4491         // make faces neighboring the found ones be boundary
4492         if ( startLink != linksEnd ) {
4493           const QFace* tria = isCase2 ? botTria : upTria;
4494           for ( int iL = 0; iL < 3; ++iL ) {
4495             linkIt = linkSet.find( tria->_sides[iL] );
4496             if ( linkIt != linksEnd )
4497               linkIt->RemoveFace( tria );
4498           }
4499         }
4500         if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
4501           botLink->RemoveFace( upTria ); // make next botTria first in vector
4502
4503         iRow++;
4504       } // loop on rows
4505
4506       iCol++;
4507     }
4508     // In the linkSet, there must remain the last links of rowChains; add them
4509     if ( linkSet.size() != rowChains.size() )
4510       return _BAD_SET_SIZE;
4511     for ( size_t iRow = 0; iRow < rowChains.size(); ++iRow ) {
4512       // find the link (startLink) ending at startCorner
4513       corner = 0;
4514       for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
4515         if ( (*startLink)->node1() == startCorner ) {
4516           corner = (*startLink)->node2(); break;
4517         }
4518         else if ( (*startLink)->node2() == startCorner) {
4519           corner = (*startLink)->node1(); break;
4520         }
4521       }
4522       if ( startLink == linksEnd )
4523         return _BAD_CORNER;
4524       rowChains[ iRow ]->push_back( *startLink );
4525       linkSet.erase( startLink );
4526       startCorner = corner;
4527     }
4528
4529     return _OK;
4530   }
4531
4532   //================================================================================
4533   /*!
4534    * \brief Place medium nodes at the link middle for elements whose corner nodes
4535    *        are out of geometrical boundary to prevent distorting elements.
4536    *        Issue 0020982, note 0013990
4537    */
4538   //================================================================================
4539
4540   void force3DOutOfBoundary( SMESH_MesherHelper&    theHelper,
4541                              SMESH_ComputeErrorPtr& theError)
4542   {
4543     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
4544     TopoDS_Shape  shape = theHelper.GetSubShape().Oriented( TopAbs_FORWARD );
4545     if ( shape.IsNull() ) return;
4546
4547     if ( !theError ) theError = SMESH_ComputeError::New();
4548
4549     gp_XYZ faceNorm;
4550
4551     if ( shape.ShapeType() == TopAbs_FACE ) // 2D
4552     {
4553       if ( theHelper.GetMesh()->NbTriangles( ORDER_QUADRATIC ) < 1 ) return;
4554
4555       SMESHDS_SubMesh* faceSM = meshDS->MeshElements( shape );
4556       if ( !faceSM ) return;
4557
4558       const TopoDS_Face&      face = TopoDS::Face( shape );
4559       Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
4560
4561       TopExp_Explorer edgeIt( face, TopAbs_EDGE );
4562       for ( ; edgeIt.More(); edgeIt.Next() ) // loop on EDGEs of a FACE
4563       {
4564         // check if the EDGE needs checking
4565         const TopoDS_Edge& edge = TopoDS::Edge( edgeIt.Current() );
4566         if ( SMESH_Algo::isDegenerated( edge ) )
4567           continue;
4568         if ( theHelper.IsRealSeam( edge ) &&
4569              edge.Orientation() == TopAbs_REVERSED )
4570           continue;
4571
4572         SMESHDS_SubMesh* edgeSM = meshDS->MeshElements( edge );
4573         if ( !edgeSM ) continue;
4574
4575         double f,l;
4576         Handle(Geom2d_Curve) pcurve  = BRep_Tool::CurveOnSurface( edge, face, f, l );
4577         BRepAdaptor_Curve    curve3D( edge );
4578         switch ( curve3D.GetType() ) {
4579         case GeomAbs_Line: continue;
4580         case GeomAbs_Circle:
4581         case GeomAbs_Ellipse:
4582         case GeomAbs_Hyperbola:
4583         case GeomAbs_Parabola:
4584           try
4585           {
4586             gp_Vec D1, D2, Du1, Dv1; gp_Pnt p;
4587             curve3D.D2( 0.5 * ( f + l ), p, D1, D2 );
4588             gp_Pnt2d uv = pcurve->Value( 0.5 * ( f + l ) );
4589             surface->D1( uv.X(), uv.Y(), p, Du1, Dv1 );
4590             gp_Vec fNorm = Du1 ^ Dv1;
4591             if ( fNorm.IsParallel( D2, M_PI * 25./180. ))
4592               continue; // face is normal to the curve3D
4593
4594             gp_Vec curvNorm = fNorm ^ D1;
4595             if ( edge.Orientation() == TopAbs_REVERSED ) curvNorm.Reverse();
4596             if ( curvNorm * D2 > 0 )
4597               continue; // convex edge
4598           }
4599           catch ( Standard_Failure )
4600           {
4601             continue;
4602           }
4603         default:;
4604         }
4605         // get nodes shared by faces that may be distorted
4606         SMDS_NodeIteratorPtr nodeIt;
4607         if ( edgeSM->NbNodes() > 0 ) {
4608           nodeIt = edgeSM->GetNodes();
4609         }
4610         else {
4611           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( theHelper.IthVertex( 0, edge ));
4612           if ( !vertexSM )
4613             vertexSM = meshDS->MeshElements( theHelper.IthVertex( 1, edge ));
4614           if ( !vertexSM ) continue;
4615           nodeIt = vertexSM->GetNodes();
4616         }
4617
4618         // find suspicious faces
4619         TIDSortedElemSet checkedFaces;
4620         vector< const SMDS_MeshNode* > nOnEdge( 2 );
4621         const SMDS_MeshNode*           nOnFace;
4622         while ( nodeIt->more() )
4623         {
4624           const SMDS_MeshNode* n      = nodeIt->next();
4625           SMDS_ElemIteratorPtr faceIt = n->GetInverseElementIterator( SMDSAbs_Face );
4626           while ( faceIt->more() )
4627           {
4628             const SMDS_MeshElement* f = faceIt->next();
4629             if ( !faceSM->Contains( f ) ||
4630                  f->NbNodes() < 6       || // check quadratic triangles only
4631                  !checkedFaces.insert( f ).second )
4632               continue;
4633
4634             // get nodes on EDGE and on FACE of a suspicious face
4635             nOnEdge.clear(); nOnFace = 0;
4636             SMDS_MeshElement::iterator triNode = f->begin_nodes();
4637             for ( int nbN = 0; nbN < 3; ++triNode, ++nbN )
4638             {
4639               n = *triNode;
4640               if ( n->GetPosition()->GetDim() == 2 )
4641                 nOnFace = n;
4642               else
4643                 nOnEdge.push_back( n );
4644             }
4645
4646             // check if nOnFace is inside the FACE
4647             if ( nOnFace && nOnEdge.size() == 2 )
4648             {
4649               theHelper.AddTLinks( static_cast< const SMDS_MeshFace* > ( f ));
4650               if ( !SMESH_MeshAlgos::FaceNormal( f, faceNorm, /*normalized=*/false ))
4651                 continue;
4652               gp_XYZ edgeDir  = SMESH_TNodeXYZ( nOnEdge[0] ) - SMESH_TNodeXYZ( nOnEdge[1] );
4653               gp_XYZ edgeNorm = faceNorm ^ edgeDir;
4654               n = theHelper.GetMediumNode( nOnEdge[0], nOnEdge[1], true ); // find n, not create 
4655               gp_XYZ pN0     = SMESH_TNodeXYZ( nOnEdge[0] );
4656               gp_XYZ pMedium = SMESH_TNodeXYZ( n );                   // on-edge node location
4657               gp_XYZ pFaceN  = SMESH_TNodeXYZ( nOnFace );             // on-face node location
4658               double hMedium = edgeNorm * gp_Vec( pN0, pMedium ).XYZ();
4659               double hFace   = edgeNorm * gp_Vec( pN0, pFaceN ).XYZ();
4660               if ( Abs( hMedium ) > Abs( hFace * 0.6 ))
4661               {
4662                 // nOnFace is out of FACE, move a medium on-edge node to the middle
4663                 gp_XYZ pMid3D = 0.5 * ( pN0 + SMESH_TNodeXYZ( nOnEdge[1] ));
4664                 meshDS->MoveNode( n, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
4665                 MSG( "move OUT of face " << n );
4666                 theError->myBadElements.push_back( f );
4667               }
4668             }
4669           }
4670         }
4671       }
4672       if ( !theError->myBadElements.empty() )
4673         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
4674       return;
4675
4676     } // 2D ==============================================================================
4677
4678     if ( shape.ShapeType() == TopAbs_SOLID ) // 3D
4679     {
4680       if ( theHelper.GetMesh()->NbTetras  ( ORDER_QUADRATIC ) < 1 &&
4681            theHelper.GetMesh()->NbPyramids( ORDER_QUADRATIC ) < 1 ) return;
4682
4683       SMESHDS_SubMesh* solidSM = meshDS->MeshElements( shape );
4684       if ( !solidSM ) return;
4685
4686       // check if the SOLID is bound by concave FACEs
4687       vector< TopoDS_Face > concaveFaces;
4688       TopExp_Explorer faceIt( shape, TopAbs_FACE );
4689       for ( ; faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4690       {
4691         const TopoDS_Face&  face = TopoDS::Face( faceIt.Current() );
4692         if ( !meshDS->MeshElements( face )) continue;
4693
4694         BRepAdaptor_Surface surface( face );
4695         switch ( surface.GetType() ) {
4696         case GeomAbs_Plane: continue;
4697         case GeomAbs_Cylinder:
4698         case GeomAbs_Cone:
4699         case GeomAbs_Sphere:
4700           try
4701           {
4702             double u = 0.5 * ( surface.FirstUParameter() + surface.LastUParameter() );
4703             double v = 0.5 * ( surface.FirstVParameter() + surface.LastVParameter() );
4704             gp_Vec Du1, Dv1, Du2, Dv2, Duv2; gp_Pnt p;
4705             surface.D2( u,v, p, Du1, Dv1, Du2, Dv2, Duv2 );
4706             gp_Vec fNorm = Du1 ^ Dv1;
4707             if ( face.Orientation() == TopAbs_REVERSED ) fNorm.Reverse();
4708             bool concaveU = ( fNorm * Du2 > 1e-100 );
4709             bool concaveV = ( fNorm * Dv2 > 1e-100 );
4710             if ( concaveU || concaveV )
4711               concaveFaces.push_back( face );
4712           }
4713           catch ( Standard_Failure )
4714           {
4715             concaveFaces.push_back( face );
4716           }
4717         default:;
4718         }
4719       }
4720       if ( concaveFaces.empty() )
4721         return;
4722
4723       // fix 2D mesh on the SOLID
4724       for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4725       {
4726         SMESH_MesherHelper faceHelper( *theHelper.GetMesh() );
4727         faceHelper.SetSubShape( faceIt.Current() );
4728         force3DOutOfBoundary( faceHelper, theError );
4729       }
4730
4731       // get an iterator over faces on concaveFaces
4732       vector< SMDS_ElemIteratorPtr > faceIterVec( concaveFaces.size() );
4733       for ( size_t i = 0; i < concaveFaces.size(); ++i )
4734         faceIterVec[i] = meshDS->MeshElements( concaveFaces[i] )->GetElements();
4735       typedef SMDS_IteratorOnIterators
4736         < const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIterOnIter;
4737       SMDS_ElemIteratorPtr faceIter( new TIterOnIter( faceIterVec ));
4738
4739       // search to check if a volume is close to a concave face
4740       SMESHUtils::Deleter< SMESH_ElementSearcher > faceSearcher
4741         ( SMESH_MeshAlgos::GetElementSearcher( *theHelper.GetMeshDS(), faceIter ));
4742
4743       // classifier
4744       //BRepClass3d_SolidClassifier solidClassifier( shape );
4745
4746       TIDSortedElemSet checkedVols, movedNodes;
4747       //for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4748       for ( size_t iF = 0; iF < concaveFaces.size(); ++iF ) // loop on concave FACEs
4749       {
4750         //const TopoDS_Shape& face = faceIt.Current();
4751         const TopoDS_Shape& face = concaveFaces[ iF ];
4752         SMESHDS_SubMesh*  faceSM = meshDS->MeshElements( face );
4753         if ( !faceSM ) continue;
4754
4755         // get nodes shared by volumes (tet and pyra) on the FACE that may be distorted
4756         SMDS_NodeIteratorPtr nodeIt;
4757         if ( faceSM->NbNodes() > 0 ) {
4758           nodeIt = faceSM->GetNodes();
4759         }
4760         else {
4761           TopExp_Explorer vertex( face, TopAbs_VERTEX );
4762           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( vertex.Current() );
4763           if ( !vertexSM ) continue;
4764           nodeIt = vertexSM->GetNodes();
4765         }
4766         // get ids of sub-shapes of the FACE
4767         set< int > subIDs;
4768         SMESH_subMeshIteratorPtr smIt =
4769           theHelper.GetMesh()->GetSubMesh( face )->getDependsOnIterator(/*includeSelf=*/true);
4770         while ( smIt->more() )
4771           subIDs.insert( smIt->next()->GetId() );
4772
4773         // find suspicious volumes adjacent to the FACE
4774         vector< const SMDS_MeshNode* >    nOnFace( 4 );
4775         const SMDS_MeshNode*              nInSolid;
4776         while ( nodeIt->more() )
4777         {
4778           const SMDS_MeshNode* n     = nodeIt->next();
4779           SMDS_ElemIteratorPtr volIt = n->GetInverseElementIterator( SMDSAbs_Volume );
4780           while ( volIt->more() )
4781           {
4782             const SMDS_MeshElement* vol = volIt->next();
4783             size_t                  nbN = vol->NbCornerNodes();
4784             if ( ( nbN != 4 && nbN != 5 )  ||
4785                  !solidSM->Contains( vol ) ||
4786                  !checkedVols.insert( vol ).second )
4787               continue;
4788
4789             // get nodes on FACE and in SOLID of a suspicious volume
4790             nOnFace.clear(); nInSolid = 0;
4791             SMDS_MeshElement::iterator volNode = vol->begin_nodes();
4792             for ( int nb = nbN; nb > 0; ++volNode, --nb )
4793             {
4794               n = *volNode;
4795               if ( n->GetPosition()->GetDim() == 3 )
4796                 nInSolid = n;
4797               else if ( subIDs.count( n->getshapeId() ))
4798                 nOnFace.push_back( n );
4799               else
4800                 nInSolid = n;
4801             }
4802             if ( !nInSolid || nOnFace.size() != nbN - 1 )
4803               continue;
4804
4805             // get size of the vol
4806             SMESH_TNodeXYZ pInSolid( nInSolid ), pOnFace0( nOnFace[0] );
4807             double volLength = pInSolid.SquareDistance( nOnFace[0] );
4808             for ( size_t i = 1; i < nOnFace.size(); ++i )
4809             {
4810               volLength = Max( volLength, pOnFace0.SquareDistance( nOnFace[i] ));
4811             }
4812
4813             // check if vol is close to concaveFaces
4814             const SMDS_MeshElement* closeFace =
4815               faceSearcher->FindClosestTo( pInSolid, SMDSAbs_Face );
4816             if ( !closeFace ||
4817                  pInSolid.SquareDistance( closeFace->GetNode(0) ) > 4 * volLength )
4818               continue;
4819
4820             // check if vol is distorted, i.e. a medium node is much closer
4821             // to nInSolid than the link middle
4822             bool isDistorted = false;
4823             SMDS_FaceOfNodes onFaceTria( nOnFace[0], nOnFace[1], nOnFace[2] );
4824             if ( !SMESH_MeshAlgos::FaceNormal( &onFaceTria, faceNorm, /*normalized=*/false ))
4825               continue;
4826             theHelper.AddTLinks( static_cast< const SMDS_MeshVolume* > ( vol ));
4827             vector< pair< SMESH_TLink, const SMDS_MeshNode* > > links;
4828             for ( size_t i = 0; i < nOnFace.size(); ++i ) // loop on links between nOnFace
4829               for ( size_t j = i+1; j < nOnFace.size(); ++j )
4830               {
4831                 SMESH_TLink link( nOnFace[i], nOnFace[j] );
4832                 TLinkNodeMap::const_iterator linkIt =
4833                   theHelper.GetTLinkNodeMap().find( link );
4834                 if ( linkIt != theHelper.GetTLinkNodeMap().end() )
4835                 {
4836                   links.push_back( make_pair( linkIt->first, linkIt->second  ));
4837                   if ( !isDistorted ) {
4838                     // compare projections of nInSolid and nMedium to face normal
4839                     gp_Pnt pMedium = SMESH_TNodeXYZ( linkIt->second );
4840                     double hMedium = faceNorm * gp_Vec( pOnFace0, pMedium ).XYZ();
4841                     double hVol    = faceNorm * gp_Vec( pOnFace0, pInSolid ).XYZ();
4842                     isDistorted = ( Abs( hMedium ) > Abs( hVol * 0.75 ));
4843                   }
4844                 }
4845               }
4846             // move medium nodes to link middle
4847             if ( isDistorted )
4848             {
4849               for ( size_t i = 0; i < links.size(); ++i )
4850               {
4851                 const SMDS_MeshNode* nMedium = links[i].second;
4852                 if ( movedNodes.insert( nMedium ).second )
4853                 {
4854                   gp_Pnt pMid3D = 0.5 * ( SMESH_TNodeXYZ( links[i].first.node1() ) +
4855                                           SMESH_TNodeXYZ( links[i].first.node2() ));
4856                   meshDS->MoveNode( nMedium, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
4857                   MSG( "move OUT of solid " << nMedium );
4858                 }
4859               }
4860               theError->myBadElements.push_back( vol );
4861             }
4862           } // loop on volumes sharing a node on FACE
4863         } // loop on nodes on FACE
4864       }  // loop on FACEs of a SOLID
4865
4866       if ( !theError->myBadElements.empty() )
4867         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
4868     } // 3D case
4869   }
4870
4871 } //namespace
4872
4873 //=======================================================================
4874 /*!
4875  * \brief Move medium nodes of faces and volumes to fix distorted elements
4876  * \param error - container of fixed distorted elements
4877  * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
4878  * 
4879  * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
4880  */
4881 //=======================================================================
4882
4883 void SMESH_MesherHelper::FixQuadraticElements(SMESH_ComputeErrorPtr& compError,
4884                                               bool                   volumeOnly)
4885 {
4886   //MESSAGE("FixQuadraticElements " << volumeOnly);
4887   // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
4888   if ( getenv("NO_FixQuadraticElements") )
4889     return;
4890
4891   // 0. Apply algorithm to SOLIDs or FACEs
4892   // ----------------------------------------------
4893   if ( myShape.IsNull() ) {
4894     if ( !myMesh->HasShapeToMesh() ) return;
4895     SetSubShape( myMesh->GetShapeToMesh() );
4896
4897 #ifdef _DEBUG_
4898     int nbSolids = 0;
4899     TopTools_IndexedMapOfShape solids;
4900     TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
4901     nbSolids = solids.Extent();
4902 #endif
4903     TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
4904     for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
4905       faces.Add( f.Current() ); // not in solid
4906     }
4907     for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
4908       if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
4909         for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
4910           faces.Add( f.Current() ); // in not meshed solid
4911       }
4912       else { // fix nodes in the solid and its faces
4913 #ifdef _DEBUG_
4914         MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
4915 #endif
4916         SMESH_MesherHelper h(*myMesh);
4917         h.SetSubShape( s.Current() );
4918         h.ToFixNodeParameters(true);
4919         h.FixQuadraticElements( compError, false );
4920       }
4921     }
4922     // fix nodes on geom faces
4923 #ifdef _DEBUG_
4924     int nbfaces = nbSolids;
4925     nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--; 
4926 #endif
4927     for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
4928       MESSAGE("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
4929       MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
4930       SMESH_MesherHelper h(*myMesh);
4931       h.SetSubShape( fIt.Key() );
4932       h.ToFixNodeParameters(true);
4933       h.FixQuadraticElements( compError, true);
4934     }
4935     //perf_print_all_meters(1);
4936     if ( compError && compError->myName == EDITERR_NO_MEDIUM_ON_GEOM )
4937       compError->myComment = "during conversion to quadratic, "
4938         "some medium nodes were not placed on geometry to avoid distorting elements";
4939     return;
4940   }
4941
4942   // 1. Find out type of elements and get iterator on them
4943   // ---------------------------------------------------
4944
4945   SMDS_ElemIteratorPtr elemIt;
4946   SMDSAbs_ElementType elemType = SMDSAbs_All;
4947
4948   SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
4949   if ( !submesh )
4950     return;
4951   if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
4952     elemIt = smDS->GetElements();
4953     if ( elemIt->more() ) {
4954       elemType = elemIt->next()->GetType();
4955       elemIt = smDS->GetElements();
4956     }
4957   }
4958   if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
4959     return;
4960
4961   // 2. Fill in auxiliary data structures
4962   // ----------------------------------
4963
4964   set< QLink > links;
4965   set< QFace > faces;
4966   set< QLink >::iterator pLink;
4967   set< QFace >::iterator pFace;
4968
4969   bool isCurved = false;
4970   //bool hasRectFaces = false;
4971   //set<int> nbElemNodeSet;
4972   SMDS_VolumeTool volTool;
4973
4974   TIDSortedNodeSet apexOfPyramid;
4975   const int apexIndex = 4;
4976
4977   // Issue 0020982
4978   // Move medium nodes to the link middle for elements whose corner nodes
4979   // are out of geometrical boundary to fix distorted elements.
4980   force3DOutOfBoundary( *this, compError );
4981
4982   if ( elemType == SMDSAbs_Volume )
4983   {
4984     while ( elemIt->more() ) // loop on volumes
4985     {
4986       const SMDS_MeshElement* vol = elemIt->next();
4987       if ( !vol->IsQuadratic() || !volTool.Set( vol ))
4988         return;
4989       double volMinSize2 = -1.;
4990       for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
4991       {
4992         int nbN = volTool.NbFaceNodes( iF );
4993         //nbElemNodeSet.insert( nbN );
4994         const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
4995         vector< const QLink* > faceLinks( nbN/2 );
4996         for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
4997         {
4998           // store QLink
4999           QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
5000           pLink = links.insert( link ).first;
5001           faceLinks[ iN/2 ] = & *pLink;
5002
5003           if ( link.MediumPos() == SMDS_TOP_3DSPACE )
5004           {
5005             if ( !link.IsStraight() )
5006               return; // already fixed
5007           }
5008           else if ( !isCurved )
5009           {
5010             if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
5011             isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
5012           }
5013         }
5014         // store QFace
5015         pFace = faces.insert( QFace( faceLinks )).first;
5016         if ( pFace->NbVolumes() == 0 )
5017           pFace->AddSelfToLinks();
5018         pFace->SetVolume( vol );
5019 //         hasRectFaces = hasRectFaces ||
5020 //           ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
5021 //             volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
5022 #ifdef _DEBUG_
5023         if ( nbN == 6 )
5024           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
5025         else
5026           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
5027                                                faceNodes[4],faceNodes[6] );
5028 #endif
5029       }
5030       // collect pyramid apexes for further correction
5031       if ( vol->NbCornerNodes() == 5 )
5032         apexOfPyramid.insert( vol->GetNode( apexIndex ));
5033     }
5034     set< QLink >::iterator pLink = links.begin();
5035     for ( ; pLink != links.end(); ++pLink )
5036       pLink->SetContinuesFaces();
5037   }
5038   else
5039   {
5040     while ( elemIt->more() ) // loop on faces
5041     {
5042       const SMDS_MeshElement* face = elemIt->next();
5043       if ( !face->IsQuadratic() )
5044         continue;
5045       //nbElemNodeSet.insert( face->NbNodes() );
5046       int nbN = face->NbNodes()/2;
5047       vector< const QLink* > faceLinks( nbN );
5048       for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
5049       {
5050         // store QLink
5051         QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
5052         pLink = links.insert( link ).first;
5053         faceLinks[ iN ] = & *pLink;
5054         if ( !isCurved &&
5055              link.node1()->GetPosition()->GetTypeOfPosition() < 2 &&
5056              link.node2()->GetPosition()->GetTypeOfPosition() < 2 )
5057           isCurved = !link.IsStraight();
5058       }
5059       // store QFace
5060       pFace = faces.insert( QFace( faceLinks )).first;
5061       pFace->AddSelfToLinks();
5062       //hasRectFaces = ( hasRectFaces || nbN == 4 );
5063     }
5064   }
5065   if ( !isCurved )
5066     return; // no curved edges of faces
5067
5068   // 3. Compute displacement of medium nodes
5069   // ---------------------------------------
5070
5071   SMESH_MesherHelper faceHlp(*myMesh);
5072
5073   // two loops on QFaces: the first is to treat boundary links, the second is for internal ones.
5074   TopLoc_Location loc;
5075   bool checkUV;
5076   // not to treat boundary of volumic sub-mesh.
5077   int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
5078   for ( ; isInside < 2; ++isInside )
5079   {
5080     MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
5081     SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
5082     SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
5083
5084     for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
5085       if ( bool(isInside) == pFace->IsBoundary() )
5086         continue;
5087       for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
5088       {
5089         MSG( "CHAIN");
5090         // make chain of links connected via continues faces
5091         int error = ERR_OK;
5092         TChain rawChain;
5093         if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
5094         rawChain.reverse();
5095         if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
5096
5097         vector< TChain > chains;
5098         if ( error == ERR_OK ) { // chain contains continues rectangles
5099           chains.resize(1);
5100           chains[0].splice( chains[0].begin(), rawChain );
5101         }
5102         else if ( error == ERR_TRI ) {  // chain contains continues triangles
5103           TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
5104           if ( res != _OK ) { // not 'quadrangles split into triangles' in chain
5105             fixTriaNearBoundary( rawChain, *this );
5106             break;
5107           }
5108         }
5109         else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
5110           fixPrism( rawChain );
5111           break;
5112         }
5113         else {
5114           continue;
5115         }
5116         for ( size_t iC = 0; iC < chains.size(); ++iC )
5117         {
5118           TChain& chain = chains[iC];
5119           if ( chain.empty() ) continue;
5120           if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
5121             MSG("3D straight - ignore");
5122             continue;
5123           }
5124           if ( chain.front()->MediumPos() > bndPos ||
5125                chain.back() ->MediumPos() > bndPos ) {
5126             MSG("Internal chain - ignore");
5127             continue;
5128           }
5129           // mesure chain length and compute link position along the chain
5130           double chainLen = 0;
5131           vector< double > linkPos;
5132           TChain savedChain; // backup
5133           MSGBEG( "Link medium nodes: ");
5134           TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
5135           for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
5136             MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
5137             double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
5138             while ( len < numeric_limits<double>::min() ) { // remove degenerated link
5139               if ( savedChain.empty() ) savedChain = chain;
5140               link1 = chain.erase( link1 );
5141               if ( link1 == chain.end() )
5142                 break;
5143               len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
5144             }
5145             chainLen += len;
5146             linkPos.push_back( chainLen );
5147           }
5148           MSG("");
5149           if ( linkPos.size() <= 2 && savedChain.size() > 2 ) {
5150             //continue;
5151             linkPos.clear();
5152             chainLen = 0;
5153             chain = savedChain;
5154             for ( link1 = chain.begin(); link1 != chain.end(); ++link1 ) {
5155               chainLen += 1;
5156               linkPos.push_back( chainLen );
5157             }
5158           }
5159           gp_Vec move0 = chain.front()->_nodeMove;
5160           gp_Vec move1 = chain.back ()->_nodeMove;
5161
5162           TopoDS_Face face;
5163           if ( !isInside )
5164           {
5165             // compute node displacement of end links of chain in parametric space of FACE
5166             TChainLink& linkOnFace = *(++chain.begin());
5167             const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
5168             TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
5169             if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
5170             {
5171               face = TopoDS::Face( f );
5172               faceHlp.SetSubShape( face );
5173               Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
5174               //bool isStraight[2]; // commented for issue 0023118
5175               for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
5176               {
5177                 TChainLink& link = is1 ? chain.back() : chain.front();
5178                 gp_XY uvm  = faceHlp.GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV );
5179                 gp_XY uv1  = faceHlp.GetNodeUV( face, link->node1(),     nodeOnFace, &checkUV );
5180                 gp_XY uv2  = faceHlp.GetNodeUV( face, link->node2(),     nodeOnFace, &checkUV );
5181                 gp_XY uv12 = faceHlp.GetMiddleUV( surf, uv1, uv2 );
5182                 // uvMove = uvm - uv12
5183                 gp_XY uvMove = ApplyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
5184                 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
5185                 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
5186                   nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
5187                 // isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
5188                 //                                   10 * uvMove.SquareModulus());
5189               }
5190               // if ( isStraight[0] && isStraight[1] ) {
5191               //   MSG("2D straight - ignore");
5192               //   continue; // straight - no need to move nodes of internal links
5193               // }
5194
5195               // check if a chain is already fixed
5196               gp_XY uvm  = faceHlp.GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV );
5197               gp_XY uv1  = faceHlp.GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV );
5198               gp_XY uv2  = faceHlp.GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV );
5199               gp_XY uv12 = faceHlp.GetMiddleUV( surf, uv1, uv2 );
5200               if (( uvm - uv12 ).SquareModulus() > 1e-10 )
5201               {
5202                 MSG("Already fixed - ignore");
5203                 continue;
5204               }
5205             }
5206           }
5207           gp_Trsf trsf;
5208           if ( isInside || face.IsNull() )
5209           {
5210             // compute node displacement of end links in their local coord systems
5211             {
5212               TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
5213               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
5214                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
5215               move0.Transform(trsf);
5216             }
5217             {
5218               TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
5219               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
5220                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
5221               move1.Transform(trsf);
5222             }
5223           }
5224           // compute displacement of medium nodes
5225           link2 = chain.begin();
5226           link0 = link2++;
5227           link1 = link2++;
5228           for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
5229           {
5230             double r = linkPos[i] / chainLen;
5231             // displacement in local coord system
5232             gp_Vec move = (1. - r) * move0 + r * move1;
5233             if ( isInside || face.IsNull()) {
5234               // transform to global
5235               gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
5236               gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
5237               try {
5238                 gp_Vec x = x01.Normalized() + x12.Normalized();
5239                 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
5240               } catch ( Standard_Failure ) {
5241                 trsf.Invert();
5242               }
5243               move.Transform(trsf);
5244               (*link1)->Move( move, /*sum=*/false, /*is2dFixed=*/false );
5245             }
5246             else {
5247               // compute 3D displacement by 2D one
5248               Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
5249               gp_XY oldUV   = faceHlp.GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV );
5250               gp_XY newUV   = ApplyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added );
5251               gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
5252               move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
5253               if ( SMDS_FacePosition* nPos =
5254                    dynamic_cast< SMDS_FacePosition* >((*link1)->_mediumNode->GetPosition()))
5255                 nPos->SetParameters( newUV.X(), newUV.Y() );
5256 #ifdef _DEBUG_
5257               if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
5258                    move.SquareMagnitude())
5259               {
5260                 gp_XY uv0 = faceHlp.GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV );
5261                 gp_XY uv2 = faceHlp.GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV );
5262                 MSG( "TOO LONG MOVE \t" <<
5263                      "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
5264                      "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
5265                      "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
5266                      "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
5267                 uv0.SetX( uv2.X() ); // avoid warning: variable set but not used
5268               }
5269 #endif
5270               (*link1)->Move( move, /*sum=*/false, /*is2dFixed=*/true );
5271             }
5272             MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
5273                  << chain.front()->_mediumNode->GetID() <<"-"
5274                  << chain.back ()->_mediumNode->GetID() <<
5275                  " by " << move.Magnitude());
5276           }
5277         } // loop on chains of links
5278       } // loop on 2 directions of propagation from quadrangle
5279     } // loop on faces
5280   } // fix faces and/or volumes
5281
5282   // 4. Move nodes
5283   // -------------
5284
5285   TIDSortedElemSet biQuadQuas, biQuadTris, triQuadHexa, biQuadPenta;
5286   const bool toFixCentralNodes = ( myMesh->NbBiQuadQuadrangles() +
5287                                    myMesh->NbBiQuadTriangles() +
5288                                    myMesh->NbTriQuadraticHexas() +
5289                                    myMesh->NbBiQuadPrisms());
5290   double distXYZ[4];
5291   faceHlp.ToFixNodeParameters( true );
5292
5293   for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
5294     if ( pLink->IsMoved() )
5295     {
5296       gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
5297
5298       // put on surface nodes on FACE but moved in 3D (23050)
5299       if ( !pLink->IsFixedOnSurface() )
5300       {
5301         faceHlp.SetSubShape( pLink->_mediumNode->getshapeId() );
5302         if ( faceHlp.GetSubShape().ShapeType() == TopAbs_FACE )
5303         {
5304           const_cast<SMDS_MeshNode*>( pLink->_mediumNode )->setXYZ( p.X(), p.Y(), p.Z());
5305           p.Coord( distXYZ[1], distXYZ[2], distXYZ[3] );
5306           gp_XY uv( Precision::Infinite(), 0 );
5307           if ( faceHlp.CheckNodeUV( TopoDS::Face( faceHlp.GetSubShape() ), pLink->_mediumNode,
5308                                     uv, /*tol=*/pLink->Move().Modulus(), /*force=*/true, distXYZ ))
5309             p.SetCoord( distXYZ[1], distXYZ[2], distXYZ[3] );
5310         }
5311       }
5312       GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
5313
5314       // collect bi-quadratic elements
5315       if ( toFixCentralNodes )
5316       {
5317         SMDS_ElemIteratorPtr eIt = pLink->_mediumNode->GetInverseElementIterator();
5318         while ( eIt->more() )
5319         {
5320           const SMDS_MeshElement* e = eIt->next();
5321           switch( e->GetEntityType() ) {
5322           case SMDSEntity_BiQuad_Quadrangle: biQuadQuas.insert( e ); break;
5323           case SMDSEntity_BiQuad_Triangle:   biQuadTris.insert( e ); break;
5324           case SMDSEntity_TriQuad_Hexa:      triQuadHexa.insert( e ); break;
5325           case SMDSEntity_BiQuad_Penta:      biQuadPenta.insert( e ); break;
5326           default:;
5327           }
5328         }
5329       }
5330     }
5331   }
5332   // Fix positions of central nodes of bi-tri-quadratic elements
5333
5334   // treat bi-quad quadrangles
5335   {
5336     vector< const SMDS_MeshNode* > nodes( 9 );
5337     gp_XY uv[ 9 ];
5338     TIDSortedElemSet::iterator quadIt = biQuadQuas.begin();
5339     for ( ; quadIt != biQuadQuas.end(); ++quadIt )
5340     {
5341       const SMDS_MeshElement* quad = *quadIt;
5342       // nodes
5343       nodes.clear();
5344       nodes.assign( quad->begin_nodes(), quad->end_nodes() );
5345       // FACE
5346       TopoDS_Shape S = GetSubShapeByNode( nodes.back(), GetMeshDS() );
5347       if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
5348       const TopoDS_Face& F = TopoDS::Face( S );
5349       Handle( Geom_Surface ) surf = BRep_Tool::Surface( F, loc );
5350       const double tol = BRep_Tool::Tolerance( F );
5351       // UV
5352       for ( int i = 0; i < 8; ++i )
5353       {
5354         uv[ i ] = GetNodeUV( F, nodes[i], nodes[8], &checkUV );
5355         // as this method is used after mesh generation, UV of nodes is not
5356         // updated according to bending links, so we update 
5357         if ( i > 3 && nodes[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
5358           CheckNodeUV( F, nodes[i], uv[ i ], 2*tol, /*force=*/true );
5359       }
5360       AdjustByPeriod( F, uv, 8 ); // put uv[] within a period (IPAL52698)
5361       // move the central node
5362       gp_XY uvCent = calcTFI (0.5, 0.5, uv[0],uv[1],uv[2],uv[3],uv[4],uv[5],uv[6],uv[7] );
5363       gp_Pnt p = surf->Value( uvCent.X(), uvCent.Y() ).Transformed( loc );
5364       GetMeshDS()->MoveNode( nodes[8], p.X(), p.Y(), p.Z());
5365     }
5366   }
5367
5368   // treat bi-quad triangles
5369   {
5370     vector< const SMDS_MeshNode* > nodes;
5371     gp_XY uv[ 6 ];
5372     TIDSortedElemSet::iterator triIt = biQuadTris.begin();
5373     for ( ; triIt != biQuadTris.end(); ++triIt )
5374     {
5375       const SMDS_MeshElement* tria = *triIt;
5376       // FACE
5377       const TopoDS_Shape& S = GetMeshDS()->IndexToShape( tria->getshapeId() );
5378       if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
5379       const TopoDS_Face& F = TopoDS::Face( S );
5380       Handle( Geom_Surface ) surf = BRep_Tool::Surface( F, loc );
5381       const double tol = BRep_Tool::Tolerance( F );
5382
5383       // nodes
5384       nodes.assign( tria->begin_nodes(), tria->end_nodes() );
5385       // UV
5386       bool uvOK = true, badTria = false;
5387       for ( int i = 0; i < 6; ++i )
5388       {
5389         uv[ i ] = GetNodeUV( F, nodes[i], nodes[(i+1)%3], &uvOK );
5390         // as this method is used after mesh generation, UV of nodes is not
5391         // updated according to bending links, so we update 
5392         if ( nodes[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
5393           CheckNodeUV( F, nodes[i], uv[ i ], 2*tol, /*force=*/true );
5394       }
5395
5396       // move the central node
5397       gp_Pnt p;
5398       if ( !uvOK || badTria )
5399       {
5400         p = ( SMESH_TNodeXYZ( nodes[3] ) +
5401               SMESH_TNodeXYZ( nodes[4] ) +
5402               SMESH_TNodeXYZ( nodes[5] )) / 3;
5403       }
5404       else
5405       {
5406         AdjustByPeriod( F, uv, 6 ); // put uv[] within a period (IPAL52698)
5407         gp_XY uvCent = GetCenterUV( uv[0], uv[1], uv[2], uv[3], uv[4], uv[5], &badTria );
5408         p = surf->Value( uvCent.X(), uvCent.Y() ).Transformed( loc );
5409       }
5410       GetMeshDS()->MoveNode( tria->GetNode(6), p.X(), p.Y(), p.Z() );
5411     }
5412   }
5413
5414   // treat tri-quadratic hexahedra
5415   {
5416     SMDS_VolumeTool volExp;
5417     TIDSortedElemSet::iterator hexIt = triQuadHexa.begin();
5418     for ( ; hexIt != triQuadHexa.end(); ++hexIt )
5419     {
5420       volExp.Set( *hexIt, /*ignoreCentralNodes=*/false );
5421
5422       // fix nodes central in sides
5423       for ( int iQuad = 0; iQuad < volExp.NbFaces(); ++iQuad )
5424       {
5425         const SMDS_MeshNode** quadNodes = volExp.GetFaceNodes( iQuad );
5426         if ( quadNodes[8]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
5427         {
5428           gp_XYZ p = calcTFI( 0.5, 0.5,
5429                               SMESH_TNodeXYZ( quadNodes[0] ), SMESH_TNodeXYZ( quadNodes[2] ),
5430                               SMESH_TNodeXYZ( quadNodes[4] ), SMESH_TNodeXYZ( quadNodes[6] ),
5431                               SMESH_TNodeXYZ( quadNodes[1] ), SMESH_TNodeXYZ( quadNodes[3] ),
5432                               SMESH_TNodeXYZ( quadNodes[5] ), SMESH_TNodeXYZ( quadNodes[7] ));
5433           GetMeshDS()->MoveNode( quadNodes[8], p.X(), p.Y(), p.Z());
5434         }
5435       }
5436
5437       // fix the volume central node
5438       vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
5439       const SMDS_MeshNode** hexNodes = volExp.GetNodes();
5440
5441       pointsOnShapes[ SMESH_Block::ID_V000 ] = SMESH_TNodeXYZ( hexNodes[ 0 ] );
5442       pointsOnShapes[ SMESH_Block::ID_V100 ] = SMESH_TNodeXYZ( hexNodes[ 3 ] );
5443       pointsOnShapes[ SMESH_Block::ID_V010 ] = SMESH_TNodeXYZ( hexNodes[ 1 ] );
5444       pointsOnShapes[ SMESH_Block::ID_V110 ] = SMESH_TNodeXYZ( hexNodes[ 2 ] );
5445       pointsOnShapes[ SMESH_Block::ID_V001 ] = SMESH_TNodeXYZ( hexNodes[ 4 ] );
5446       pointsOnShapes[ SMESH_Block::ID_V101 ] = SMESH_TNodeXYZ( hexNodes[ 7 ] );
5447       pointsOnShapes[ SMESH_Block::ID_V011 ] = SMESH_TNodeXYZ( hexNodes[ 5 ] );
5448       pointsOnShapes[ SMESH_Block::ID_V111 ] = SMESH_TNodeXYZ( hexNodes[ 6 ] );
5449
5450       pointsOnShapes[ SMESH_Block::ID_Ex00 ] = SMESH_TNodeXYZ( hexNodes[ 11 ] );
5451       pointsOnShapes[ SMESH_Block::ID_Ex10 ] = SMESH_TNodeXYZ( hexNodes[  9 ] );
5452       pointsOnShapes[ SMESH_Block::ID_E0y0 ] = SMESH_TNodeXYZ( hexNodes[  8 ] );
5453       pointsOnShapes[ SMESH_Block::ID_E1y0 ] = SMESH_TNodeXYZ( hexNodes[ 10 ] );
5454       pointsOnShapes[ SMESH_Block::ID_Ex01 ] = SMESH_TNodeXYZ( hexNodes[ 15 ] );
5455       pointsOnShapes[ SMESH_Block::ID_Ex11 ] = SMESH_TNodeXYZ( hexNodes[ 13 ] );
5456       pointsOnShapes[ SMESH_Block::ID_E0y1 ] = SMESH_TNodeXYZ( hexNodes[ 12 ] );
5457       pointsOnShapes[ SMESH_Block::ID_E1y1 ] = SMESH_TNodeXYZ( hexNodes[ 14 ] );
5458       pointsOnShapes[ SMESH_Block::ID_E00z ] = SMESH_TNodeXYZ( hexNodes[ 16 ] );    
5459       pointsOnShapes[ SMESH_Block::ID_E10z ] = SMESH_TNodeXYZ( hexNodes[ 19 ] );    
5460       pointsOnShapes[ SMESH_Block::ID_E01z ] = SMESH_TNodeXYZ( hexNodes[ 17 ] );    
5461       pointsOnShapes[ SMESH_Block::ID_E11z ] = SMESH_TNodeXYZ( hexNodes[ 18 ] );
5462
5463       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = SMESH_TNodeXYZ( hexNodes[ 20 ] );
5464       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = SMESH_TNodeXYZ( hexNodes[ 25 ] );
5465       pointsOnShapes[ SMESH_Block::ID_Fx0z ] = SMESH_TNodeXYZ( hexNodes[ 21 ] );   
5466       pointsOnShapes[ SMESH_Block::ID_Fx1z ] = SMESH_TNodeXYZ( hexNodes[ 23 ] );   
5467       pointsOnShapes[ SMESH_Block::ID_F0yz ] = SMESH_TNodeXYZ( hexNodes[ 24 ] );    
5468       pointsOnShapes[ SMESH_Block::ID_F1yz ] = SMESH_TNodeXYZ( hexNodes[ 22 ] );
5469
5470       gp_XYZ nCenterParams(0.5, 0.5, 0.5), nCenterCoords;
5471       SMESH_Block::ShellPoint( nCenterParams, pointsOnShapes, nCenterCoords );
5472       GetMeshDS()->MoveNode( hexNodes[26],
5473                              nCenterCoords.X(), nCenterCoords.Y(), nCenterCoords.Z());
5474     }
5475   }
5476   // treat tri-quadratic hexahedra
5477   {
5478     SMDS_VolumeTool volExp;
5479     TIDSortedElemSet::iterator pentIt = biQuadPenta.begin();
5480     for ( ; pentIt != biQuadPenta.end(); ++pentIt )
5481     {
5482       MESSAGE("---");
5483       volExp.Set( *pentIt, /*ignoreCentralNodes=*/false );
5484     }
5485   }
5486 #ifdef _DEBUG_
5487   // avoid warning: defined but not used operator<<()
5488   SMESH_Comment() << *links.begin() << *faces.begin();
5489 #endif
5490 }
5491
5492 //================================================================================
5493 /*!
5494  * \brief DEBUG
5495  */
5496 //================================================================================
5497
5498 void SMESH_MesherHelper::WriteShape(const TopoDS_Shape& s)
5499 {
5500   const char* name = "/tmp/shape.brep";
5501   BRepTools::Write( s, name );
5502 #ifdef _DEBUG_
5503   std::cout << name << std::endl;
5504 #endif
5505 }
5506