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