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