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