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