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