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