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