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